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 #include <sys/types.h>
34 # Print `objects` on the standard output (`stdout`).
35 protected fun printn
(objects
: Object...)
37 stdout
.write
(objects
.to_s
)
40 # Print an `object` on the standard output (`stdout`) and add a newline.
41 protected fun print
(object
: Object)
43 stdout
.write
(object
.to_s
)
47 # Read a character from the standard input (`stdin`).
48 protected fun getc
: Char
50 return stdin
.read_char
.ascii
53 # Read a line from the standard input (`stdin`).
54 protected fun gets
: String
56 return stdin
.read_line
59 # Return the working (current) directory
60 protected fun getcwd
: String do return file_getcwd
.to_s
61 private fun file_getcwd
: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"
64 # File Abstract Stream
65 abstract class FStream
67 # The path of the file.
68 var path
: nullable String = null
71 var _file
: nullable NativeFile = null
73 fun file_stat
: FileStat
74 do return _file
.file_stat
end
83 # Open the same file again.
84 # The original path is reused, therefore the reopened file can be a different file.
88 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
96 var i
= _file
.io_close
100 redef fun fill_buffer
102 var nb
= _file
.io_read
(_buffer
.items
, _buffer
.capacity
)
112 redef var end_reached
: Bool = false
114 # Open the file at `path` for reading.
115 init open
(path
: String)
119 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
120 assert not _file
.address_is_null
else
121 print
"Error: Opening file at '{path}' failed with '{sys.errno.strerror}'"
126 private init without_file
do end
137 write_native
(s
.to_cstring
, s
.length
)
140 redef fun is_writable
do return _writable
144 var i
= _file
.io_close
148 # Is the file open in write mode
151 # Write `len` bytes from `native`.
152 private fun write_native
(native
: NativeString, len
: Int)
155 var err
= _file
.io_write
(native
, len
)
158 printn
("Problem in writing : ", err
, " ", len
, "\n")
162 # Open the file at `path` for writing.
163 init open
(path
: String)
165 _file
= new NativeFile.io_open_write
(path
.to_cstring
)
166 assert not _file
.address_is_null
else
167 print
"Error: Opening file at '{path}' failed with '{sys.errno.strerror}'"
174 private init without_file
do end
177 ###############################################################################
181 super PollableIStream
184 _file
= new NativeFile.native_stdin
189 redef fun poll_in
: Bool is extern "file_stdin_poll_in"
195 _file
= new NativeFile.native_stdout
204 _file
= new NativeFile.native_stderr
210 ###############################################################################
212 redef class Streamable
213 # Like `write_to` but take care of creating the file
214 fun write_to_file
(filepath
: String)
216 var stream
= new OFStream.open
(filepath
)
223 # return true if a file with this names exists
224 fun file_exists
: Bool do return to_cstring
.file_exists
226 # The status of a file. see POSIX stat(2).
227 fun file_stat
: FileStat do return to_cstring
.file_stat
229 # The status of a file or of a symlink. see POSIX lstat(2).
230 fun file_lstat
: FileStat do return to_cstring
.file_lstat
232 # Remove a file, return true if success
233 fun file_delete
: Bool do return to_cstring
.file_delete
235 # Copy content of file at `self` to `dest`
236 fun file_copy_to
(dest
: String)
238 var input
= new IFStream.open
(self)
239 var output
= new OFStream.open
(dest
)
241 while not input
.eof
do
242 var buffer
= input
.read
(1024)
250 # Remove the trailing extension `ext`.
252 # `ext` usually starts with a dot but could be anything.
254 # assert "file.txt".strip_extension(".txt") == "file"
255 # assert "file.txt".strip_extension("le.txt") == "fi"
256 # assert "file.txt".strip_extension("xt") == "file.t"
258 # if `ext` is not present, `self` is returned unmodified.
260 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
261 fun strip_extension
(ext
: String): String
263 if has_suffix
(ext
) then
264 return substring
(0, length
- ext
.length
)
269 # Extract the basename of a path and remove the extension
271 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
272 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
273 # assert "path/to".basename(".ext") == "to"
274 # assert "path/to/".basename(".ext") == "to"
275 # assert "path".basename("") == "path"
276 # assert "/path".basename("") == "path"
277 # assert "/".basename("") == "/"
278 # assert "".basename("") == ""
279 fun basename
(ext
: String): String
281 var l
= length
- 1 # Index of the last char
282 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
283 if l
== 0 then return "/"
284 var pos
= chars
.last_index_of_from
('/', l
)
287 n
= substring
(pos
+1, l-pos
)
289 return n
.strip_extension
(ext
)
292 # Extract the dirname of a path
294 # assert "/path/to/a_file.ext".dirname == "/path/to"
295 # assert "path/to/a_file.ext".dirname == "path/to"
296 # assert "path/to".dirname == "path"
297 # assert "path/to/".dirname == "path"
298 # assert "path".dirname == "."
299 # assert "/path".dirname == "/"
300 # assert "/".dirname == "/"
301 # assert "".dirname == "."
304 var l
= length
- 1 # Index of the last char
305 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
306 var pos
= chars
.last_index_of_from
('/', l
)
308 return substring
(0, pos
)
309 else if pos
== 0 then
316 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
317 fun realpath
: String do
318 var cs
= to_cstring
.file_realpath
319 var res
= cs
.to_s_with_copy
320 # cs.free_malloc # FIXME memory leak
324 # Simplify a file path by remove useless ".", removing "//", and resolving ".."
325 # ".." are not resolved if they start the path
326 # starting "/" is not removed
327 # trainling "/" is removed
329 # Note that the method only wonrk on the string:
330 # * no I/O access is performed
331 # * the validity of the path is not checked
333 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
334 # assert "../dir/file".simplify_path == "../dir/file"
335 # assert "dir/../../".simplify_path == ".."
336 # assert "dir/..".simplify_path == "."
337 # assert "//absolute//path/".simplify_path == "/absolute/path"
338 fun simplify_path
: String
340 var a
= self.split_with
("/")
341 var a2
= new Array[String]
343 if x
== "." then continue
344 if x
== "" and not a2
.is_empty
then continue
345 if x
== ".." and not a2
.is_empty
and a2
.last
!= ".." then
351 if a2
.is_empty
then return "."
355 # Correctly join two path using the directory separator.
357 # Using a standard "{self}/{path}" does not work when `self` is the empty string.
358 # This method ensure that the join is valid.
360 # assert "hello".join_path("world") == "hello/world"
361 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
362 # assert "".join_path("world") == "world"
363 # assert "/hello".join_path("/world") == "/world"
365 # Note: you may want to use `simplify_path` on the result
367 # Note: I you want to join a great number of path, you can write
369 # [p1, p2, p3, p4].join("/")
370 fun join_path
(path
: String): String
372 if path
.is_empty
then return self
373 if self.is_empty
then return path
374 if path
.chars
[0] == '/' then return path
375 return "{self}/{path}"
378 # Create a directory (and all intermediate directories if needed)
381 var dirs
= self.split_with
("/")
382 var path
= new FlatBuffer
383 if dirs
.is_empty
then return
384 if dirs
[0].is_empty
then
385 # it was a starting /
389 if d
.is_empty
then continue
392 path
.to_s
.to_cstring
.file_mkdir
396 # Change the current working directory
399 # assert getcwd == "/etc"
401 # assert getcwd == "/"
404 fun chdir
do to_cstring
.file_chdir
406 # Return right-most extension (without the dot)
408 # Only the last extension is returned.
409 # There is no special case for combined extensions.
411 # assert "file.txt".file_extension == "txt"
412 # assert "file.tar.gz".file_extension == "gz"
414 # For file without extension, `null` is returned.
415 # Hoever, for trailing dot, `""` is returned.
417 # assert "file".file_extension == null
418 # assert "file.".file_extension == ""
420 # The starting dot of hidden files is never considered.
422 # assert ".file.txt".file_extension == "txt"
423 # assert ".file".file_extension == null
424 fun file_extension
: nullable String
426 var last_slash
= chars
.last_index_of
('.')
427 if last_slash
> 0 then
428 return substring
( last_slash
+1, length
)
434 # returns files contained within the directory represented by self
435 fun files
: Set[ String ] is extern import HashSet[String], HashSet[String].add
, NativeString.to_s
, String.to_cstring
, HashSet[String].as(Set[String]) `{
439 dir_path = String_to_cstring( recv );
440 if ((dir = opendir(dir_path)) == NULL)
447 HashSet_of_String results;
451 results = new_HashSet_of_String();
453 while ( ( de = readdir( dir ) ) != NULL )
454 if ( strcmp( de->d_name, ".." ) != 0 &&
455 strcmp( de->d_name, "." ) != 0 )
457 file_name = NativeString_to_s( strdup( de->d_name ) );
458 HashSet_of_String_add( results, file_name );
462 return HashSet_of_String_as_Set_of_String( results );
467 redef class NativeString
468 private fun file_exists
: Bool is extern "string_NativeString_NativeString_file_exists_0"
469 private fun file_stat
: FileStat is extern "string_NativeString_NativeString_file_stat_0"
470 private fun file_lstat
: FileStat `{
471 struct stat* stat_element;
473 stat_element = malloc(sizeof(struct stat));
474 res = lstat(recv, stat_element);
475 if (res == -1) return NULL;
478 private fun file_mkdir
: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
479 private fun file_delete
: Bool is extern "string_NativeString_NativeString_file_delete_0"
480 private fun file_chdir
is extern "string_NativeString_NativeString_file_chdir_0"
481 private fun file_realpath
: NativeString is extern "file_NativeString_realpath"
484 # This class is system dependent ... must reify the vfs
485 extern class FileStat `{ struct stat * `}
486 # Returns the permission bits of file
487 fun mode: Int is extern "file_FileStat_FileStat_mode_0"
488 # Returns the last access time
489 fun atime: Int is extern "file_FileStat_FileStat_atime_0"
490 # Returns the last status change time
491 fun ctime: Int is extern "file_FileStat_FileStat_ctime_0"
492 # Returns the last modification time
493 fun mtime: Int is extern "file_FileStat_FileStat_mtime_0"
495 fun size: Int is extern "file_FileStat_FileStat_size_0"
497 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
498 fun is_reg: Bool `{ return S_ISREG(recv->st_mode); `}
499 # Returns true if it is a directory
500 fun is_dir
: Bool `{ return S_ISDIR(recv->st_mode); `}
501 # Returns true if it is a character device
502 fun is_chr: Bool `{ return S_ISCHR(recv->st_mode); `}
503 # Returns true if it is a block device
504 fun is_blk
: Bool `{ return S_ISBLK(recv->st_mode); `}
505 # Returns true if the type is fifo
506 fun is_fifo: Bool `{ return S_ISFIFO(recv->st_mode); `}
507 # Returns true if the type is a link
508 fun is_lnk
: Bool `{ return S_ISLNK(recv->st_mode); `}
509 # Returns true if the type is a socket
510 fun is_sock: Bool `{ return S_ISSOCK(recv->st_mode); `}
513 # Instance of this class are standard FILE * pointers
514 private extern class NativeFile `{ FILE* `}
515 fun io_read(buf: NativeString, len: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
516 fun io_write(buf: NativeString, len: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
517 fun io_close: Int is extern "file_NativeFile_NativeFile_io_close_0"
518 fun file_stat: FileStat is extern "file_NativeFile_NativeFile_file_stat_0"
520 new io_open_read(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
521 new io_open_write(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
522 new native_stdin is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
523 new native_stdout is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
524 new native_stderr is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
528 fun stdin: Stdin do return once new Stdin
531 fun stdout: OFStream do return once new Stdout
533 # Standard output for error.
534 fun stderr: OFStream do return once new Stderr