1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 # Copyright 2008 Floréal Morandat <morandat@lirmm.fr>
5 # Copyright 2008 Jean-Sébastien Gélinas <calestar@gmail.com>
7 # This file is free software, which comes along with NIT. This software is
8 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
10 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
11 # is kept unaltered, and a notification of the changes is added.
12 # You are allowed to redistribute it and sell it, alone or is a part of
15 # File manipulations (create, read, write, etc.)
26 #include <sys/types.h>
34 # File Abstract Stream
35 abstract class FStream
37 # The path of the file.
38 var path
: nullable String = null
41 private var file
: nullable NativeFile = null
43 fun file_stat
: FileStat do return _file
.file_stat
45 # File descriptor of this file
46 fun fd
: Int do return _file
.fileno
48 # Sets the buffering mode for the current FStream
50 # If the buf_size is <= 0, its value will be 512 by default
52 # The mode is any of the buffer_mode enumeration in `Sys`:
56 fun set_buffering_mode
(buf_size
, mode
: Int) do
57 if buf_size
<= 0 then buf_size
= 512
58 if _file
.set_buffering_type
(buf_size
, mode
) != 0 then
59 last_error
= new IOError("Error while changing buffering type for FStream, returned error {sys.errno.strerror}")
71 # Open the same file again.
72 # The original path is reused, therefore the reopened file can be a different file.
75 if not eof
and not _file
.address_is_null
then close
77 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
78 if _file
.address_is_null
then
79 last_error
= new IOError("Error: Opening file at '{path.as(not null)}' failed with '{sys.errno.strerror}'")
90 if _file
.address_is_null
then return
91 var i
= _file
.io_close
98 var nb
= _file
.io_read
(_buffer
.items
, _buffer
.capacity
)
108 redef var end_reached
: Bool = false
110 # Open the file at `path` for reading.
111 init open
(path
: String)
115 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
116 if _file
.address_is_null
then
117 last_error
= new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
122 init from_fd
(fd
: Int) do
125 _file
= fd
.fd_to_stream
(read_only
)
126 if _file
.address_is_null
then
127 last_error
= new IOError("Error: Converting fd {fd} to stream failed with '{sys.errno.strerror}'")
140 if last_error
!= null then return
141 if not _is_writable
then
142 last_error
= new IOError("Cannot write to non-writable stream")
145 if s
isa FlatText then
146 write_native
(s
.to_cstring
, s
.length
)
148 for i
in s
.substrings
do write_native
(i
.to_cstring
, i
.length
)
155 if _file
.address_is_null
then
156 if last_error
!= null then return
157 last_error
= new IOError("Cannot close unopened write stream")
161 var i
= _file
.io_close
163 last_error
= new IOError("Close failed due to error {sys.errno.strerror}")
167 redef var is_writable
= false
169 # Write `len` bytes from `native`.
170 private fun write_native
(native
: NativeString, len
: Int)
172 if last_error
!= null then return
173 if not _is_writable
then
174 last_error
= new IOError("Cannot write to non-writable stream")
177 if _file
.address_is_null
then
178 last_error
= new IOError("Writing on a null stream")
182 var err
= _file
.io_write
(native
, len
)
185 last_error
= new IOError("Problem in writing : {err} {len} \n")
189 # Open the file at `path` for writing.
190 init open
(path
: String)
192 _file
= new NativeFile.io_open_write
(path
.to_cstring
)
195 if _file
.address_is_null
then
196 last_error
= new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
201 # Creates a new File stream from a file descriptor
202 init from_fd
(fd
: Int) do
204 _file
= fd
.fd_to_stream
(wipe_write
)
206 if _file
.address_is_null
then
207 last_error
= new IOError("Error: Opening stream from file descriptor {fd} failed with '{sys.errno.strerror}'")
214 # Creates a file stream from a file descriptor `fd` using the file access `mode`.
216 # NOTE: The `mode` specified must be compatible with the one used in the file descriptor.
217 private fun fd_to_stream
(mode
: NativeString): NativeFile is extern "file_int_fdtostream"
220 # Constant for read-only file streams
221 private fun read_only
: NativeString do return "r".to_cstring
223 # Constant for write-only file streams
225 # If a stream is opened on a file with this method,
226 # it will wipe the previous file if any.
227 # Else, it will create the file.
228 private fun wipe_write
: NativeString do return "w".to_cstring
230 ###############################################################################
236 _file
= new NativeFile.native_stdin
241 redef fun poll_in
: Bool is extern "file_stdin_poll_in"
247 _file
= new NativeFile.native_stdout
256 _file
= new NativeFile.native_stderr
262 ###############################################################################
264 redef class Streamable
265 # Like `write_to` but take care of creating the file
266 fun write_to_file
(filepath
: String)
268 var stream
= new OFStream.open
(filepath
)
275 # return true if a file with this names exists
276 fun file_exists
: Bool do return to_cstring
.file_exists
278 # The status of a file. see POSIX stat(2).
279 fun file_stat
: FileStat do return to_cstring
.file_stat
281 # The status of a file or of a symlink. see POSIX lstat(2).
282 fun file_lstat
: FileStat do return to_cstring
.file_lstat
284 # Remove a file, return true if success
285 fun file_delete
: Bool do return to_cstring
.file_delete
287 # Copy content of file at `self` to `dest`
288 fun file_copy_to
(dest
: String)
290 var input
= new IFStream.open
(self)
291 var output
= new OFStream.open
(dest
)
293 while not input
.eof
do
294 var buffer
= input
.read
(1024)
302 # Remove the trailing extension `ext`.
304 # `ext` usually starts with a dot but could be anything.
306 # assert "file.txt".strip_extension(".txt") == "file"
307 # assert "file.txt".strip_extension("le.txt") == "fi"
308 # assert "file.txt".strip_extension("xt") == "file.t"
310 # if `ext` is not present, `self` is returned unmodified.
312 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
313 fun strip_extension
(ext
: String): String
315 if has_suffix
(ext
) then
316 return substring
(0, length
- ext
.length
)
321 # Extract the basename of a path and remove the extension
323 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
324 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
325 # assert "path/to".basename(".ext") == "to"
326 # assert "path/to/".basename(".ext") == "to"
327 # assert "path".basename("") == "path"
328 # assert "/path".basename("") == "path"
329 # assert "/".basename("") == "/"
330 # assert "".basename("") == ""
331 fun basename
(ext
: String): String
333 var l
= length
- 1 # Index of the last char
334 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
335 if l
== 0 then return "/"
336 var pos
= chars
.last_index_of_from
('/', l
)
339 n
= substring
(pos
+1, l-pos
)
341 return n
.strip_extension
(ext
)
344 # Extract the dirname of a path
346 # assert "/path/to/a_file.ext".dirname == "/path/to"
347 # assert "path/to/a_file.ext".dirname == "path/to"
348 # assert "path/to".dirname == "path"
349 # assert "path/to/".dirname == "path"
350 # assert "path".dirname == "."
351 # assert "/path".dirname == "/"
352 # assert "/".dirname == "/"
353 # assert "".dirname == "."
356 var l
= length
- 1 # Index of the last char
357 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
358 var pos
= chars
.last_index_of_from
('/', l
)
360 return substring
(0, pos
)
361 else if pos
== 0 then
368 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
369 fun realpath
: String do
370 var cs
= to_cstring
.file_realpath
371 var res
= cs
.to_s_with_copy
372 # cs.free_malloc # FIXME memory leak
376 # Simplify a file path by remove useless ".", removing "//", and resolving ".."
377 # ".." are not resolved if they start the path
378 # starting "/" is not removed
379 # trainling "/" is removed
381 # Note that the method only wonrk on the string:
382 # * no I/O access is performed
383 # * the validity of the path is not checked
385 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
386 # assert "../dir/file".simplify_path == "../dir/file"
387 # assert "dir/../../".simplify_path == ".."
388 # assert "dir/..".simplify_path == "."
389 # assert "//absolute//path/".simplify_path == "/absolute/path"
390 # assert "//absolute//../".simplify_path == "/"
391 fun simplify_path
: String
393 var a
= self.split_with
("/")
394 var a2
= new Array[String]
396 if x
== "." then continue
397 if x
== "" and not a2
.is_empty
then continue
398 if x
== ".." and not a2
.is_empty
and a2
.last
!= ".." then
404 if a2
.is_empty
then return "."
405 if a2
.length
== 1 and a2
.first
== "" then return "/"
409 # Correctly join two path using the directory separator.
411 # Using a standard "{self}/{path}" does not work in the following cases:
414 # * `path` ends with `'/'`.
415 # * `path` starts with `'/'`.
417 # This method ensures that the join is valid.
419 # assert "hello".join_path("world") == "hello/world"
420 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
421 # assert "".join_path("world") == "world"
422 # assert "hello".join_path("/world") == "/world"
423 # assert "hello/".join_path("world") == "hello/world"
424 # assert "hello/".join_path("/world") == "/world"
426 # Note: You may want to use `simplify_path` on the result.
428 # Note: This method works only with POSIX paths.
429 fun join_path
(path
: String): String
431 if path
.is_empty
then return self
432 if self.is_empty
then return path
433 if path
.chars
[0] == '/' then return path
434 if self.last
== '/' then return "{self}{path}"
435 return "{self}/{path}"
438 # Convert the path (`self`) to a program name.
440 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
441 # used as a program name. In order to do that, prepend `./` if needed.
443 # assert "foo".to_program_name == "./foo"
444 # assert "/foo".to_program_name == "/foo"
445 # assert "".to_program_name == "./" # At least, your shell will detect the error.
446 fun to_program_name
: String do
447 if self.has_prefix
("/") then
454 # Alias for `join_path`
456 # assert "hello" / "world" == "hello/world"
457 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
458 # assert "" / "world" == "world"
459 # assert "/hello" / "/world" == "/world"
461 # This operator is quite useful for chaining changes of path.
462 # The next one being relative to the previous one.
466 # var c = "baz/foobar"
467 # assert a/b/c == "/bar/baz/foobar"
468 fun /(path
: String): String do return join_path
(path
)
470 # Returns the relative path needed to go from `self` to `dest`.
472 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
473 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
475 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
477 # In some cases, the result is still independent of the current directory:
479 # assert "foo/bar".relpath("..") == "../../.."
481 # In other cases, parts of the current directory may be exhibited:
483 # var p = "../foo/bar".relpath("baz")
484 # var c = getcwd.basename("")
485 # assert p == "../../{c}/baz"
487 # For path resolution independent of the current directory (eg. for paths in URL),
488 # or to use an other starting directory than the current directory,
489 # just force absolute paths:
491 # var start = "/a/b/c/d"
492 # var p2 = (start/"../foo/bar").relpath(start/"baz")
493 # assert p2 == "../../d/baz"
496 # Neither `self` or `dest` has to be real paths or to exist in directories since
497 # the resolution is only done with string manipulations and without any access to
498 # the underlying file system.
500 # If `self` and `dest` are the same directory, the empty string is returned:
502 # assert "foo".relpath("foo") == ""
503 # assert "foo/../bar".relpath("bar") == ""
505 # The empty string and "." designate both the current directory:
507 # assert "".relpath("foo/bar") == "foo/bar"
508 # assert ".".relpath("foo/bar") == "foo/bar"
509 # assert "foo/bar".relpath("") == "../.."
510 # assert "/" + "/".relpath(".") == getcwd
511 fun relpath
(dest
: String): String
514 var from
= (cwd
/self).simplify_path
.split
("/")
515 if from
.last
.is_empty
then from
.pop
# case for the root directory
516 var to
= (cwd
/dest
).simplify_path
.split
("/")
517 if to
.last
.is_empty
then to
.pop
# case for the root directory
519 # Remove common prefixes
520 while not from
.is_empty
and not to
.is_empty
and from
.first
== to
.first
do
525 # Result is going up in `from` with ".." then going down following `to`
526 var from_len
= from
.length
527 if from_len
== 0 then return to
.join
("/")
528 var up
= "../"*(from_len-1
) + ".."
529 if to
.is_empty
then return up
530 var res
= up
+ "/" + to
.join
("/")
534 # Create a directory (and all intermediate directories if needed)
537 var dirs
= self.split_with
("/")
538 var path
= new FlatBuffer
539 if dirs
.is_empty
then return
540 if dirs
[0].is_empty
then
541 # it was a starting /
545 if d
.is_empty
then continue
548 path
.to_s
.to_cstring
.file_mkdir
552 # Delete a directory and all of its content, return `true` on success
554 # Does not go through symbolic links and may get stuck in a cycle if there
555 # is a cycle in the filesystem.
559 for file
in self.files
do
560 var file_path
= self.join_path
(file
)
561 var stat
= file_path
.file_lstat
563 ok
= file_path
.rmdir
and ok
565 ok
= file_path
.file_delete
and ok
570 # Delete the directory itself
571 if ok
then to_cstring
.rmdir
576 # Change the current working directory
579 # assert getcwd == "/etc"
581 # assert getcwd == "/"
584 fun chdir
do to_cstring
.file_chdir
586 # Return right-most extension (without the dot)
588 # Only the last extension is returned.
589 # There is no special case for combined extensions.
591 # assert "file.txt".file_extension == "txt"
592 # assert "file.tar.gz".file_extension == "gz"
594 # For file without extension, `null` is returned.
595 # Hoever, for trailing dot, `""` is returned.
597 # assert "file".file_extension == null
598 # assert "file.".file_extension == ""
600 # The starting dot of hidden files is never considered.
602 # assert ".file.txt".file_extension == "txt"
603 # assert ".file".file_extension == null
604 fun file_extension
: nullable String
606 var last_slash
= chars
.last_index_of
('.')
607 if last_slash
> 0 then
608 return substring
( last_slash
+1, length
)
614 # returns files contained within the directory represented by self
615 fun files
: Set[ String ] is extern import HashSet[String], HashSet[String].add
, NativeString.to_s
, String.to_cstring
, HashSet[String].as(Set[String]) `{
619 dir_path = String_to_cstring( recv );
620 if ((dir = opendir(dir_path)) == NULL)
627 HashSet_of_String results;
631 results = new_HashSet_of_String();
633 while ( ( de = readdir( dir ) ) != NULL )
634 if ( strcmp( de->d_name, ".." ) != 0 &&
635 strcmp( de->d_name, "." ) != 0 )
637 file_name = NativeString_to_s( strdup( de->d_name ) );
638 HashSet_of_String_add( results, file_name );
642 return HashSet_of_String_as_Set_of_String( results );
647 redef class NativeString
648 private fun file_exists
: Bool is extern "string_NativeString_NativeString_file_exists_0"
649 private fun file_stat
: FileStat is extern "string_NativeString_NativeString_file_stat_0"
650 private fun file_lstat
: FileStat `{
651 struct stat* stat_element;
653 stat_element = malloc(sizeof(struct stat));
654 res = lstat(recv, stat_element);
655 if (res == -1) return NULL;
658 private fun file_mkdir
: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
659 private fun rmdir
: Bool `{ return rmdir(recv); `}
660 private fun file_delete: Bool is extern "string_NativeString_NativeString_file_delete_0"
661 private fun file_chdir is extern "string_NativeString_NativeString_file_chdir_0"
662 private fun file_realpath: NativeString is extern "file_NativeString_realpath"
665 # This class is system dependent ... must reify the vfs
666 extern class FileStat `{ struct stat * `}
667 # Returns the permission bits of file
668 fun mode
: Int is extern "file_FileStat_FileStat_mode_0"
669 # Returns the last access time
670 fun atime
: Int is extern "file_FileStat_FileStat_atime_0"
671 # Returns the last status change time
672 fun ctime
: Int is extern "file_FileStat_FileStat_ctime_0"
673 # Returns the last modification time
674 fun mtime
: Int is extern "file_FileStat_FileStat_mtime_0"
676 fun size
: Int is extern "file_FileStat_FileStat_size_0"
678 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
679 fun is_reg
: Bool `{ return S_ISREG(recv->st_mode); `}
680 # Returns true if it is a directory
681 fun is_dir: Bool `{ return S_ISDIR(recv->st_mode); `}
682 # Returns true if it is a character device
683 fun is_chr
: Bool `{ return S_ISCHR(recv->st_mode); `}
684 # Returns true if it is a block device
685 fun is_blk: Bool `{ return S_ISBLK(recv->st_mode); `}
686 # Returns true if the type is fifo
687 fun is_fifo
: Bool `{ return S_ISFIFO(recv->st_mode); `}
688 # Returns true if the type is a link
689 fun is_lnk: Bool `{ return S_ISLNK(recv->st_mode); `}
690 # Returns true if the type is a socket
691 fun is_sock
: Bool `{ return S_ISSOCK(recv->st_mode); `}
694 # Instance of this class are standard FILE * pointers
695 private extern class NativeFile `{ FILE* `}
696 fun io_read
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
697 fun io_write
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
698 fun io_close
: Int is extern "file_NativeFile_NativeFile_io_close_0"
699 fun file_stat
: FileStat is extern "file_NativeFile_NativeFile_file_stat_0"
700 fun fileno
: Int `{ return fileno(recv); `}
701 # Flushes the buffer, forcing the write operation
702 fun flush: Int is extern "fflush"
703 # Used to specify how the buffering will be handled for the current stream.
704 fun set_buffering_type(buf_length: Int, mode: Int): Int is extern "file_NativeFile_NativeFile_set_buffering_type_0"
706 new io_open_read(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
707 new io_open_write(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
708 new native_stdin is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
709 new native_stdout is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
710 new native_stderr is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
716 var stdin: PollableIStream = new Stdin is protected writable
719 var stdout: OStream = new Stdout is protected writable
721 # Standard output for errors
722 var stderr: OStream = new Stderr is protected writable
724 # Enumeration for buffer mode full (flushes when buffer is full)
725 fun buffer_mode_full: Int is extern "file_Sys_Sys_buffer_mode_full_0"
726 # Enumeration for buffer mode line (flushes when a `\n
` is encountered)
727 fun buffer_mode_line: Int is extern "file_Sys_Sys_buffer_mode_line_0"
728 # Enumeration for buffer mode none (flushes ASAP when something is written)
729 fun buffer_mode_none: Int is extern "file_Sys_Sys_buffer_mode_none_0"
731 # returns first available stream to read or write to
732 # return null on interruption (possibly a signal)
733 protected fun poll( streams : Sequence[FStream] ) : nullable FStream
735 var in_fds = new Array[Int]
736 var out_fds = new Array[Int]
737 var fd_to_stream = new HashMap[Int,FStream]
740 if s isa IFStream then in_fds.add( fd )
741 if s isa OFStream then out_fds.add( fd )
746 var polled_fd = intern_poll( in_fds, out_fds )
748 if polled_fd == null then
751 return fd_to_stream[polled_fd]
755 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) `{
756 int in_len
, out_len
, total_len
;
757 struct pollfd
*c_fds
;
760 int first_polled_fd
= -1;
763 in_len
= Array_of_Int_length( in_fds
);
764 out_len
= Array_of_Int_length( out_fds
);
765 total_len
= in_len
+ out_len
;
766 c_fds
= malloc
( sizeof
(struct pollfd
) * total_len
);
769 for ( i
=0; i
<in_len
; i
++ ) {
771 fd
= Array_of_Int__index( in_fds
, i
);
774 c_fds
[i
].events
= POLLIN;
778 for ( i
=0; i
<out_len
; i
++ ) {
780 fd
= Array_of_Int__index( out_fds
, i
);
783 c_fds
[i
].events
= POLLOUT;
786 /* poll all fds
, unlimited timeout
*/
787 result
= poll
( c_fds
, total_len
, -1 );
790 /* analyse results
*/
791 for ( i
=0; i
<total_len
; i
++ )
792 if ( c_fds
[i
].revents
& c_fds
[i
].events
|| /* awaited event
*/
793 c_fds
[i
].revents
& POLLHUP ) /* closed
*/
795 first_polled_fd
= c_fds
[i
].fd
;
799 return Int_as_nullable( first_polled_fd
);
801 else if ( result
< 0 )
802 fprintf
( stderr
, "Error in Stream:poll: %s\n", strerror
( errno
) );
809 # Print `objects
` on the standard output (`stdout
`).
810 protected fun printn(objects: Object...)
812 sys.stdout.write(objects.to_s)
815 # Print an `object
` on the standard output (`stdout
`) and add a newline.
816 protected fun print(object: Object)
818 sys.stdout.write(object.to_s)
819 sys.stdout.write("\n")
822 # Read a character from the standard input (`stdin
`).
823 protected fun getc: Char
825 return sys.stdin.read_char.ascii
828 # Read a line from the standard input (`stdin
`).
829 protected fun gets: String
831 return sys.stdin.read_line
834 # Return the working (current) directory
835 protected fun getcwd: String do return file_getcwd.to_s
836 private fun file_getcwd: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"