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("Error: Opening file at '{path.as(not null)}' failed with '{sys.errno.strerror}'")
127 redef fun fill_buffer
129 var nb
= _file
.io_read
(_buffer
, _buffer_capacity
)
139 redef var end_reached
= false
141 # Open the file at `path` for reading.
143 # var f = new FileReader.open("/etc/issue")
144 # assert not f.end_reached
147 # In case of error, `last_error` is set
149 # f = new FileReader.open("/fail/does not/exist")
150 # assert f.end_reached
151 # assert f.last_error != null
152 init open
(path
: String)
156 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
157 if _file
.address_is_null
then
158 last_error
= new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
163 # Creates a new File stream from a file descriptor
165 # This is a low-level method.
166 init from_fd
(fd
: Int) do
169 _file
= fd
.fd_to_stream
(read_only
)
170 if _file
.address_is_null
then
171 last_error
= new IOError("Error: Converting fd {fd} to stream failed with '{sys.errno.strerror}'")
177 # `Stream` that can write to a File
182 redef fun write_bytes
(s
) do
183 if last_error
!= null then return
184 if not _is_writable
then
185 last_error
= new IOError("cannot write to non-writable stream")
188 write_native
(s
.items
, s
.length
)
193 if last_error
!= null then return
194 if not _is_writable
then
195 last_error
= new IOError("cannot write to non-writable stream")
198 for i
in s
.substrings
do write_native
(i
.to_cstring
, i
.length
)
201 redef fun write_byte
(value
)
203 if last_error
!= null then return
204 if not _is_writable
then
205 last_error
= new IOError("Cannot write to non-writable stream")
208 if _file
.address_is_null
then
209 last_error
= new IOError("Writing on a null stream")
214 var err
= _file
.write_byte
(value
)
217 last_error
= new IOError("Problem writing a byte: {err}")
226 redef var is_writable
= false
228 # Write `len` bytes from `native`.
229 private fun write_native
(native
: NativeString, len
: Int)
231 if last_error
!= null then return
232 if not _is_writable
then
233 last_error
= new IOError("Cannot write to non-writable stream")
236 if _file
.address_is_null
then
237 last_error
= new IOError("Writing on a null stream")
241 var err
= _file
.io_write
(native
, len
)
244 last_error
= new IOError("Problem in writing : {err} {len} \n")
248 # Open the file at `path` for writing.
249 init open
(path
: String)
251 _file
= new NativeFile.io_open_write
(path
.to_cstring
)
254 if _file
.address_is_null
then
255 last_error
= new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
260 # Creates a new File stream from a file descriptor
261 init from_fd
(fd
: Int) do
263 _file
= fd
.fd_to_stream
(wipe_write
)
265 if _file
.address_is_null
then
266 last_error
= new IOError("Error: Opening stream from file descriptor {fd} failed with '{sys.errno.strerror}'")
273 # Creates a file stream from a file descriptor `fd` using the file access `mode`.
275 # NOTE: The `mode` specified must be compatible with the one used in the file descriptor.
276 private fun fd_to_stream
(mode
: NativeString): NativeFile `{
277 return fdopen(self, mode);
281 # Constant for read-only file streams
282 private fun read_only
: NativeString do return once
"r".to_cstring
284 # Constant for write-only file streams
286 # If a stream is opened on a file with this method,
287 # it will wipe the previous file if any.
288 # Else, it will create the file.
289 private fun wipe_write
: NativeString do return once
"w".to_cstring
291 ###############################################################################
293 # Standard input stream.
295 # The class of the default value of `sys.stdin`.
300 _file
= new NativeFile.native_stdin
306 struct pollfd fd = {0, POLLIN, 0};
307 int res = poll(&fd, 1, 0);
309 perror("Error poll stdin");
316 # Standard output stream.
318 # The class of the default value of `sys.stdout`.
322 _file
= new NativeFile.native_stdout
325 set_buffering_mode
(256, sys
.buffer_mode_line
)
329 # Standard error stream.
331 # The class of the default value of `sys.stderr`.
335 _file
= new NativeFile.native_stderr
341 ###############################################################################
344 # Like `write_to` but take care of creating the file
345 fun write_to_file
(filepath
: String)
347 var stream
= new FileWriter.open
(filepath
)
353 # Utility class to access file system services
355 # Usually created with `Text::to_path`.
358 private var path
: String
361 redef fun to_s
do return path
363 # Short name of the file at `to_s`
366 # var path = "/tmp/somefile".to_path
367 # assert path.filename == "somefile"
369 var filename
: String = path
.basename
("") is lazy
371 # Does the file at `path` exists?
372 fun exists
: Bool do return stat
!= null
374 # Information on the file at `self` following symbolic links
376 # Returns `null` if there is no file at `self`.
378 # assert "/etc/".to_path.stat.is_dir
379 # assert "/etc/issue".to_path.stat.is_file
380 # assert "/fail/does not/exist".to_path.stat == null
383 # var p = "/tmp/".to_path
385 # if stat != null then # Does `p` exist?
386 # print "It's size is {stat.size}"
387 # if stat.is_dir then print "It's a directory"
390 fun stat
: nullable FileStat
392 var stat
= path
.to_cstring
.file_stat
393 if stat
.address_is_null
then return null
394 return new FileStat(stat
)
397 # Information on the file or link at `self`
399 # Do not follow symbolic links.
400 fun link_stat
: nullable FileStat
402 var stat
= path
.to_cstring
.file_lstat
403 if stat
.address_is_null
then return null
404 return new FileStat(stat
)
407 # Delete a file from the file system, return `true` on success
408 fun delete
: Bool do return path
.to_cstring
.file_delete
410 # Copy content of file at `path` to `dest`
416 var output
= dest
.open_wo
418 while not input
.eof
do
419 var buffer
= input
.read
(1024)
427 # Open this file for reading
429 # Require: `exists and not link_stat.is_dir`
430 fun open_ro
: FileReader
432 # TODO manage streams error when they are merged
433 return new FileReader.open
(path
)
436 # Open this file for writing
438 # Require: `not exists or not stat.is_dir`
439 fun open_wo
: FileWriter
441 # TODO manage streams error when they are merged
442 return new FileWriter.open
(path
)
445 # Read all the content of the file
448 # var content = "/etc/issue".to_path.read_all
452 # See `Reader::read_all` for details.
453 fun read_all
: String do return read_all_bytes
.to_s
455 fun read_all_bytes
: Bytes
458 var res
= s
.read_all_bytes
463 # Read all the lines of the file
466 # var lines = "/etc/passwd".to_path.read_lines
468 # print "{lines.length} users"
471 # var fields = l.split(":")
472 # print "name={fields[0]} uid={fields[2]}"
476 # See `Reader::read_lines` for details.
477 fun read_lines
: Array[String]
480 var res
= s
.read_lines
485 # Return an iterator on each line of the file
488 # for l in "/etc/passwd".to_path.each_line do
489 # var fields = l.split(":")
490 # print "name={fields[0]} uid={fields[2]}"
494 # Note: the stream is automatically closed at the end of the file (see `LineIterator::close_on_finish`)
496 # See `Reader::each_line` for details.
497 fun each_line
: LineIterator
500 var res
= s
.each_line
501 res
.close_on_finish
= true
506 # Lists the name of the files contained within the directory at `path`
508 # Require: `exists and is_dir`
509 fun files
: Array[Path]
511 var files
= new Array[Path]
512 for filename
in path
.files
do
513 files
.add
new Path(path
/ filename
)
518 # Delete a directory and all of its content, return `true` on success
520 # Does not go through symbolic links and may get stuck in a cycle if there
521 # is a cycle in the file system.
525 for file
in self.files
do
526 var stat
= file
.link_stat
528 ok
= file
.rmdir
and ok
530 ok
= file
.delete
and ok
534 # Delete the directory itself
535 if ok
then ok
= path
.to_cstring
.rmdir
and ok
540 redef fun ==(other
) do return other
isa Path and path
.simplify_path
== other
.path
.simplify_path
541 redef fun hash
do return path
.simplify_path
.hash
544 # Information on a file
546 # Created by `Path::stat` and `Path::link_stat`.
548 # The information within this class is gathered when the instance is initialized
549 # it will not be updated if the targeted file is modified.
555 # The low-level status of a file
558 private var stat
: NativeFileStat
560 private var finalized
= false
564 if not finalized
then
570 # Returns the last access time in seconds since Epoch
571 fun last_access_time
: Int
577 # Returns the last access time
579 # alias for `last_access_time`
580 fun atime
: Int do return last_access_time
582 # Returns the last modification time in seconds since Epoch
583 fun last_modification_time
: Int
589 # Returns the last modification time
591 # alias for `last_modification_time`
592 fun mtime
: Int do return last_modification_time
595 # Size of the file at `path`
602 # Is self a regular file and not a device file, pipe, socket, etc.?
609 # Alias for `is_file`
610 fun is_reg
: Bool do return is_file
612 # Is this a directory?
619 # Is this a symbolic link?
626 # FIXME Make the following POSIX only? or implement in some other way on Windows
628 # Returns the last status change time in seconds since Epoch
629 fun last_status_change_time
: Int
635 # Returns the last status change time
637 # alias for `last_status_change_time`
638 fun ctime
: Int do return last_status_change_time
640 # Returns the permission bits of file
647 # Is this a character device?
654 # Is this a block device?
661 # Is this a FIFO pipe?
668 # Is this a UNIX socket
677 # Access file system related services on the path at `self`
678 fun to_path
: Path do return new Path(to_s
)
682 # return true if a file with this names exists
683 fun file_exists
: Bool do return to_cstring
.file_exists
685 # The status of a file. see POSIX stat(2).
686 fun file_stat
: nullable FileStat
688 var stat
= to_cstring
.file_stat
689 if stat
.address_is_null
then return null
690 return new FileStat(stat
)
693 # The status of a file or of a symlink. see POSIX lstat(2).
694 fun file_lstat
: nullable FileStat
696 var stat
= to_cstring
.file_lstat
697 if stat
.address_is_null
then return null
698 return new FileStat(stat
)
701 # Remove a file, return true if success
702 fun file_delete
: Bool do return to_cstring
.file_delete
704 # Copy content of file at `self` to `dest`
705 fun file_copy_to
(dest
: String) do to_path
.copy
(dest
.to_path
)
707 # Remove the trailing `extension`.
709 # `extension` usually starts with a dot but could be anything.
711 # assert "file.txt".strip_extension(".txt") == "file"
712 # assert "file.txt".strip_extension("le.txt") == "fi"
713 # assert "file.txt".strip_extension("xt") == "file.t"
715 # If `extension == null`, the rightmost extension is stripped, including the last dot.
717 # assert "file.txt".strip_extension == "file"
719 # If `extension` is not present, `self` is returned unmodified.
721 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
722 fun strip_extension
(extension
: nullable String): String
724 if extension
== null then
725 extension
= file_extension
726 if extension
== null then
728 else extension
= ".{extension}"
731 if has_suffix
(extension
) then
732 return substring
(0, length
- extension
.length
)
737 # Extract the basename of a path and strip the `extension`
739 # The extension is stripped only if `extension != null`.
741 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
742 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
743 # assert "path/to/a_file.ext".basename == "a_file.ext"
744 # assert "path/to".basename(".ext") == "to"
745 # assert "path/to/".basename(".ext") == "to"
746 # assert "path/to".basename == "to"
747 # assert "path".basename("") == "path"
748 # assert "/path".basename("") == "path"
749 # assert "/".basename("") == "/"
750 # assert "".basename("") == ""
751 fun basename
(extension
: nullable String): String
753 var l
= length
- 1 # Index of the last char
754 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
755 if l
== 0 then return "/"
756 var pos
= chars
.last_index_of_from
('/', l
)
759 n
= substring
(pos
+1, l-pos
)
762 if extension
!= null then
763 return n
.strip_extension
(extension
)
767 # Extract the dirname of a path
769 # assert "/path/to/a_file.ext".dirname == "/path/to"
770 # assert "path/to/a_file.ext".dirname == "path/to"
771 # assert "path/to".dirname == "path"
772 # assert "path/to/".dirname == "path"
773 # assert "path".dirname == "."
774 # assert "/path".dirname == "/"
775 # assert "/".dirname == "/"
776 # assert "".dirname == "."
779 var l
= length
- 1 # Index of the last char
780 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
781 var pos
= chars
.last_index_of_from
('/', l
)
783 return substring
(0, pos
)
784 else if pos
== 0 then
791 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
792 fun realpath
: String do
793 var cs
= to_cstring
.file_realpath
794 var res
= cs
.to_s_with_copy
795 # cs.free_malloc # FIXME memory leak
799 # Simplify a file path by remove useless `.`, removing `//`, and resolving `..`
801 # * `..` are not resolved if they start the path
802 # * starting `.` is simplified unless the path is empty
803 # * starting `/` is not removed
804 # * trailing `/` is removed
806 # Note that the method only work on the string:
808 # * no I/O access is performed
809 # * the validity of the path is not checked
812 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
813 # assert "../dir/file".simplify_path == "../dir/file"
814 # assert "dir/../../".simplify_path == ".."
815 # assert "dir/..".simplify_path == "."
816 # assert "//absolute//path/".simplify_path == "/absolute/path"
817 # assert "//absolute//../".simplify_path == "/"
818 # assert "/".simplify_path == "/"
819 # assert "../".simplify_path == ".."
820 # assert "./".simplify_path == "."
821 # assert "././././././".simplify_path == "."
822 # assert "./../dir".simplify_path == "../dir"
823 # assert "./dir".simplify_path == "dir"
825 fun simplify_path
: String
827 var a
= self.split_with
("/")
828 var a2
= new Array[String]
830 if x
== "." and not a2
.is_empty
then continue # skip `././`
831 if x
== "" and not a2
.is_empty
then continue # skip `//`
832 if x
== ".." and not a2
.is_empty
and a2
.last
!= ".." then
833 if a2
.last
== "." then # do not skip `./../`
834 a2
.pop
# reduce `./../` in `../`
835 else # reduce `dir/../` in `/`
839 else if not a2
.is_empty
and a2
.last
== "." then
840 a2
.pop
# reduce `./dir` in `dir`
844 if a2
.is_empty
then return "."
845 if a2
.length
== 1 and a2
.first
== "" then return "/"
849 # Correctly join two path using the directory separator.
851 # Using a standard "{self}/{path}" does not work in the following cases:
854 # * `path` starts with `'/'`.
856 # This method ensures that the join is valid.
858 # assert "hello".join_path("world") == "hello/world"
859 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
860 # assert "".join_path("world") == "world"
861 # assert "hello".join_path("/world") == "/world"
862 # assert "hello/".join_path("world") == "hello/world"
863 # assert "hello/".join_path("/world") == "/world"
865 # Note: You may want to use `simplify_path` on the result.
867 # Note: This method works only with POSIX paths.
868 fun join_path
(path
: String): String
870 if path
.is_empty
then return self
871 if self.is_empty
then return path
872 if path
.chars
[0] == '/' then return path
873 if self.last
== '/' then return "{self}{path}"
874 return "{self}/{path}"
877 # Convert the path (`self`) to a program name.
879 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
880 # used as a program name. In order to do that, prepend `./` if needed.
882 # assert "foo".to_program_name == "./foo"
883 # assert "/foo".to_program_name == "/foo"
884 # assert "".to_program_name == "./" # At least, your shell will detect the error.
885 fun to_program_name
: String do
886 if self.has_prefix
("/") then
893 # Alias for `join_path`
895 # assert "hello" / "world" == "hello/world"
896 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
897 # assert "" / "world" == "world"
898 # assert "/hello" / "/world" == "/world"
900 # This operator is quite useful for chaining changes of path.
901 # The next one being relative to the previous one.
905 # var c = "baz/foobar"
906 # assert a/b/c == "/bar/baz/foobar"
907 fun /(path
: String): String do return join_path
(path
)
909 # Returns the relative path needed to go from `self` to `dest`.
911 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
912 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
914 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
916 # In some cases, the result is still independent of the current directory:
918 # assert "foo/bar".relpath("..") == "../../.."
920 # In other cases, parts of the current directory may be exhibited:
922 # var p = "../foo/bar".relpath("baz")
923 # var c = getcwd.basename("")
924 # assert p == "../../{c}/baz"
926 # For path resolution independent of the current directory (eg. for paths in URL),
927 # or to use an other starting directory than the current directory,
928 # just force absolute paths:
930 # var start = "/a/b/c/d"
931 # var p2 = (start/"../foo/bar").relpath(start/"baz")
932 # assert p2 == "../../d/baz"
935 # Neither `self` or `dest` has to be real paths or to exist in directories since
936 # the resolution is only done with string manipulations and without any access to
937 # the underlying file system.
939 # If `self` and `dest` are the same directory, the empty string is returned:
941 # assert "foo".relpath("foo") == ""
942 # assert "foo/../bar".relpath("bar") == ""
944 # The empty string and "." designate both the current directory:
946 # assert "".relpath("foo/bar") == "foo/bar"
947 # assert ".".relpath("foo/bar") == "foo/bar"
948 # assert "foo/bar".relpath("") == "../.."
949 # assert "/" + "/".relpath(".") == getcwd
950 fun relpath
(dest
: String): String
953 var from
= (cwd
/self).simplify_path
.split
("/")
954 if from
.last
.is_empty
then from
.pop
# case for the root directory
955 var to
= (cwd
/dest
).simplify_path
.split
("/")
956 if to
.last
.is_empty
then to
.pop
# case for the root directory
958 # Remove common prefixes
959 while not from
.is_empty
and not to
.is_empty
and from
.first
== to
.first
do
964 # Result is going up in `from` with ".." then going down following `to`
965 var from_len
= from
.length
966 if from_len
== 0 then return to
.join
("/")
967 var up
= "../"*(from_len-1
) + ".."
968 if to
.is_empty
then return up
969 var res
= up
+ "/" + to
.join
("/")
973 # Create a directory (and all intermediate directories if needed)
975 # Return an error object in case of error.
977 # assert "/etc/".mkdir != null
978 fun mkdir
: nullable Error
980 var dirs
= self.split_with
("/")
981 var path
= new FlatBuffer
982 if dirs
.is_empty
then return null
983 if dirs
[0].is_empty
then
984 # it was a starting /
987 var error
: nullable Error = null
989 if d
.is_empty
then continue
992 var res
= path
.to_s
.to_cstring
.file_mkdir
993 if not res
and error
== null then
994 error
= new IOError("Cannot create directory `{path}`: {sys.errno.strerror}")
1000 # Delete a directory and all of its content, return `true` on success
1002 # Does not go through symbolic links and may get stuck in a cycle if there
1003 # is a cycle in the filesystem.
1005 # Return an error object in case of error.
1007 # assert "/fail/does not/exist".rmdir != null
1008 fun rmdir
: nullable Error
1010 var res
= to_path
.rmdir
1011 if res
then return null
1012 var error
= new IOError("Cannot change remove `{self}`: {sys.errno.strerror}")
1016 # Change the current working directory
1019 # assert getcwd == "/etc"
1021 # assert getcwd == "/"
1023 # Return an error object in case of error.
1025 # assert "/etc".chdir == null
1026 # assert "/fail/does no/exist".chdir != null
1027 # assert getcwd == "/etc" # unchanger
1028 fun chdir
: nullable Error
1030 var res
= to_cstring
.file_chdir
1031 if res
then return null
1032 var error
= new IOError("Cannot change directory to `{self}`: {sys.errno.strerror}")
1036 # Return right-most extension (without the dot)
1038 # Only the last extension is returned.
1039 # There is no special case for combined extensions.
1041 # assert "file.txt".file_extension == "txt"
1042 # assert "file.tar.gz".file_extension == "gz"
1044 # For file without extension, `null` is returned.
1045 # Hoever, for trailing dot, `""` is returned.
1047 # assert "file".file_extension == null
1048 # assert "file.".file_extension == ""
1050 # The starting dot of hidden files is never considered.
1052 # assert ".file.txt".file_extension == "txt"
1053 # assert ".file".file_extension == null
1054 fun file_extension
: nullable String
1056 var last_slash
= chars
.last_index_of
('.')
1057 if last_slash
> 0 then
1058 return substring
( last_slash
+1, length
)
1064 # Returns entries contained within the directory represented by self.
1066 # var files = "/etc".files
1067 # assert files.has("issue")
1069 # Returns an empty array in case of error
1071 # files = "/etc/issue".files
1072 # assert files.is_empty
1074 # TODO find a better way to handle errors and to give them back to the user.
1075 fun files
: Array[String]
1077 var res
= new Array[String]
1078 var d
= new NativeDir.opendir
(to_cstring
)
1079 if d
.address_is_null
then return res
1083 if de
.address_is_null
then break
1084 var name
= de
.to_s_with_copy
1085 if name
== "." or name
== ".." then continue
1094 redef class NativeString
1095 private fun file_exists
: Bool `{
1096 FILE *hdl = fopen(self,"r");
1103 private fun file_stat
: NativeFileStat `{
1105 if(stat(self, &buff) != -1) {
1106 struct stat* stat_element;
1107 stat_element = malloc(sizeof(struct stat));
1108 return memcpy(stat_element, &buff, sizeof(struct stat));
1113 private fun file_lstat
: NativeFileStat `{
1114 struct stat* stat_element;
1116 stat_element = malloc(sizeof(struct stat));
1117 res = lstat(self, stat_element);
1118 if (res == -1) return NULL;
1119 return stat_element;
1122 private fun file_mkdir
: Bool `{ return !mkdir(self, 0777); `}
1124 private fun rmdir: Bool `{ return !rmdir(self); `}
1126 private fun file_delete
: Bool `{
1127 return remove(self) == 0;
1130 private fun file_chdir
: Bool `{ return !chdir(self); `}
1132 private fun file_realpath: NativeString `{ return realpath(self, NULL); `}
1135 # This class is system dependent ... must reify the vfs
1136 private extern class NativeFileStat `{ struct stat * `}
1138 # Returns the permission bits of file
1139 fun mode: Int `{ return self->st_mode; `}
1141 # Returns the last access time
1142 fun atime
: Int `{ return self->st_atime; `}
1144 # Returns the last status change time
1145 fun ctime: Int `{ return self->st_ctime; `}
1147 # Returns the last modification time
1148 fun mtime
: Int `{ return self->st_mtime; `}
1151 fun size: Int `{ return self->st_size; `}
1153 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
1154 fun is_reg
: Bool `{ return S_ISREG(self->st_mode); `}
1156 # Returns true if it is a directory
1157 fun is_dir: Bool `{ return S_ISDIR(self->st_mode); `}
1159 # Returns true if it is a character device
1160 fun is_chr
: Bool `{ return S_ISCHR(self->st_mode); `}
1162 # Returns true if it is a block device
1163 fun is_blk: Bool `{ return S_ISBLK(self->st_mode); `}
1165 # Returns true if the type is fifo
1166 fun is_fifo
: Bool `{ return S_ISFIFO(self->st_mode); `}
1168 # Returns true if the type is a link
1169 fun is_lnk: Bool `{ return S_ISLNK(self->st_mode); `}
1171 # Returns true if the type is a socket
1172 fun is_sock
: Bool `{ return S_ISSOCK(self->st_mode); `}
1175 # Instance of this class are standard FILE * pointers
1176 private extern class NativeFile `{ FILE* `}
1177 fun io_read
(buf
: NativeString, len
: Int): Int `{
1178 return fread(buf, 1, len, self);
1181 fun io_write
(buf
: NativeString, len
: Int): Int `{
1182 return fwrite(buf, 1, len, self);
1185 fun write_byte
(value
: Byte): Int `{
1186 unsigned char b = (unsigned char)value;
1187 return fwrite(&b, 1, 1, self);
1190 fun io_close
: Int `{ return fclose(self); `}
1192 fun file_stat: NativeFileStat `{
1194 if(fstat
(fileno
(self), &buff
) != -1) {
1195 struct stat
* stat_element
;
1196 stat_element
= malloc
(sizeof
(struct stat
));
1197 return memcpy
(stat_element
, &buff
, sizeof
(struct stat
));
1202 fun fileno: Int `{ return fileno(self); `}
1204 # Flushes the buffer, forcing the write operation
1205 fun flush
: Int `{ return fflush(self); `}
1207 # Used to specify how the buffering will be handled for the current stream.
1208 fun set_buffering_type(buf_length: Int, mode: Int): Int `{
1209 return setvbuf
(self, NULL, mode
, buf_length
);
1212 new io_open_read(path: NativeString) `{ return fopen(path, "r"); `}
1214 new io_open_write
(path
: NativeString) `{ return fopen(path, "w"); `}
1216 new native_stdin `{ return stdin; `}
1218 new native_stdout
`{ return stdout; `}
1220 new native_stderr `{ return stderr; `}
1223 # Standard `DIR*` pointer
1224 private extern class NativeDir `{ DIR* `}
1227 new opendir(path: NativeString) `{ return opendir(path); `}
1230 fun closedir
`{ closedir(self); `}
1232 # Read the next directory entry
1233 fun readdir: NativeString `{
1236 if (!de
) return NULL;
1244 var stdin: PollableReader = new Stdin is protected writable, lazy
1247 var stdout: Writer = new Stdout is protected writable, lazy
1249 # Standard output for errors
1250 var stderr: Writer = new Stderr is protected writable, lazy
1252 # Enumeration for buffer mode full (flushes when buffer is full)
1253 fun buffer_mode_full: Int `{ return _IOFBF; `}
1255 # Enumeration for buffer mode line (flushes when a `\n` is encountered)
1256 fun buffer_mode_line
: Int `{ return _IONBF; `}
1258 # Enumeration for buffer mode none (flushes ASAP when something is written)
1259 fun buffer_mode_none: Int `{ return _IOLBF; `}
1261 # returns first available stream to read or write to
1262 # return null on interruption (possibly a signal)
1263 protected fun poll
( streams
: Sequence[FileStream] ) : nullable FileStream
1265 var in_fds
= new Array[Int]
1266 var out_fds
= new Array[Int]
1267 var fd_to_stream
= new HashMap[Int,FileStream]
1270 if s
isa FileReader then in_fds
.add
( fd
)
1271 if s
isa FileWriter then out_fds
.add
( fd
)
1273 fd_to_stream
[fd
] = s
1276 var polled_fd
= intern_poll
( in_fds
, out_fds
)
1278 if polled_fd
== null then
1281 return fd_to_stream
[polled_fd
]
1285 private fun intern_poll
(in_fds
: Array[Int], out_fds
: Array[Int]): nullable Int
1286 import Array[Int].length
, Array[Int].[], Int.as(nullable Int) `{
1287 int in_len, out_len, total_len;
1288 struct pollfd *c_fds;
1290 int first_polled_fd = -1;
1293 in_len = Array_of_Int_length( in_fds );
1294 out_len = Array_of_Int_length( out_fds );
1295 total_len = in_len + out_len;
1296 c_fds = malloc( sizeof(struct pollfd) * total_len );
1299 for ( i=0; i<in_len; i ++ ) {
1301 fd = Array_of_Int__index( in_fds, i );
1304 c_fds[i].events = POLLIN;
1307 /* output streams */
1308 for ( i=0; i<out_len; i ++ ) {
1310 fd = Array_of_Int__index( out_fds, i );
1313 c_fds[i].events = POLLOUT;
1316 /* poll all fds, unlimited timeout */
1317 result = poll( c_fds, total_len, -1 );
1320 /* analyse results */
1321 for ( i=0; i<total_len; i++ )
1322 if ( c_fds[i].revents & c_fds[i].events || /* awaited event */
1323 c_fds[i].revents & POLLHUP ) /* closed */
1325 first_polled_fd = c_fds[i].fd;
1329 return Int_as_nullable( first_polled_fd );
1331 else if ( result < 0 )
1332 fprintf( stderr, "Error in Stream:poll: %s\n", strerror( errno ) );
1339 # Print `objects` on the standard output (`stdout`).
1340 fun printn
(objects
: Object...)
1342 sys
.stdout
.write
(objects
.plain_to_s
)
1345 # Print an `object` on the standard output (`stdout`) and add a newline.
1346 fun print
(object
: Object)
1348 sys
.stdout
.write
(object
.to_s
)
1349 sys
.stdout
.write
("\n")
1352 # Print `object` on the error output (`stderr` or a log system)
1353 fun print_error
(object
: Object)
1355 sys
.stderr
.write object
.to_s
1356 sys
.stderr
.write
"\n"
1359 # Read a character from the standard input (`stdin`).
1362 var c
= sys
.stdin
.read_char
1363 if c
== null then return '\1'
1367 # Read a line from the standard input (`stdin`).
1370 return sys
.stdin
.read_line
1373 # Return the working (current) directory
1374 fun getcwd
: String do return native_getcwd
.to_s
1376 private fun native_getcwd
: NativeString `{ return getcwd(NULL, 0); `}