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.)
19 intrude import text
::ropes
27 #include <sys/types.h>
35 # `Stream` used to interact with a File or FileDescriptor
36 abstract class FileStream
38 # The path of the file.
39 var path
: nullable String = null
42 private var file
: nullable NativeFile = null
44 # The status of a file. see POSIX stat(2).
46 # var f = new FileReader.open("/etc/issue")
47 # assert f.file_stat.is_file
49 # Return null in case of error
50 fun file_stat
: nullable FileStat
52 var stat
= _file
.file_stat
53 if stat
.address_is_null
then return null
54 return new FileStat(stat
)
57 # File descriptor of this file
58 fun fd
: Int do return _file
.fileno
62 if _file
== null then return
63 if _file
.address_is_null
then
64 if last_error
!= null then return
65 last_error
= new IOError("Cannot close unopened file")
68 var i
= _file
.io_close
70 last_error
= new IOError("Close failed due to error {sys.errno.strerror}")
75 # Sets the buffering mode for the current FileStream
77 # If the buf_size is <= 0, its value will be 512 by default
79 # The mode is any of the buffer_mode enumeration in `Sys`:
81 # * `buffer_mode_full`
82 # * `buffer_mode_line`
83 # * `buffer_mode_none`
84 fun set_buffering_mode
(buf_size
, mode
: Int) do
85 if buf_size
<= 0 then buf_size
= 512
86 if _file
.set_buffering_type
(buf_size
, mode
) != 0 then
87 last_error
= new IOError("Error while changing buffering type for FileStream, returned error {sys.errno.strerror}")
92 # `Stream` that can read from a File
99 # Open the same file again.
100 # The original path is reused, therefore the reopened file can be a different file.
102 # var f = new FileReader.open("/etc/issue")
103 # var l = f.read_line
105 # assert l == f.read_line
108 if not eof
and not _file
.address_is_null
then close
110 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
111 if _file
.address_is_null
then
112 last_error
= new IOError("Cannot open `{path.as(not null)}`: {sys.errno.strerror}")
127 redef fun fill_buffer
129 var nb
= _file
.io_read
(_buffer
, _buffer_capacity
)
130 if last_error
== null and _file
.ferror
then
131 last_error
= new IOError("Cannot read `{path.as(not null)}`: {sys.errno.strerror}")
143 redef var end_reached
= false
145 # Open the file at `path` for reading.
147 # var f = new FileReader.open("/etc/issue")
148 # assert not f.end_reached
151 # In case of error, `last_error` is set
153 # f = new FileReader.open("/fail/does not/exist")
154 # assert f.end_reached
155 # assert f.last_error != null
156 init open
(path
: String)
160 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
161 if _file
.address_is_null
then
162 last_error
= new IOError("Cannot open `{path}`: {sys.errno.strerror}")
167 # Creates a new File stream from a file descriptor
169 # This is a low-level method.
170 init from_fd
(fd
: Int) do
173 _file
= fd
.fd_to_stream
(read_only
)
174 if _file
.address_is_null
then
175 last_error
= new IOError("Error: Converting fd {fd} to stream failed with '{sys.errno.strerror}'")
182 var res
= native_poll_in
(fd
)
184 last_error
= new IOError(errno
.to_s
)
189 private fun native_poll_in
(fd
: Int): Int `{
190 struct pollfd fds = {fd, POLLIN, 0};
191 return poll(&fds, 1, 0);
195 # `Stream` that can write to a File
200 redef fun write_bytes
(s
) do
201 if last_error
!= null then return
202 if not _is_writable
then
203 last_error
= new IOError("cannot write to non-writable stream")
206 write_native
(s
.items
, 0, s
.length
)
211 if last_error
!= null then return
212 if not _is_writable
then
213 last_error
= new IOError("cannot write to non-writable stream")
216 s
.write_native_to
(self)
219 redef fun write_byte
(value
)
221 if last_error
!= null then return
222 if not _is_writable
then
223 last_error
= new IOError("Cannot write to non-writable stream")
226 if _file
.address_is_null
then
227 last_error
= new IOError("Writing on a null stream")
232 var err
= _file
.write_byte
(value
)
235 last_error
= new IOError("Problem writing a byte: {err}")
244 redef var is_writable
= false
246 # Write `len` bytes from `native`.
247 private fun write_native
(native
: NativeString, from
, len
: Int)
249 if last_error
!= null then return
250 if not _is_writable
then
251 last_error
= new IOError("Cannot write to non-writable stream")
254 if _file
.address_is_null
then
255 last_error
= new IOError("Writing on a null stream")
259 var err
= _file
.io_write
(native
, from
, len
)
262 last_error
= new IOError("Problem in writing : {err} {len} \n")
266 # Open the file at `path` for writing.
267 init open
(path
: String)
269 _file
= new NativeFile.io_open_write
(path
.to_cstring
)
272 if _file
.address_is_null
then
273 last_error
= new IOError("Cannot open `{path}`: {sys.errno.strerror}")
278 # Creates a new File stream from a file descriptor
279 init from_fd
(fd
: Int) do
281 _file
= fd
.fd_to_stream
(wipe_write
)
283 if _file
.address_is_null
then
284 last_error
= new IOError("Error: Opening stream from file descriptor {fd} failed with '{sys.errno.strerror}'")
291 # Creates a file stream from a file descriptor `fd` using the file access `mode`.
293 # NOTE: The `mode` specified must be compatible with the one used in the file descriptor.
294 private fun fd_to_stream
(mode
: NativeString): NativeFile `{
295 return fdopen(self, mode);
299 # Constant for read-only file streams
300 private fun read_only
: NativeString do return once
"r".to_cstring
302 # Constant for write-only file streams
304 # If a stream is opened on a file with this method,
305 # it will wipe the previous file if any.
306 # Else, it will create the file.
307 private fun wipe_write
: NativeString do return once
"w".to_cstring
309 ###############################################################################
311 # Standard input stream.
313 # The class of the default value of `sys.stdin`.
318 _file
= new NativeFile.native_stdin
324 # Standard output stream.
326 # The class of the default value of `sys.stdout`.
330 _file
= new NativeFile.native_stdout
333 set_buffering_mode
(256, sys
.buffer_mode_line
)
337 # Standard error stream.
339 # The class of the default value of `sys.stderr`.
343 _file
= new NativeFile.native_stderr
349 ###############################################################################
352 # Like `write_to` but take care of creating the file
353 fun write_to_file
(filepath
: String)
355 var stream
= new FileWriter.open
(filepath
)
361 # Utility class to access file system services.
363 # Usually created with `Text::to_path`.
365 # `Path` objects does not necessarily represent existing files in a file system.
366 # They are sate-less objects that efficiently represent path information.
367 # They also provide an easy to use API on file-system services and are used to store their error status (see `last_error`)
370 private var path
: String
373 redef fun to_s
do return path
375 # Short name of the file at `to_s`
378 # var path = "/tmp/somefile".to_path
379 # assert path.filename == "somefile"
382 # The result does not depend of the file system, thus is cached for efficiency.
383 var filename
: String = path
.basename
is lazy
385 # The path simplified by removing useless `.`, removing `//`, and resolving `..`
388 # var path = "somedir/./tmp/../somefile".to_path
389 # assert path.simplified.to_s == "somedir/somefile"
392 # See `String:simplify_path` for details.
394 # The result does not depend of the file system, thus is cached for efficiency.
395 var simplified
: Path is lazy
do
396 var res
= path
.simplify_path
.to_path
401 # Return the directory part of the path.
404 # var path = "/foo/bar/baz".to_path
405 # assert path.dir.to_s == "/foo/bar"
406 # assert path.dir.dir.to_s == "/foo"
407 # assert path.dir.dir.dir.to_s == "/"
410 # See `String:dirname` for details.
412 # The result does not depend of the file system, thus is cached for efficiency.
413 var dir
: Path is lazy
do
414 return path
.dirname
.to_path
417 # Last error produced by I/O operations.
420 # var path = "/does/not/exists".to_path
421 # assert path.last_error == null
423 # assert path.last_error != null
426 # Since `Path` objects are stateless, `last_error` is reset on most operations and reflect its status.
427 var last_error
: nullable IOError = null is writable
429 # Does the file at `path` exists?
431 # If the file does not exists, `last_error` is set to the information.
432 fun exists
: Bool do return stat
!= null
434 # Information on the file at `self` following symbolic links
436 # Returns `null` if there is no file at `self`.
437 # `last_error` is updated to contains the error information on error, and null on success.
439 # assert "/etc/".to_path.stat.is_dir
440 # assert "/etc/issue".to_path.stat.is_file
441 # assert "/fail/does not/exist".to_path.stat == null
444 # var p = "/tmp/".to_path
446 # if stat != null then # Does `p` exist?
447 # print "It's size is {stat.size}"
448 # if stat.is_dir then print "It's a directory"
450 # print p.last_error.to_s
453 fun stat
: nullable FileStat
455 var stat
= path
.to_cstring
.file_stat
456 if stat
.address_is_null
then
457 last_error
= new IOError("Cannot open `{path}`: {sys.errno.strerror}")
461 return new FileStat(stat
)
464 # Information on the file or link at `self`
466 # Do not follow symbolic links.
467 fun link_stat
: nullable FileStat
469 var stat
= path
.to_cstring
.file_lstat
470 if stat
.address_is_null
then
471 last_error
= new IOError("Cannot open `{path}`: {sys.errno.strerror}")
475 return new FileStat(stat
)
478 # Delete a file from the file system.
480 # `last_error` is updated to contains the error information on error, and null on success.
483 var res
= path
.to_cstring
.file_delete
485 last_error
= new IOError("Cannot delete `{path}`: {sys.errno.strerror}")
491 # Copy content of file at `path` to `dest`.
493 # `last_error` is updated to contains the error information on error, and null on success.
498 var output
= dest
.open_wo
500 while not input
.eof
do
501 var buffer
= input
.read
(1024)
507 last_error
= input
.last_error
or else output
.last_error
510 # Open this file for reading.
513 # var file = "/etc/issue".to_path.open_ro
514 # print file.read_line
518 # Note that it is the user's responsibility to close the stream.
519 # Therefore, for simple use case, look at `read_all` or `each_line`.
521 # ENSURE `last_error == result.last_error`
522 fun open_ro
: FileReader
524 var res
= new FileReader.open
(path
)
525 last_error
= res
.last_error
529 # Open this file for writing
532 # var file = "bla.log".to_path.open_wo
533 # file.write "Blabla\n"
537 # Note that it is the user's responsibility to close the stream.
538 # Therefore, for simple use case, look at `Writable::write_to_file`.
540 # ENSURE `last_error == result.last_error`
541 fun open_wo
: FileWriter
543 var res
= new FileWriter.open
(path
)
544 last_error
= res
.last_error
548 # Read all the content of the file as a string.
551 # var content = "/etc/issue".to_path.read_all
555 # `last_error` is updated to contains the error information on error, and null on success.
556 # In case of error, the result might be empty or truncated.
558 # See `Reader::read_all` for details.
559 fun read_all
: String do return read_all_bytes
.to_s
561 # Read all the content on the file as a raw sequence of bytes.
564 # var content = "/etc/issue".to_path.read_all_bytes
568 # `last_error` is updated to contains the error information on error, and null on success.
569 # In case of error, the result might be empty or truncated.
570 fun read_all_bytes
: Bytes
573 var res
= s
.read_all_bytes
575 last_error
= s
.last_error
579 # Read all the lines of the file
582 # var lines = "/etc/passwd".to_path.read_lines
584 # print "{lines.length} users"
587 # var fields = l.split(":")
588 # print "name={fields[0]} uid={fields[2]}"
592 # `last_error` is updated to contains the error information on error, and null on success.
593 # In case of error, the result might be empty or truncated.
595 # See `Reader::read_lines` for details.
596 fun read_lines
: Array[String]
599 var res
= s
.read_lines
601 last_error
= s
.last_error
605 # Return an iterator on each line of the file
608 # for l in "/etc/passwd".to_path.each_line do
609 # var fields = l.split(":")
610 # print "name={fields[0]} uid={fields[2]}"
614 # Note: the stream is automatically closed at the end of the file (see `LineIterator::close_on_finish`)
616 # `last_error` is updated to contains the error information on error, and null on success.
618 # See `Reader::each_line` for details.
619 fun each_line
: LineIterator
622 var res
= s
.each_line
623 res
.close_on_finish
= true
624 last_error
= s
.last_error
629 # Lists the files contained within the directory at `path`.
631 # var files = "/etc".to_path.files
632 # assert files.has("/etc/issue".to_path)
634 # `last_error` is updated to contains the error information on error, and null on success.
635 # In case of error, the result might be empty or truncated.
637 # var path = "/etc/issue".to_path
639 # assert files.is_empty
640 # assert path.last_error != null
641 fun files
: Array[Path]
644 var res
= new Array[Path]
645 var d
= new NativeDir.opendir
(path
.to_cstring
)
646 if d
.address_is_null
then
647 last_error
= new IOError("Cannot list directory `{path}`: {sys.errno.strerror}")
653 if de
.address_is_null
then
654 # readdir cannot fail, so null means end of list
657 var name
= de
.to_s_with_copy
658 if name
== "." or name
== ".." then continue
659 res
.add
new Path(path
/ name
)
666 # Delete a directory and all of its content
668 # Does not go through symbolic links and may get stuck in a cycle if there
669 # is a cycle in the file system.
671 # `last_error` is updated to contains the error information on error, and null on success.
672 # The method does not stop on the first error and try to remove most file and directories.
675 # var path = "/does/not/exists/".to_path
677 # assert path.last_error != null
682 for file
in self.files
do
683 var stat
= file
.link_stat
685 last_error
= file
.last_error
694 if last_error
== null then last_error
= file
.last_error
697 # Delete the directory itself if things are fine
698 if last_error
== null then
699 if path
.to_cstring
.rmdir
then
700 last_error
= new IOError("Cannot remove `{self}`: {sys.errno.strerror}")
705 redef fun ==(other
) do return other
isa Path and simplified
.path
== other
.simplified
.path
706 redef fun hash
do return simplified
.path
.hash
709 # Information on a file
711 # Created by `Path::stat` and `Path::link_stat`.
713 # The information within this class is gathered when the instance is initialized
714 # it will not be updated if the targeted file is modified.
720 # The low-level status of a file
723 private var stat
: NativeFileStat
725 private var finalized
= false
729 if not finalized
then
735 # Returns the last access time in seconds since Epoch
736 fun last_access_time
: Int
742 # Returns the last access time
744 # alias for `last_access_time`
745 fun atime
: Int do return last_access_time
747 # Returns the last modification time in seconds since Epoch
748 fun last_modification_time
: Int
754 # Returns the last modification time
756 # alias for `last_modification_time`
757 fun mtime
: Int do return last_modification_time
760 # Size of the file at `path`
767 # Is self a regular file and not a device file, pipe, socket, etc.?
774 # Alias for `is_file`
775 fun is_reg
: Bool do return is_file
777 # Is this a directory?
784 # Is this a symbolic link?
791 # FIXME Make the following POSIX only? or implement in some other way on Windows
793 # Returns the last status change time in seconds since Epoch
794 fun last_status_change_time
: Int
800 # Returns the last status change time
802 # alias for `last_status_change_time`
803 fun ctime
: Int do return last_status_change_time
805 # Returns the permission bits of file
812 # Is this a character device?
819 # Is this a block device?
826 # Is this a FIFO pipe?
833 # Is this a UNIX socket
842 # Access file system related services on the path at `self`
843 fun to_path
: Path do return new Path(to_s
)
845 private fun write_native_to
(s
: FileWriter)
847 for i
in substrings
do s
.write_native
(i
.to_cstring
, 0, i
.bytelen
)
852 # return true if a file with this names exists
853 fun file_exists
: Bool do return to_cstring
.file_exists
855 # The status of a file. see POSIX stat(2).
856 fun file_stat
: nullable FileStat
858 var stat
= to_cstring
.file_stat
859 if stat
.address_is_null
then return null
860 return new FileStat(stat
)
863 # The status of a file or of a symlink. see POSIX lstat(2).
864 fun file_lstat
: nullable FileStat
866 var stat
= to_cstring
.file_lstat
867 if stat
.address_is_null
then return null
868 return new FileStat(stat
)
871 # Remove a file, return true if success
872 fun file_delete
: Bool do return to_cstring
.file_delete
874 # Copy content of file at `self` to `dest`
875 fun file_copy_to
(dest
: String) do to_path
.copy
(dest
.to_path
)
877 # Remove the trailing `extension`.
879 # `extension` usually starts with a dot but could be anything.
881 # assert "file.txt".strip_extension(".txt") == "file"
882 # assert "file.txt".strip_extension("le.txt") == "fi"
883 # assert "file.txt".strip_extension("xt") == "file.t"
885 # If `extension == null`, the rightmost extension is stripped, including the last dot.
887 # assert "file.txt".strip_extension == "file"
889 # If `extension` is not present, `self` is returned unmodified.
891 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
892 fun strip_extension
(extension
: nullable String): String
894 if extension
== null then
895 extension
= file_extension
896 if extension
== null then
898 else extension
= ".{extension}"
901 if has_suffix
(extension
) then
902 return substring
(0, length
- extension
.length
)
907 # Extract the basename of a path and strip the `extension`
909 # The extension is stripped only if `extension != null`.
911 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
912 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
913 # assert "path/to/a_file.ext".basename == "a_file.ext"
914 # assert "path/to".basename(".ext") == "to"
915 # assert "path/to/".basename(".ext") == "to"
916 # assert "path/to".basename == "to"
917 # assert "path".basename("") == "path"
918 # assert "/path".basename("") == "path"
919 # assert "/".basename("") == "/"
920 # assert "".basename("") == ""
921 fun basename
(extension
: nullable String): String
923 var l
= length
- 1 # Index of the last char
924 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
925 if l
== 0 then return "/"
926 var pos
= chars
.last_index_of_from
('/', l
)
929 n
= substring
(pos
+1, l-pos
)
932 if extension
!= null then
933 return n
.strip_extension
(extension
)
937 # Extract the dirname of a path
939 # assert "/path/to/a_file.ext".dirname == "/path/to"
940 # assert "path/to/a_file.ext".dirname == "path/to"
941 # assert "path/to".dirname == "path"
942 # assert "path/to/".dirname == "path"
943 # assert "path".dirname == "."
944 # assert "/path".dirname == "/"
945 # assert "/".dirname == "/"
946 # assert "".dirname == "."
949 var l
= length
- 1 # Index of the last char
950 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
951 var pos
= chars
.last_index_of_from
('/', l
)
953 return substring
(0, pos
)
954 else if pos
== 0 then
961 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
962 fun realpath
: String do
963 var cs
= to_cstring
.file_realpath
964 var res
= cs
.to_s_with_copy
965 # cs.free_malloc # FIXME memory leak
969 # Simplify a file path by remove useless `.`, removing `//`, and resolving `..`
971 # * `..` are not resolved if they start the path
972 # * starting `.` is simplified unless the path is empty
973 # * starting `/` is not removed
974 # * trailing `/` is removed
976 # Note that the method only work on the string:
978 # * no I/O access is performed
979 # * the validity of the path is not checked
982 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
983 # assert "../dir/file".simplify_path == "../dir/file"
984 # assert "dir/../../".simplify_path == ".."
985 # assert "dir/..".simplify_path == "."
986 # assert "//absolute//path/".simplify_path == "/absolute/path"
987 # assert "//absolute//../".simplify_path == "/"
988 # assert "/".simplify_path == "/"
989 # assert "../".simplify_path == ".."
990 # assert "./".simplify_path == "."
991 # assert "././././././".simplify_path == "."
992 # assert "./../dir".simplify_path == "../dir"
993 # assert "./dir".simplify_path == "dir"
995 fun simplify_path
: String
997 var a
= self.split_with
("/")
998 var a2
= new Array[String]
1000 if x
== "." and not a2
.is_empty
then continue # skip `././`
1001 if x
== "" and not a2
.is_empty
then continue # skip `//`
1002 if x
== ".." and not a2
.is_empty
and a2
.last
!= ".." then
1003 if a2
.last
== "." then # do not skip `./../`
1004 a2
.pop
# reduce `./../` in `../`
1005 else # reduce `dir/../` in `/`
1009 else if not a2
.is_empty
and a2
.last
== "." then
1010 a2
.pop
# reduce `./dir` in `dir`
1014 if a2
.is_empty
then return "."
1015 if a2
.length
== 1 and a2
.first
== "" then return "/"
1019 # Correctly join two path using the directory separator.
1021 # Using a standard "{self}/{path}" does not work in the following cases:
1023 # * `self` is empty.
1024 # * `path` starts with `'/'`.
1026 # This method ensures that the join is valid.
1028 # assert "hello".join_path("world") == "hello/world"
1029 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
1030 # assert "".join_path("world") == "world"
1031 # assert "hello".join_path("/world") == "/world"
1032 # assert "hello/".join_path("world") == "hello/world"
1033 # assert "hello/".join_path("/world") == "/world"
1035 # Note: You may want to use `simplify_path` on the result.
1037 # Note: This method works only with POSIX paths.
1038 fun join_path
(path
: String): String
1040 if path
.is_empty
then return self
1041 if self.is_empty
then return path
1042 if path
.chars
[0] == '/' then return path
1043 if self.last
== '/' then return "{self}{path}"
1044 return "{self}/{path}"
1047 # Convert the path (`self`) to a program name.
1049 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
1050 # used as a program name. In order to do that, prepend `./` if needed.
1052 # assert "foo".to_program_name == "./foo"
1053 # assert "/foo".to_program_name == "/foo"
1054 # assert "".to_program_name == "./" # At least, your shell will detect the error.
1055 fun to_program_name
: String do
1056 if self.has_prefix
("/") then
1063 # Alias for `join_path`
1065 # assert "hello" / "world" == "hello/world"
1066 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
1067 # assert "" / "world" == "world"
1068 # assert "/hello" / "/world" == "/world"
1070 # This operator is quite useful for chaining changes of path.
1071 # The next one being relative to the previous one.
1075 # var c = "baz/foobar"
1076 # assert a/b/c == "/bar/baz/foobar"
1077 fun /(path
: String): String do return join_path
(path
)
1079 # Returns the relative path needed to go from `self` to `dest`.
1081 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
1082 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
1084 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
1086 # In some cases, the result is still independent of the current directory:
1088 # assert "foo/bar".relpath("..") == "../../.."
1090 # In other cases, parts of the current directory may be exhibited:
1092 # var p = "../foo/bar".relpath("baz")
1093 # var c = getcwd.basename
1094 # assert p == "../../{c}/baz"
1096 # For path resolution independent of the current directory (eg. for paths in URL),
1097 # or to use an other starting directory than the current directory,
1098 # just force absolute paths:
1100 # var start = "/a/b/c/d"
1101 # var p2 = (start/"../foo/bar").relpath(start/"baz")
1102 # assert p2 == "../../d/baz"
1105 # Neither `self` or `dest` has to be real paths or to exist in directories since
1106 # the resolution is only done with string manipulations and without any access to
1107 # the underlying file system.
1109 # If `self` and `dest` are the same directory, the empty string is returned:
1111 # assert "foo".relpath("foo") == ""
1112 # assert "foo/../bar".relpath("bar") == ""
1114 # The empty string and "." designate both the current directory:
1116 # assert "".relpath("foo/bar") == "foo/bar"
1117 # assert ".".relpath("foo/bar") == "foo/bar"
1118 # assert "foo/bar".relpath("") == "../.."
1119 # assert "/" + "/".relpath(".") == getcwd
1120 fun relpath
(dest
: String): String
1123 var from
= (cwd
/self).simplify_path
.split
("/")
1124 if from
.last
.is_empty
then from
.pop
# case for the root directory
1125 var to
= (cwd
/dest
).simplify_path
.split
("/")
1126 if to
.last
.is_empty
then to
.pop
# case for the root directory
1128 # Remove common prefixes
1129 while not from
.is_empty
and not to
.is_empty
and from
.first
== to
.first
do
1134 # Result is going up in `from` with ".." then going down following `to`
1135 var from_len
= from
.length
1136 if from_len
== 0 then return to
.join
("/")
1137 var up
= "../"*(from_len-1
) + ".."
1138 if to
.is_empty
then return up
1139 var res
= up
+ "/" + to
.join
("/")
1143 # Create a directory (and all intermediate directories if needed)
1145 # Return an error object in case of error.
1147 # assert "/etc/".mkdir != null
1148 fun mkdir
: nullable Error
1150 var dirs
= self.split_with
("/")
1151 var path
= new FlatBuffer
1152 if dirs
.is_empty
then return null
1153 if dirs
[0].is_empty
then
1154 # it was a starting /
1157 var error
: nullable Error = null
1159 if d
.is_empty
then continue
1162 var res
= path
.to_s
.to_cstring
.file_mkdir
1163 if not res
and error
== null then
1164 error
= new IOError("Cannot create directory `{path}`: {sys.errno.strerror}")
1170 # Delete a directory and all of its content, return `true` on success
1172 # Does not go through symbolic links and may get stuck in a cycle if there
1173 # is a cycle in the filesystem.
1175 # Return an error object in case of error.
1177 # assert "/fail/does not/exist".rmdir != null
1178 fun rmdir
: nullable Error
1185 # Change the current working directory
1188 # assert getcwd == "/etc"
1190 # assert getcwd == "/"
1192 # Return an error object in case of error.
1194 # assert "/etc".chdir == null
1195 # assert "/fail/does no/exist".chdir != null
1196 # assert getcwd == "/etc" # unchanger
1197 fun chdir
: nullable Error
1199 var res
= to_cstring
.file_chdir
1200 if res
then return null
1201 var error
= new IOError("Cannot change directory to `{self}`: {sys.errno.strerror}")
1205 # Return right-most extension (without the dot)
1207 # Only the last extension is returned.
1208 # There is no special case for combined extensions.
1210 # assert "file.txt".file_extension == "txt"
1211 # assert "file.tar.gz".file_extension == "gz"
1213 # For file without extension, `null` is returned.
1214 # Hoever, for trailing dot, `""` is returned.
1216 # assert "file".file_extension == null
1217 # assert "file.".file_extension == ""
1219 # The starting dot of hidden files is never considered.
1221 # assert ".file.txt".file_extension == "txt"
1222 # assert ".file".file_extension == null
1223 fun file_extension
: nullable String
1225 var last_slash
= chars
.last_index_of
('.')
1226 if last_slash
> 0 then
1227 return substring
( last_slash
+1, length
)
1233 # Returns entries contained within the directory represented by self.
1235 # var files = "/etc".files
1236 # assert files.has("issue")
1238 # Returns an empty array in case of error
1240 # files = "/etc/issue".files
1241 # assert files.is_empty
1243 # TODO find a better way to handle errors and to give them back to the user.
1244 fun files
: Array[String]
1246 var res
= new Array[String]
1247 var d
= new NativeDir.opendir
(to_cstring
)
1248 if d
.address_is_null
then return res
1252 if de
.address_is_null
then break
1253 var name
= de
.to_s_with_copy
1254 if name
== "." or name
== ".." then continue
1263 redef class FlatString
1264 redef fun write_native_to
(s
)
1266 s
.write_native
(items
, first_byte
, bytelen
)
1270 redef class NativeString
1271 private fun file_exists
: Bool `{
1272 FILE *hdl = fopen(self,"r");
1279 private fun file_stat
: NativeFileStat `{
1281 if(stat(self, &buff) != -1) {
1282 struct stat* stat_element;
1283 stat_element = malloc(sizeof(struct stat));
1284 return memcpy(stat_element, &buff, sizeof(struct stat));
1289 private fun file_lstat
: NativeFileStat `{
1290 struct stat* stat_element;
1292 stat_element = malloc(sizeof(struct stat));
1293 res = lstat(self, stat_element);
1294 if (res == -1) return NULL;
1295 return stat_element;
1298 private fun file_mkdir
: Bool `{ return !mkdir(self, 0777); `}
1300 private fun rmdir: Bool `{ return !rmdir(self); `}
1302 private fun file_delete
: Bool `{
1303 return remove(self) == 0;
1306 private fun file_chdir
: Bool `{ return !chdir(self); `}
1308 private fun file_realpath: NativeString `{ return realpath(self, NULL); `}
1311 # This class is system dependent ... must reify the vfs
1312 private extern class NativeFileStat `{ struct stat * `}
1314 # Returns the permission bits of file
1315 fun mode: Int `{ return self->st_mode; `}
1317 # Returns the last access time
1318 fun atime
: Int `{ return self->st_atime; `}
1320 # Returns the last status change time
1321 fun ctime: Int `{ return self->st_ctime; `}
1323 # Returns the last modification time
1324 fun mtime
: Int `{ return self->st_mtime; `}
1327 fun size: Int `{ return self->st_size; `}
1329 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
1330 fun is_reg
: Bool `{ return S_ISREG(self->st_mode); `}
1332 # Returns true if it is a directory
1333 fun is_dir: Bool `{ return S_ISDIR(self->st_mode); `}
1335 # Returns true if it is a character device
1336 fun is_chr
: Bool `{ return S_ISCHR(self->st_mode); `}
1338 # Returns true if it is a block device
1339 fun is_blk: Bool `{ return S_ISBLK(self->st_mode); `}
1341 # Returns true if the type is fifo
1342 fun is_fifo
: Bool `{ return S_ISFIFO(self->st_mode); `}
1344 # Returns true if the type is a link
1345 fun is_lnk: Bool `{ return S_ISLNK(self->st_mode); `}
1347 # Returns true if the type is a socket
1348 fun is_sock
: Bool `{ return S_ISSOCK(self->st_mode); `}
1351 # Instance of this class are standard FILE * pointers
1352 private extern class NativeFile `{ FILE* `}
1353 fun io_read
(buf
: NativeString, len
: Int): Int `{
1354 return fread(buf, 1, len, self);
1357 fun io_write
(buf
: NativeString, from
, len
: Int): Int `{
1358 return fwrite(buf+from, 1, len, self);
1361 fun write_byte
(value
: Byte): Int `{
1362 unsigned char b = (unsigned char)value;
1363 return fwrite(&b, 1, 1, self);
1366 fun io_close
: Int `{ return fclose(self); `}
1368 fun file_stat: NativeFileStat `{
1370 if(fstat
(fileno
(self), &buff
) != -1) {
1371 struct stat
* stat_element
;
1372 stat_element
= malloc
(sizeof
(struct stat
));
1373 return memcpy
(stat_element
, &buff
, sizeof
(struct stat
));
1378 fun ferror: Bool `{ return ferror(self); `}
1380 fun fileno
: Int `{ return fileno(self); `}
1382 # Flushes the buffer, forcing the write operation
1383 fun flush: Int `{ return fflush(self); `}
1385 # Used to specify how the buffering will be handled for the current stream.
1386 fun set_buffering_type
(buf_length
: Int, mode
: Int): Int `{
1387 return setvbuf(self, NULL, mode, buf_length);
1390 new io_open_read
(path
: NativeString) `{ return fopen(path, "r"); `}
1392 new io_open_write(path: NativeString) `{ return fopen(path, "w"); `}
1394 new native_stdin
`{ return stdin; `}
1396 new native_stdout `{ return stdout; `}
1398 new native_stderr
`{ return stderr; `}
1401 # Standard `DIR*` pointer
1402 private extern class NativeDir `{ DIR* `}
1405 new opendir
(path
: NativeString) `{ return opendir(path); `}
1408 fun closedir `{ closedir(self); `}
1410 # Read the next directory entry
1411 fun readdir
: NativeString `{
1414 if (!de) return NULL;
1422 var stdin
: PollableReader = new Stdin is protected writable, lazy
1425 var stdout
: Writer = new Stdout is protected writable, lazy
1427 # Standard output for errors
1428 var stderr
: Writer = new Stderr is protected writable, lazy
1430 # Enumeration for buffer mode full (flushes when buffer is full)
1431 fun buffer_mode_full
: Int `{ return _IOFBF; `}
1433 # Enumeration for buffer mode line (flushes when a `\n
` is encountered)
1434 fun buffer_mode_line: Int `{ return _IONBF; `}
1436 # Enumeration for buffer mode none (flushes ASAP when something is written)
1437 fun buffer_mode_none
: Int `{ return _IOLBF; `}
1439 # returns first available stream to read or write to
1440 # return null on interruption (possibly a signal)
1441 protected fun poll( streams : Sequence[FileStream] ) : nullable FileStream
1443 var in_fds = new Array[Int]
1444 var out_fds = new Array[Int]
1445 var fd_to_stream = new HashMap[Int,FileStream]
1448 if s isa FileReader then in_fds.add( fd )
1449 if s isa FileWriter then out_fds.add( fd )
1451 fd_to_stream[fd] = s
1454 var polled_fd = intern_poll( in_fds, out_fds )
1456 if polled_fd == null then
1459 return fd_to_stream[polled_fd]
1463 private fun intern_poll(in_fds: Array[Int], out_fds: Array[Int]): nullable Int
1464 import Array[Int].length, Array[Int].[], Int.as(nullable Int) `{
1465 int in_len
, out_len
, total_len
;
1466 struct pollfd
*c_fds
;
1468 int first_polled_fd
= -1;
1471 in_len
= Array_of_Int_length( in_fds
);
1472 out_len
= Array_of_Int_length( out_fds
);
1473 total_len
= in_len
+ out_len
;
1474 c_fds
= malloc
( sizeof
(struct pollfd
) * total_len
);
1477 for ( i
=0; i
<in_len
; i
++ ) {
1479 fd
= Array_of_Int__index( in_fds
, i
);
1482 c_fds
[i
].events
= POLLIN;
1485 /* output streams
*/
1486 for ( i
=0; i
<out_len
; i
++ ) {
1488 fd
= Array_of_Int__index( out_fds
, i
);
1491 c_fds
[i
].events
= POLLOUT;
1494 /* poll all fds
, unlimited timeout
*/
1495 result
= poll
( c_fds
, total_len
, -1 );
1498 /* analyse results
*/
1499 for ( i
=0; i
<total_len
; i
++ )
1500 if ( c_fds
[i
].revents
& c_fds
[i
].events
|| /* awaited event
*/
1501 c_fds
[i
].revents
& POLLHUP ) /* closed
*/
1503 first_polled_fd
= c_fds
[i
].fd
;
1507 return Int_as_nullable( first_polled_fd
);
1509 else if ( result
< 0 )
1510 fprintf
( stderr
, "Error in Stream:poll: %s\n", strerror
( errno
) );
1517 # Print `objects
` on the standard output (`stdout
`).
1518 fun printn(objects: Object...)
1520 sys.stdout.write(objects.plain_to_s)
1523 # Print an `object
` on the standard output (`stdout
`) and add a newline.
1524 fun print(object: Object)
1526 sys.stdout.write(object.to_s)
1527 sys.stdout.write("\n")
1530 # Print `object
` on the error output (`stderr
` or a log system)
1531 fun print_error(object: Object)
1533 sys.stderr.write object.to_s
1534 sys.stderr.write "\n"
1537 # Read a character from the standard input (`stdin
`).
1540 var c = sys.stdin.read_char
1541 if c == null then return '\1'
1545 # Read a line from the standard input (`stdin
`).
1548 return sys.stdin.read_line
1551 # Return the working (current) directory
1552 fun getcwd: String do return native_getcwd.to_s
1554 private fun native_getcwd: NativeString `{ return getcwd(NULL, 0); `}