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.)
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`:
83 fun set_buffering_mode
(buf_size
, mode
: Int) do
84 if buf_size
<= 0 then buf_size
= 512
85 if _file
.set_buffering_type
(buf_size
, mode
) != 0 then
86 last_error
= new IOError("Error while changing buffering type for FileStream, returned error {sys.errno.strerror}")
91 # `Stream` that can read from a File
98 # Open the same file again.
99 # The original path is reused, therefore the reopened file can be a different file.
101 # var f = new FileReader.open("/etc/issue")
102 # var l = f.read_line
104 # assert l == f.read_line
107 if not eof
and not _file
.address_is_null
then close
109 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
110 if _file
.address_is_null
then
111 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
.items
, _buffer
.capacity
)
139 redef var end_reached
: Bool = 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
184 if last_error
!= null then return
185 if not _is_writable
then
186 last_error
= new IOError("Cannot write to non-writable stream")
189 if s
isa FlatText then
190 write_native
(s
.to_cstring
, s
.length
)
192 for i
in s
.substrings
do write_native
(i
.to_cstring
, i
.length
)
196 redef fun write_byte
(value
)
198 if last_error
!= null then return
199 if not _is_writable
then
200 last_error
= new IOError("Cannot write to non-writable stream")
203 if _file
.address_is_null
then
204 last_error
= new IOError("Writing on a null stream")
209 var err
= _file
.write_byte
(value
)
212 last_error
= new IOError("Problem writing a byte: {err}")
221 redef var is_writable
= false
223 # Write `len` bytes from `native`.
224 private fun write_native
(native
: NativeString, len
: Int)
226 if last_error
!= null then return
227 if not _is_writable
then
228 last_error
= new IOError("Cannot write to non-writable stream")
231 if _file
.address_is_null
then
232 last_error
= new IOError("Writing on a null stream")
236 var err
= _file
.io_write
(native
, len
)
239 last_error
= new IOError("Problem in writing : {err} {len} \n")
243 # Open the file at `path` for writing.
244 init open
(path
: String)
246 _file
= new NativeFile.io_open_write
(path
.to_cstring
)
249 if _file
.address_is_null
then
250 last_error
= new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
255 # Creates a new File stream from a file descriptor
256 init from_fd
(fd
: Int) do
258 _file
= fd
.fd_to_stream
(wipe_write
)
260 if _file
.address_is_null
then
261 last_error
= new IOError("Error: Opening stream from file descriptor {fd} failed with '{sys.errno.strerror}'")
268 # Creates a file stream from a file descriptor `fd` using the file access `mode`.
270 # NOTE: The `mode` specified must be compatible with the one used in the file descriptor.
271 private fun fd_to_stream
(mode
: NativeString): NativeFile is extern "file_int_fdtostream"
274 # Constant for read-only file streams
275 private fun read_only
: NativeString do return once
"r".to_cstring
277 # Constant for write-only file streams
279 # If a stream is opened on a file with this method,
280 # it will wipe the previous file if any.
281 # Else, it will create the file.
282 private fun wipe_write
: NativeString do return once
"w".to_cstring
284 ###############################################################################
286 # Standard input stream.
288 # The class of the default value of `sys.stdin`.
293 _file
= new NativeFile.native_stdin
298 redef fun poll_in
: Bool is extern "file_stdin_poll_in"
301 # Standard output stream.
303 # The class of the default value of `sys.stdout`.
307 _file
= new NativeFile.native_stdout
310 set_buffering_mode
(256, sys
.buffer_mode_line
)
314 # Standard error stream.
316 # The class of the default value of `sys.stderr`.
320 _file
= new NativeFile.native_stderr
326 ###############################################################################
329 # Like `write_to` but take care of creating the file
330 fun write_to_file
(filepath
: String)
332 var stream
= new FileWriter.open
(filepath
)
338 # Utility class to access file system services
340 # Usually created with `Text::to_path`.
343 private var path
: String
346 redef fun to_s
do return path
348 # Name of the file name at `to_s`
351 # var path = "/tmp/somefile".to_path
352 # assert path.filename == "somefile"
354 var filename
: String = path
.basename
("") is lazy
356 # Does the file at `path` exists?
357 fun exists
: Bool do return stat
!= null
359 # Information on the file at `self` following symbolic links
361 # Returns `null` if there is no file at `self`.
363 # assert "/etc/".to_path.stat.is_dir
364 # assert "/etc/issue".to_path.stat.is_file
365 # assert "/fail/does not/exist".to_path.stat == null
368 # var p = "/tmp/".to_path
370 # if stat != null then # Does `p` exist?
371 # print "It's size is {stat.size}"
372 # if stat.is_dir then print "It's a directory"
375 fun stat
: nullable FileStat
377 var stat
= path
.to_cstring
.file_stat
378 if stat
.address_is_null
then return null
379 return new FileStat(stat
)
382 # Information on the file or link at `self`
384 # Do not follow symbolic links.
385 fun link_stat
: nullable FileStat
387 var stat
= path
.to_cstring
.file_lstat
388 if stat
.address_is_null
then return null
389 return new FileStat(stat
)
392 # Delete a file from the file system, return `true` on success
393 fun delete
: Bool do return path
.to_cstring
.file_delete
395 # Copy content of file at `path` to `dest`
401 var output
= dest
.open_wo
403 while not input
.eof
do
404 var buffer
= input
.read
(1024)
412 # Open this file for reading
414 # Require: `exists and not link_stat.is_dir`
415 fun open_ro
: FileReader
417 # TODO manage streams error when they are merged
418 return new FileReader.open
(path
)
421 # Open this file for writing
423 # Require: `not exists or not stat.is_dir`
424 fun open_wo
: FileWriter
426 # TODO manage streams error when they are merged
427 return new FileWriter.open
(path
)
430 # Read all the content of the file
433 # var content = "/etc/issue".to_path.read_all
437 # See `Reader::read_all` for details.
446 # Read all the lines of the file
449 # var lines = "/etc/passwd".to_path.read_lines
451 # print "{lines.length} users"
454 # var fields = l.split(":")
455 # print "name={fields[0]} uid={fields[2]}"
459 # See `Reader::read_lines` for details.
460 fun read_lines
: Array[String]
463 var res
= s
.read_lines
468 # Return an iterator on each line of the file
471 # for l in "/etc/passwd".to_path.each_line do
472 # var fields = l.split(":")
473 # print "name={fields[0]} uid={fields[2]}"
477 # Note: the stream is automatically closed at the end of the file (see `LineIterator::close_on_finish`)
479 # See `Reader::each_line` for details.
480 fun each_line
: LineIterator
483 var res
= s
.each_line
484 res
.close_on_finish
= true
489 # Lists the name of the files contained within the directory at `path`
491 # Require: `exists and is_dir`
492 fun files
: Array[Path]
494 var files
= new Array[Path]
495 for filename
in path
.files
do
496 files
.add
new Path(path
/ filename
)
501 # Delete a directory and all of its content, return `true` on success
503 # Does not go through symbolic links and may get stuck in a cycle if there
504 # is a cycle in the file system.
508 for file
in self.files
do
509 var stat
= file
.link_stat
511 ok
= file
.rmdir
and ok
513 ok
= file
.delete
and ok
517 # Delete the directory itself
518 if ok
then ok
= path
.to_cstring
.rmdir
and ok
523 redef fun ==(other
) do return other
isa Path and path
.simplify_path
== other
.path
.simplify_path
524 redef fun hash
do return path
.simplify_path
.hash
527 # Information on a file
529 # Created by `Path::stat` and `Path::link_stat`.
531 # The information within this class is gathered when the instance is initialized
532 # it will not be updated if the targeted file is modified.
538 # The low-level status of a file
541 private var stat
: NativeFileStat
543 private var finalized
= false
547 if not finalized
then
553 # Returns the last access time in seconds since Epoch
554 fun last_access_time
: Int
560 # Returns the last access time
562 # alias for `last_access_time`
563 fun atime
: Int do return last_access_time
565 # Returns the last modification time in seconds since Epoch
566 fun last_modification_time
: Int
572 # Returns the last modification time
574 # alias for `last_modification_time`
575 fun mtime
: Int do return last_modification_time
578 # Size of the file at `path`
585 # Is self a regular file and not a device file, pipe, socket, etc.?
592 # Alias for `is_file`
593 fun is_reg
: Bool do return is_file
595 # Is this a directory?
602 # Is this a symbolic link?
609 # FIXME Make the following POSIX only? or implement in some other way on Windows
611 # Returns the last status change time in seconds since Epoch
612 fun last_status_change_time
: Int
618 # Returns the last status change time
620 # alias for `last_status_change_time`
621 fun ctime
: Int do return last_status_change_time
623 # Returns the permission bits of file
630 # Is this a character device?
637 # Is this a block device?
644 # Is this a FIFO pipe?
651 # Is this a UNIX socket
660 # Access file system related services on the path at `self`
661 fun to_path
: Path do return new Path(to_s
)
665 # return true if a file with this names exists
666 fun file_exists
: Bool do return to_cstring
.file_exists
668 # The status of a file. see POSIX stat(2).
669 fun file_stat
: nullable FileStat
671 var stat
= to_cstring
.file_stat
672 if stat
.address_is_null
then return null
673 return new FileStat(stat
)
676 # The status of a file or of a symlink. see POSIX lstat(2).
677 fun file_lstat
: nullable FileStat
679 var stat
= to_cstring
.file_lstat
680 if stat
.address_is_null
then return null
681 return new FileStat(stat
)
684 # Remove a file, return true if success
685 fun file_delete
: Bool do return to_cstring
.file_delete
687 # Copy content of file at `self` to `dest`
688 fun file_copy_to
(dest
: String) do to_path
.copy
(dest
.to_path
)
690 # Remove the trailing extension `ext`.
692 # `ext` usually starts with a dot but could be anything.
694 # assert "file.txt".strip_extension(".txt") == "file"
695 # assert "file.txt".strip_extension("le.txt") == "fi"
696 # assert "file.txt".strip_extension("xt") == "file.t"
698 # if `ext` is not present, `self` is returned unmodified.
700 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
701 fun strip_extension
(ext
: String): String
703 if has_suffix
(ext
) then
704 return substring
(0, length
- ext
.length
)
709 # Extract the basename of a path and remove the extension
711 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
712 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
713 # assert "path/to".basename(".ext") == "to"
714 # assert "path/to/".basename(".ext") == "to"
715 # assert "path".basename("") == "path"
716 # assert "/path".basename("") == "path"
717 # assert "/".basename("") == "/"
718 # assert "".basename("") == ""
719 fun basename
(ext
: String): String
721 var l
= length
- 1 # Index of the last char
722 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
723 if l
== 0 then return "/"
724 var pos
= chars
.last_index_of_from
('/', l
)
727 n
= substring
(pos
+1, l-pos
)
729 return n
.strip_extension
(ext
)
732 # Extract the dirname of a path
734 # assert "/path/to/a_file.ext".dirname == "/path/to"
735 # assert "path/to/a_file.ext".dirname == "path/to"
736 # assert "path/to".dirname == "path"
737 # assert "path/to/".dirname == "path"
738 # assert "path".dirname == "."
739 # assert "/path".dirname == "/"
740 # assert "/".dirname == "/"
741 # assert "".dirname == "."
744 var l
= length
- 1 # Index of the last char
745 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
746 var pos
= chars
.last_index_of_from
('/', l
)
748 return substring
(0, pos
)
749 else if pos
== 0 then
756 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
757 fun realpath
: String do
758 var cs
= to_cstring
.file_realpath
759 var res
= cs
.to_s_with_copy
760 # cs.free_malloc # FIXME memory leak
764 # Simplify a file path by remove useless ".", removing "//", and resolving ".."
766 # * ".." are not resolved if they start the path
767 # * starting "/" is not removed
768 # * trailing "/" is removed
770 # Note that the method only work on the string:
772 # * no I/O access is performed
773 # * the validity of the path is not checked
776 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
777 # assert "../dir/file".simplify_path == "../dir/file"
778 # assert "dir/../../".simplify_path == ".."
779 # assert "dir/..".simplify_path == "."
780 # assert "//absolute//path/".simplify_path == "/absolute/path"
781 # assert "//absolute//../".simplify_path == "/"
783 fun simplify_path
: String
785 var a
= self.split_with
("/")
786 var a2
= new Array[String]
788 if x
== "." then continue
789 if x
== "" and not a2
.is_empty
then continue
790 if x
== ".." and not a2
.is_empty
and a2
.last
!= ".." then
796 if a2
.is_empty
then return "."
797 if a2
.length
== 1 and a2
.first
== "" then return "/"
801 # Correctly join two path using the directory separator.
803 # Using a standard "{self}/{path}" does not work in the following cases:
806 # * `path` starts with `'/'`.
808 # This method ensures that the join is valid.
810 # assert "hello".join_path("world") == "hello/world"
811 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
812 # assert "".join_path("world") == "world"
813 # assert "hello".join_path("/world") == "/world"
814 # assert "hello/".join_path("world") == "hello/world"
815 # assert "hello/".join_path("/world") == "/world"
817 # Note: You may want to use `simplify_path` on the result.
819 # Note: This method works only with POSIX paths.
820 fun join_path
(path
: String): String
822 if path
.is_empty
then return self
823 if self.is_empty
then return path
824 if path
.chars
[0] == '/' then return path
825 if self.last
== '/' then return "{self}{path}"
826 return "{self}/{path}"
829 # Convert the path (`self`) to a program name.
831 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
832 # used as a program name. In order to do that, prepend `./` if needed.
834 # assert "foo".to_program_name == "./foo"
835 # assert "/foo".to_program_name == "/foo"
836 # assert "".to_program_name == "./" # At least, your shell will detect the error.
837 fun to_program_name
: String do
838 if self.has_prefix
("/") then
845 # Alias for `join_path`
847 # assert "hello" / "world" == "hello/world"
848 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
849 # assert "" / "world" == "world"
850 # assert "/hello" / "/world" == "/world"
852 # This operator is quite useful for chaining changes of path.
853 # The next one being relative to the previous one.
857 # var c = "baz/foobar"
858 # assert a/b/c == "/bar/baz/foobar"
859 fun /(path
: String): String do return join_path
(path
)
861 # Returns the relative path needed to go from `self` to `dest`.
863 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
864 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
866 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
868 # In some cases, the result is still independent of the current directory:
870 # assert "foo/bar".relpath("..") == "../../.."
872 # In other cases, parts of the current directory may be exhibited:
874 # var p = "../foo/bar".relpath("baz")
875 # var c = getcwd.basename("")
876 # assert p == "../../{c}/baz"
878 # For path resolution independent of the current directory (eg. for paths in URL),
879 # or to use an other starting directory than the current directory,
880 # just force absolute paths:
882 # var start = "/a/b/c/d"
883 # var p2 = (start/"../foo/bar").relpath(start/"baz")
884 # assert p2 == "../../d/baz"
887 # Neither `self` or `dest` has to be real paths or to exist in directories since
888 # the resolution is only done with string manipulations and without any access to
889 # the underlying file system.
891 # If `self` and `dest` are the same directory, the empty string is returned:
893 # assert "foo".relpath("foo") == ""
894 # assert "foo/../bar".relpath("bar") == ""
896 # The empty string and "." designate both the current directory:
898 # assert "".relpath("foo/bar") == "foo/bar"
899 # assert ".".relpath("foo/bar") == "foo/bar"
900 # assert "foo/bar".relpath("") == "../.."
901 # assert "/" + "/".relpath(".") == getcwd
902 fun relpath
(dest
: String): String
905 var from
= (cwd
/self).simplify_path
.split
("/")
906 if from
.last
.is_empty
then from
.pop
# case for the root directory
907 var to
= (cwd
/dest
).simplify_path
.split
("/")
908 if to
.last
.is_empty
then to
.pop
# case for the root directory
910 # Remove common prefixes
911 while not from
.is_empty
and not to
.is_empty
and from
.first
== to
.first
do
916 # Result is going up in `from` with ".." then going down following `to`
917 var from_len
= from
.length
918 if from_len
== 0 then return to
.join
("/")
919 var up
= "../"*(from_len-1
) + ".."
920 if to
.is_empty
then return up
921 var res
= up
+ "/" + to
.join
("/")
925 # Create a directory (and all intermediate directories if needed)
927 # Return an error object in case of error.
929 # assert "/etc/".mkdir != null
930 fun mkdir
: nullable Error
932 var dirs
= self.split_with
("/")
933 var path
= new FlatBuffer
934 if dirs
.is_empty
then return null
935 if dirs
[0].is_empty
then
936 # it was a starting /
939 var error
: nullable Error = null
941 if d
.is_empty
then continue
944 var res
= path
.to_s
.to_cstring
.file_mkdir
945 if not res
and error
== null then
946 error
= new IOError("Cannot create directory `{path}`: {sys.errno.strerror}")
952 # Delete a directory and all of its content, return `true` on success
954 # Does not go through symbolic links and may get stuck in a cycle if there
955 # is a cycle in the filesystem.
957 # Return an error object in case of error.
959 # assert "/fail/does not/exist".rmdir != null
960 fun rmdir
: nullable Error
962 var res
= to_path
.rmdir
963 if res
then return null
964 var error
= new IOError("Cannot change remove `{self}`: {sys.errno.strerror}")
968 # Change the current working directory
971 # assert getcwd == "/etc"
973 # assert getcwd == "/"
975 # Return an error object in case of error.
977 # assert "/etc".chdir == null
978 # assert "/fail/does no/exist".chdir != null
979 # assert getcwd == "/etc" # unchanger
980 fun chdir
: nullable Error
982 var res
= to_cstring
.file_chdir
983 if res
then return null
984 var error
= new IOError("Cannot change directory to `{self}`: {sys.errno.strerror}")
988 # Return right-most extension (without the dot)
990 # Only the last extension is returned.
991 # There is no special case for combined extensions.
993 # assert "file.txt".file_extension == "txt"
994 # assert "file.tar.gz".file_extension == "gz"
996 # For file without extension, `null` is returned.
997 # Hoever, for trailing dot, `""` is returned.
999 # assert "file".file_extension == null
1000 # assert "file.".file_extension == ""
1002 # The starting dot of hidden files is never considered.
1004 # assert ".file.txt".file_extension == "txt"
1005 # assert ".file".file_extension == null
1006 fun file_extension
: nullable String
1008 var last_slash
= chars
.last_index_of
('.')
1009 if last_slash
> 0 then
1010 return substring
( last_slash
+1, length
)
1016 # Returns entries contained within the directory represented by self.
1018 # var files = "/etc".files
1019 # assert files.has("issue")
1021 # Returns an empty array in case of error
1023 # files = "/etc/issue".files
1024 # assert files.is_empty
1026 # TODO find a better way to handle errors and to give them back to the user.
1027 fun files
: Array[String]
1029 var res
= new Array[String]
1030 var d
= new NativeDir.opendir
(to_cstring
)
1031 if d
.address_is_null
then return res
1035 if de
.address_is_null
then break
1036 var name
= de
.to_s_with_copy
1037 if name
== "." or name
== ".." then continue
1046 redef class NativeString
1047 private fun file_exists
: Bool is extern "string_NativeString_NativeString_file_exists_0"
1048 private fun file_stat
: NativeFileStat is extern "string_NativeString_NativeString_file_stat_0"
1049 private fun file_lstat
: NativeFileStat `{
1050 struct stat* stat_element;
1052 stat_element = malloc(sizeof(struct stat));
1053 res = lstat(recv, stat_element);
1054 if (res == -1) return NULL;
1055 return stat_element;
1057 private fun file_mkdir
: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
1058 private fun rmdir
: Bool `{ return !rmdir(recv); `}
1059 private fun file_delete: Bool is extern "string_NativeString_NativeString_file_delete_0"
1060 private fun file_chdir: Bool is extern "string_NativeString_NativeString_file_chdir_0"
1061 private fun file_realpath: NativeString is extern "file_NativeString_realpath"
1064 # This class is system dependent ... must reify the vfs
1065 private extern class NativeFileStat `{ struct stat * `}
1066 # Returns the permission bits of file
1067 fun mode
: Int is extern "file_FileStat_FileStat_mode_0"
1068 # Returns the last access time
1069 fun atime
: Int is extern "file_FileStat_FileStat_atime_0"
1070 # Returns the last status change time
1071 fun ctime
: Int is extern "file_FileStat_FileStat_ctime_0"
1072 # Returns the last modification time
1073 fun mtime
: Int is extern "file_FileStat_FileStat_mtime_0"
1075 fun size
: Int is extern "file_FileStat_FileStat_size_0"
1077 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
1078 fun is_reg
: Bool `{ return S_ISREG(recv->st_mode); `}
1079 # Returns true if it is a directory
1080 fun is_dir: Bool `{ return S_ISDIR(recv->st_mode); `}
1081 # Returns true if it is a character device
1082 fun is_chr
: Bool `{ return S_ISCHR(recv->st_mode); `}
1083 # Returns true if it is a block device
1084 fun is_blk: Bool `{ return S_ISBLK(recv->st_mode); `}
1085 # Returns true if the type is fifo
1086 fun is_fifo
: Bool `{ return S_ISFIFO(recv->st_mode); `}
1087 # Returns true if the type is a link
1088 fun is_lnk: Bool `{ return S_ISLNK(recv->st_mode); `}
1089 # Returns true if the type is a socket
1090 fun is_sock
: Bool `{ return S_ISSOCK(recv->st_mode); `}
1093 # Instance of this class are standard FILE * pointers
1094 private extern class NativeFile `{ FILE* `}
1095 fun io_read
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
1096 fun io_write
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
1097 fun write_byte
(value
: Int): Int `{
1098 unsigned char b = (unsigned char)value;
1099 return fwrite(&b, 1, 1, recv);
1101 fun io_close
: Int is extern "file_NativeFile_NativeFile_io_close_0"
1102 fun file_stat
: NativeFileStat is extern "file_NativeFile_NativeFile_file_stat_0"
1103 fun fileno
: Int `{ return fileno(recv); `}
1104 # Flushes the buffer, forcing the write operation
1105 fun flush: Int is extern "fflush"
1106 # Used to specify how the buffering will be handled for the current stream.
1107 fun set_buffering_type(buf_length: Int, mode: Int): Int is extern "file_NativeFile_NativeFile_set_buffering_type_0"
1109 new io_open_read(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
1110 new io_open_write(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
1111 new native_stdin is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
1112 new native_stdout is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
1113 new native_stderr is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
1116 # Standard `DIR*` pointer
1117 private extern class NativeDir `{ DIR* `}
1120 new opendir
(path
: NativeString) `{ return opendir(path); `}
1123 fun closedir `{ closedir(recv); `}
1125 # Read the next directory entry
1126 fun readdir
: NativeString `{
1129 if (!de) return NULL;
1137 var stdin
: PollableReader = new Stdin is protected writable, lazy
1140 var stdout
: Writer = new Stdout is protected writable, lazy
1142 # Standard output for errors
1143 var stderr
: Writer = new Stderr is protected writable, lazy
1145 # Enumeration for buffer mode full (flushes when buffer is full)
1146 fun buffer_mode_full
: Int is extern "file_Sys_Sys_buffer_mode_full_0"
1147 # Enumeration for buffer mode line (flushes when a `\n` is encountered)
1148 fun buffer_mode_line
: Int is extern "file_Sys_Sys_buffer_mode_line_0"
1149 # Enumeration for buffer mode none (flushes ASAP when something is written)
1150 fun buffer_mode_none
: Int is extern "file_Sys_Sys_buffer_mode_none_0"
1152 # returns first available stream to read or write to
1153 # return null on interruption (possibly a signal)
1154 protected fun poll
( streams
: Sequence[FileStream] ) : nullable FileStream
1156 var in_fds
= new Array[Int]
1157 var out_fds
= new Array[Int]
1158 var fd_to_stream
= new HashMap[Int,FileStream]
1161 if s
isa FileReader then in_fds
.add
( fd
)
1162 if s
isa FileWriter then out_fds
.add
( fd
)
1164 fd_to_stream
[fd
] = s
1167 var polled_fd
= intern_poll
( in_fds
, out_fds
)
1169 if polled_fd
== null then
1172 return fd_to_stream
[polled_fd
]
1176 private fun intern_poll
(in_fds
: Array[Int], out_fds
: Array[Int]) : nullable Int is extern import Array[Int].length
, Array[Int].[], Int.as(nullable Int) `{
1177 int in_len, out_len, total_len;
1178 struct pollfd *c_fds;
1181 int first_polled_fd = -1;
1184 in_len = Array_of_Int_length( in_fds );
1185 out_len = Array_of_Int_length( out_fds );
1186 total_len = in_len + out_len;
1187 c_fds = malloc( sizeof(struct pollfd) * total_len );
1190 for ( i=0; i<in_len; i ++ ) {
1192 fd = Array_of_Int__index( in_fds, i );
1195 c_fds[i].events = POLLIN;
1198 /* output streams */
1199 for ( i=0; i<out_len; i ++ ) {
1201 fd = Array_of_Int__index( out_fds, i );
1204 c_fds[i].events = POLLOUT;
1207 /* poll all fds, unlimited timeout */
1208 result = poll( c_fds, total_len, -1 );
1211 /* analyse results */
1212 for ( i=0; i<total_len; i++ )
1213 if ( c_fds[i].revents & c_fds[i].events || /* awaited event */
1214 c_fds[i].revents & POLLHUP ) /* closed */
1216 first_polled_fd = c_fds[i].fd;
1220 return Int_as_nullable( first_polled_fd );
1222 else if ( result < 0 )
1223 fprintf( stderr, "Error in Stream:poll: %s\n", strerror( errno ) );
1230 # Print `objects` on the standard output (`stdout`).
1231 fun printn
(objects
: Object...)
1233 sys
.stdout
.write
(objects
.to_s
)
1236 # Print an `object` on the standard output (`stdout`) and add a newline.
1237 fun print
(object
: Object)
1239 sys
.stdout
.write
(object
.to_s
)
1240 sys
.stdout
.write
("\n")
1243 # Print `object` on the error output (`stderr` or a log system)
1244 fun print_error
(object
: Object)
1246 sys
.stderr
.write object
.to_s
1247 sys
.stderr
.write
"\n"
1250 # Read a character from the standard input (`stdin`).
1253 var c
= sys
.stdin
.read_char
1254 if c
== null then return '\1'
1258 # Read a line from the standard input (`stdin`).
1261 return sys
.stdin
.read_line
1264 # Return the working (current) directory
1265 fun getcwd
: String do return file_getcwd
.to_s
1266 private fun file_getcwd
: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"