1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 # Copyright 2008 Floréal Morandat <morandat@lirmm.fr>
5 # Copyright 2008 Jean-Sébastien Gélinas <calestar@gmail.com>
7 # This file is free software, which comes along with NIT. This software is
8 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
10 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
11 # is kept unaltered, and a notification of the changes is added.
12 # You are allowed to redistribute it and sell it, alone or is a part of
15 # File manipulations (create, read, write, etc.)
26 # Print `objects` on the standard output (`stdout`).
27 protected fun printn
(objects
: Object...)
29 stdout
.write
(objects
.to_s
)
32 # Print an `object` on the standard output (`stdout`) and add a newline.
33 protected fun print
(object
: Object)
35 stdout
.write
(object
.to_s
)
39 # Read a character from the standard input (`stdin`).
40 protected fun getc
: Char
42 return stdin
.read_char
.ascii
45 # Read a line from the standard input (`stdin`).
46 protected fun gets
: String
48 return stdin
.read_line
51 # Return the working (current) directory
52 protected fun getcwd
: String do return file_getcwd
.to_s
53 private fun file_getcwd
: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"
56 # File Abstract Stream
57 abstract class FStream
59 # The path of the file.
60 readable var _path
: nullable String = null
63 var _file
: nullable NativeFile = null
65 fun file_stat
: FileStat
66 do return _file
.file_stat
end
75 # Open the same file again.
76 # The original path is reused, therefore the reopened file can be a different file.
80 _file
= new NativeFile.io_open_read
(_path
.to_cstring
)
88 var i
= _file
.io_close
94 var nb
= _file
.io_read
(_buffer
._items
, _buffer
._capacity
)
104 redef readable var _end_reached
: Bool = false
106 # Open the file at `path` for reading.
107 init open
(path
: String)
111 _file
= new NativeFile.io_open_read
(_path
.to_cstring
)
112 assert cant_open_file
: _file
!= null
116 private init without_file
do end
127 write_native
(s
.to_cstring
, s
.length
)
130 redef fun is_writable
do return _writable
134 var i
= _file
.io_close
138 # Is the file open in write mode
141 # Write `len` bytes from `native`.
142 private fun write_native
(native
: NativeString, len
: Int)
145 var err
= _file
.io_write
(native
, len
)
148 printn
("Problem in writing : ", err
, " ", len
, "\n")
152 # Open the file at `path` for writing.
153 init open
(path
: String)
155 _file
= new NativeFile.io_open_write
(path
.to_cstring
)
156 assert cant_open_file
: _file
!= null
162 private init without_file
do end
165 ###############################################################################
170 _file
= new NativeFile.native_stdin
175 # Is these something to read? (non blocking)
176 # FIXME: should be generalized
177 fun poll_in
: Bool is extern "file_stdin_poll_in"
183 _file
= new NativeFile.native_stdout
184 _path
= "/dev/stdout"
192 _file
= new NativeFile.native_stderr
193 _path
= "/dev/stderr"
198 ###############################################################################
201 # return true if a file with this names exists
202 fun file_exists
: Bool do return to_cstring
.file_exists
204 fun file_stat
: FileStat do return to_cstring
.file_stat
205 fun file_lstat
: FileStat do return to_cstring
.file_lstat
207 # Remove a file, return true if success
208 fun file_delete
: Bool do return to_cstring
.file_delete
210 # remove the trailing extension "ext"
211 fun strip_extension
(ext
: String): String
213 if has_suffix
(ext
) then
214 return substring
(0, length
- ext
.length
)
219 # Extract the basename of a path and remove the extension
220 fun basename
(ext
: String): String
222 var pos
= last_index_of_from
('/', _length
- 1)
225 n
= substring_from
(pos
+1)
227 return n
.strip_extension
(ext
)
230 # Extract the dirname of a path
232 # assert "/path/to/a_file.ext".dirname == "/path/to"
233 # assert "path/to/a_file.ext".dirname == "path/to"
234 # assert "path/to".dirname == "path"
235 # assert "path/to/".dirname == "path"
236 # assert "path".dirname == "."
237 # assert "/path".dirname == "/"
238 # assert "/".dirname == "/"
239 # assert "".dirname == "."
242 var l
= _length
- 1 # Index of the last char
243 if l
> 0 and self[l
] == '/' then l
-= 1 # remove trailing `/`
244 var pos
= last_index_of_from
('/', l
)
246 return substring
(0, pos
)
247 else if pos
== 0 then
254 # Simplify a file path by remove useless ".", removing "//", and resolving ".."
255 # ".." are not resolved if they start the path
256 # starting "/" is not removed
257 # trainling "/" is removed
259 # Note that the method only wonrk on the string:
260 # * no I/O access is performed
261 # * the validity of the path is not checked
263 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
264 # assert "../dir/file".simplify_path == "../dir/file"
265 # assert "dir/../../".simplify_path == ".."
266 # assert "//absolute//path/".simplify_path == "/absolute/path"
267 fun simplify_path
: String
269 var a
= self.split_with
("/")
270 var a2
= new Array[String]
272 if x
== "." then continue
273 if x
== "" and not a2
.is_empty
then continue
274 if x
== ".." and not a2
.is_empty
and a2
.last
!= ".." then
283 # Correctly join two path using the directory separator.
285 # Using a standard "{self}/{path}" does not work when `self` is the empty string.
286 # This method ensure that the join is valid.
288 # assert "hello".join_path("world") == "hello/world"
289 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
290 # assert "".join_path("world") == "world"
291 # assert "/hello".join_path("/world") == "/world"
293 # Note: you may want to use `simplify_path` on the result
295 # Note: I you want to join a great number of path, you can write
297 # [p1, p2, p3, p4].join("/")
298 fun join_path
(path
: String): String
300 if path
.is_empty
then return self
301 if self.is_empty
then return path
302 if path
[0] == '/' then return path
303 return "{self}/{path}"
306 # Create a directory (and all intermediate directories if needed)
309 var dirs
= self.split_with
("/")
310 var path
= new Buffer
311 if dirs
.is_empty
then return
312 if dirs
[0].is_empty
then
313 # it was a starting /
317 if d
.is_empty
then continue
320 path
.to_s
.to_cstring
.file_mkdir
324 # Change the current working directory
327 # assert getcwd == "/etc"
329 # assert getcwd == "/"
332 fun chdir
do to_cstring
.file_chdir
334 # Return right-most extension (without the dot)
335 fun file_extension
: nullable String
337 var last_slash
= last_index_of
('.')
338 if last_slash
>= 0 then
339 return substring
( last_slash
+1, length
)
345 # returns files contained within the directory represented by self
346 fun files
: Set[ String ] is extern import HashSet, HashSet::add
, NativeString::to_s
, String::to_cstring
, HashSet[String] as( Set[String] ), String as( Object )
349 redef class NativeString
350 private fun file_exists
: Bool is extern "string_NativeString_NativeString_file_exists_0"
351 private fun file_stat
: FileStat is extern "string_NativeString_NativeString_file_stat_0"
352 private fun file_lstat
: FileStat `{
353 struct stat* stat_element;
355 stat_element = malloc(sizeof(struct stat));
356 res = lstat(recv, stat_element);
357 if (res == -1) return NULL;
360 private fun file_mkdir
: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
361 private fun file_delete
: Bool is extern "string_NativeString_NativeString_file_delete_0"
362 private fun file_chdir
is extern "string_NativeString_NativeString_file_chdir_0"
365 # This class is system dependent ... must reify the vfs
366 extern class FileStat `{ struct stat * `}
367 # Returns the permission bits of file
368 fun mode: Int is extern "file_FileStat_FileStat_mode_0"
369 # Returns the last access time
370 fun atime: Int is extern "file_FileStat_FileStat_atime_0"
371 # Returns the last status change time
372 fun ctime: Int is extern "file_FileStat_FileStat_ctime_0"
373 # Returns the last modification time
374 fun mtime: Int is extern "file_FileStat_FileStat_mtime_0"
376 fun size: Int is extern "file_FileStat_FileStat_size_0"
378 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
379 fun is_reg: Bool `{ return S_ISREG(recv->st_mode); `}
380 # Returns true if it is a directory
381 fun is_dir
: Bool `{ return S_ISDIR(recv->st_mode); `}
382 # Returns true if it is a character device
383 fun is_chr: Bool `{ return S_ISCHR(recv->st_mode); `}
384 # Returns true if it is a block device
385 fun is_blk
: Bool `{ return S_ISBLK(recv->st_mode); `}
386 # Returns true if the type is fifo
387 fun is_fifo: Bool `{ return S_ISFIFO(recv->st_mode); `}
388 # Returns true if the type is a link
389 fun is_lnk
: Bool `{ return S_ISLNK(recv->st_mode); `}
390 # Returns true if the type is a socket
391 fun is_sock: Bool `{ return S_ISSOCK(recv->st_mode); `}
394 # Instance of this class are standard FILE * pointers
395 private extern NativeFile
396 fun io_read
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
397 fun io_write
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
398 fun io_close
: Int is extern "file_NativeFile_NativeFile_io_close_0"
399 fun file_stat
: FileStat is extern "file_NativeFile_NativeFile_file_stat_0"
401 new io_open_read
(path
: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
402 new io_open_write
(path
: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
403 new native_stdin
is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
404 new native_stdout
is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
405 new native_stderr
is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
409 fun stdin
: Stdin do return once
new Stdin
412 fun stdout
: OFStream do return once
new Stdout
414 # Standard output for error.
415 fun stderr
: OFStream do return once
new Stderr