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
56 # Open the same file again.
57 # The original path is reused, therefore the reopened file can be a different file.
60 if not eof
and not _file
.address_is_null
then close
62 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
63 if _file
.address_is_null
then
64 last_error
= new IOError("Error: Opening file at '{path.as(not null)}' failed with '{sys.errno.strerror}'")
75 if _file
.address_is_null
then return
76 var i
= _file
.io_close
83 var nb
= _file
.io_read
(_buffer
.items
, _buffer
.capacity
)
93 redef var end_reached
: Bool = false
95 # Open the file at `path` for reading.
96 init open
(path
: String)
100 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
101 if _file
.address_is_null
then
102 last_error
= new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
107 init from_fd
(fd
: Int) do
110 _file
= fd
.fd_to_stream
(read_only
)
111 if _file
.address_is_null
then
112 last_error
= new IOError("Error: Converting fd {fd} to stream failed with '{sys.errno.strerror}'")
125 if last_error
!= null then return
126 if not _is_writable
then
127 last_error
= new IOError("Cannot write to non-writable stream")
130 if s
isa FlatText then
131 write_native
(s
.to_cstring
, s
.length
)
133 for i
in s
.substrings
do write_native
(i
.to_cstring
, i
.length
)
139 if _file
.address_is_null
then
140 if last_error
!= null then return
141 last_error
= new IOError("Cannot close unopened write stream")
145 var i
= _file
.io_close
147 last_error
= new IOError("Close failed due to error {sys.errno.strerror}")
151 redef var is_writable
= false
153 # Write `len` bytes from `native`.
154 private fun write_native
(native
: NativeString, len
: Int)
156 if last_error
!= null then return
157 if not _is_writable
then
158 last_error
= new IOError("Cannot write to non-writable stream")
161 if _file
.address_is_null
then
162 last_error
= new IOError("Writing on a null stream")
166 var err
= _file
.io_write
(native
, len
)
169 last_error
= new IOError("Problem in writing : {err} {len} \n")
173 # Open the file at `path` for writing.
174 init open
(path
: String)
176 _file
= new NativeFile.io_open_write
(path
.to_cstring
)
179 if _file
.address_is_null
then
180 last_error
= new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
185 # Creates a new File stream from a file descriptor
186 init from_fd
(fd
: Int) do
188 _file
= fd
.fd_to_stream
(wipe_write
)
190 if _file
.address_is_null
then
191 last_error
= new IOError("Error: Opening stream from file descriptor {fd} failed with '{sys.errno.strerror}'")
198 # Creates a file stream from a file descriptor `fd` using the file access `mode`.
200 # NOTE: The `mode` specified must be compatible with the one used in the file descriptor.
201 private fun fd_to_stream
(mode
: NativeString): NativeFile is extern "file_int_fdtostream"
204 # Constant for read-only file streams
205 private fun read_only
: NativeString do return "r".to_cstring
207 # Constant for write-only file streams
209 # If a stream is opened on a file with this method,
210 # it will wipe the previous file if any.
211 # Else, it will create the file.
212 private fun wipe_write
: NativeString do return "w".to_cstring
214 ###############################################################################
220 _file
= new NativeFile.native_stdin
225 redef fun poll_in
: Bool is extern "file_stdin_poll_in"
231 _file
= new NativeFile.native_stdout
240 _file
= new NativeFile.native_stderr
246 ###############################################################################
248 redef class Streamable
249 # Like `write_to` but take care of creating the file
250 fun write_to_file
(filepath
: String)
252 var stream
= new OFStream.open
(filepath
)
259 # return true if a file with this names exists
260 fun file_exists
: Bool do return to_cstring
.file_exists
262 # The status of a file. see POSIX stat(2).
263 fun file_stat
: FileStat do return to_cstring
.file_stat
265 # The status of a file or of a symlink. see POSIX lstat(2).
266 fun file_lstat
: FileStat do return to_cstring
.file_lstat
268 # Remove a file, return true if success
269 fun file_delete
: Bool do return to_cstring
.file_delete
271 # Copy content of file at `self` to `dest`
272 fun file_copy_to
(dest
: String)
274 var input
= new IFStream.open
(self)
275 var output
= new OFStream.open
(dest
)
277 while not input
.eof
do
278 var buffer
= input
.read
(1024)
286 # Remove the trailing extension `ext`.
288 # `ext` usually starts with a dot but could be anything.
290 # assert "file.txt".strip_extension(".txt") == "file"
291 # assert "file.txt".strip_extension("le.txt") == "fi"
292 # assert "file.txt".strip_extension("xt") == "file.t"
294 # if `ext` is not present, `self` is returned unmodified.
296 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
297 fun strip_extension
(ext
: String): String
299 if has_suffix
(ext
) then
300 return substring
(0, length
- ext
.length
)
305 # Extract the basename of a path and remove the extension
307 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
308 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
309 # assert "path/to".basename(".ext") == "to"
310 # assert "path/to/".basename(".ext") == "to"
311 # assert "path".basename("") == "path"
312 # assert "/path".basename("") == "path"
313 # assert "/".basename("") == "/"
314 # assert "".basename("") == ""
315 fun basename
(ext
: String): String
317 var l
= length
- 1 # Index of the last char
318 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
319 if l
== 0 then return "/"
320 var pos
= chars
.last_index_of_from
('/', l
)
323 n
= substring
(pos
+1, l-pos
)
325 return n
.strip_extension
(ext
)
328 # Extract the dirname of a path
330 # assert "/path/to/a_file.ext".dirname == "/path/to"
331 # assert "path/to/a_file.ext".dirname == "path/to"
332 # assert "path/to".dirname == "path"
333 # assert "path/to/".dirname == "path"
334 # assert "path".dirname == "."
335 # assert "/path".dirname == "/"
336 # assert "/".dirname == "/"
337 # assert "".dirname == "."
340 var l
= length
- 1 # Index of the last char
341 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
342 var pos
= chars
.last_index_of_from
('/', l
)
344 return substring
(0, pos
)
345 else if pos
== 0 then
352 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
353 fun realpath
: String do
354 var cs
= to_cstring
.file_realpath
355 var res
= cs
.to_s_with_copy
356 # cs.free_malloc # FIXME memory leak
360 # Simplify a file path by remove useless ".", removing "//", and resolving ".."
361 # ".." are not resolved if they start the path
362 # starting "/" is not removed
363 # trainling "/" is removed
365 # Note that the method only wonrk on the string:
366 # * no I/O access is performed
367 # * the validity of the path is not checked
369 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
370 # assert "../dir/file".simplify_path == "../dir/file"
371 # assert "dir/../../".simplify_path == ".."
372 # assert "dir/..".simplify_path == "."
373 # assert "//absolute//path/".simplify_path == "/absolute/path"
374 # assert "//absolute//../".simplify_path == "/"
375 fun simplify_path
: String
377 var a
= self.split_with
("/")
378 var a2
= new Array[String]
380 if x
== "." then continue
381 if x
== "" and not a2
.is_empty
then continue
382 if x
== ".." and not a2
.is_empty
and a2
.last
!= ".." then
388 if a2
.is_empty
then return "."
389 if a2
.length
== 1 and a2
.first
== "" then return "/"
393 # Correctly join two path using the directory separator.
395 # Using a standard "{self}/{path}" does not work in the following cases:
398 # * `path` ends with `'/'`.
399 # * `path` starts with `'/'`.
401 # This method ensures that the join is valid.
403 # assert "hello".join_path("world") == "hello/world"
404 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
405 # assert "".join_path("world") == "world"
406 # assert "hello".join_path("/world") == "/world"
407 # assert "hello/".join_path("world") == "hello/world"
408 # assert "hello/".join_path("/world") == "/world"
410 # Note: You may want to use `simplify_path` on the result.
412 # Note: This method works only with POSIX paths.
413 fun join_path
(path
: String): String
415 if path
.is_empty
then return self
416 if self.is_empty
then return path
417 if path
.chars
[0] == '/' then return path
418 if self.last
== '/' then return "{self}{path}"
419 return "{self}/{path}"
422 # Convert the path (`self`) to a program name.
424 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
425 # used as a program name. In order to do that, prepend `./` if needed.
427 # assert "foo".to_program_name == "./foo"
428 # assert "/foo".to_program_name == "/foo"
429 # assert "".to_program_name == "./" # At least, your shell will detect the error.
430 fun to_program_name
: String do
431 if self.has_prefix
("/") then
438 # Alias for `join_path`
440 # assert "hello" / "world" == "hello/world"
441 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
442 # assert "" / "world" == "world"
443 # assert "/hello" / "/world" == "/world"
445 # This operator is quite useful for chaining changes of path.
446 # The next one being relative to the previous one.
450 # var c = "baz/foobar"
451 # assert a/b/c == "/bar/baz/foobar"
452 fun /(path
: String): String do return join_path
(path
)
454 # Returns the relative path needed to go from `self` to `dest`.
456 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
457 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
459 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
461 # In some cases, the result is still independent of the current directory:
463 # assert "foo/bar".relpath("..") == "../../.."
465 # In other cases, parts of the current directory may be exhibited:
467 # var p = "../foo/bar".relpath("baz")
468 # var c = getcwd.basename("")
469 # assert p == "../../{c}/baz"
471 # For path resolution independent of the current directory (eg. for paths in URL),
472 # or to use an other starting directory than the current directory,
473 # just force absolute paths:
475 # var start = "/a/b/c/d"
476 # var p2 = (start/"../foo/bar").relpath(start/"baz")
477 # assert p2 == "../../d/baz"
480 # Neither `self` or `dest` has to be real paths or to exist in directories since
481 # the resolution is only done with string manipulations and without any access to
482 # the underlying file system.
484 # If `self` and `dest` are the same directory, the empty string is returned:
486 # assert "foo".relpath("foo") == ""
487 # assert "foo/../bar".relpath("bar") == ""
489 # The empty string and "." designate both the current directory:
491 # assert "".relpath("foo/bar") == "foo/bar"
492 # assert ".".relpath("foo/bar") == "foo/bar"
493 # assert "foo/bar".relpath("") == "../.."
494 # assert "/" + "/".relpath(".") == getcwd
495 fun relpath
(dest
: String): String
498 var from
= (cwd
/self).simplify_path
.split
("/")
499 if from
.last
.is_empty
then from
.pop
# case for the root directory
500 var to
= (cwd
/dest
).simplify_path
.split
("/")
501 if to
.last
.is_empty
then to
.pop
# case for the root directory
503 # Remove common prefixes
504 while not from
.is_empty
and not to
.is_empty
and from
.first
== to
.first
do
509 # Result is going up in `from` with ".." then going down following `to`
510 var from_len
= from
.length
511 if from_len
== 0 then return to
.join
("/")
512 var up
= "../"*(from_len-1
) + ".."
513 if to
.is_empty
then return up
514 var res
= up
+ "/" + to
.join
("/")
518 # Create a directory (and all intermediate directories if needed)
521 var dirs
= self.split_with
("/")
522 var path
= new FlatBuffer
523 if dirs
.is_empty
then return
524 if dirs
[0].is_empty
then
525 # it was a starting /
529 if d
.is_empty
then continue
532 path
.to_s
.to_cstring
.file_mkdir
536 # Delete a directory and all of its content, return `true` on success
538 # Does not go through symbolic links and may get stuck in a cycle if there
539 # is a cycle in the filesystem.
543 for file
in self.files
do
544 var file_path
= self.join_path
(file
)
545 var stat
= file_path
.file_lstat
547 ok
= file_path
.rmdir
and ok
549 ok
= file_path
.file_delete
and ok
554 # Delete the directory itself
555 if ok
then to_cstring
.rmdir
560 # Change the current working directory
563 # assert getcwd == "/etc"
565 # assert getcwd == "/"
568 fun chdir
do to_cstring
.file_chdir
570 # Return right-most extension (without the dot)
572 # Only the last extension is returned.
573 # There is no special case for combined extensions.
575 # assert "file.txt".file_extension == "txt"
576 # assert "file.tar.gz".file_extension == "gz"
578 # For file without extension, `null` is returned.
579 # Hoever, for trailing dot, `""` is returned.
581 # assert "file".file_extension == null
582 # assert "file.".file_extension == ""
584 # The starting dot of hidden files is never considered.
586 # assert ".file.txt".file_extension == "txt"
587 # assert ".file".file_extension == null
588 fun file_extension
: nullable String
590 var last_slash
= chars
.last_index_of
('.')
591 if last_slash
> 0 then
592 return substring
( last_slash
+1, length
)
598 # returns files contained within the directory represented by self
599 fun files
: Set[ String ] is extern import HashSet[String], HashSet[String].add
, NativeString.to_s
, String.to_cstring
, HashSet[String].as(Set[String]) `{
603 dir_path = String_to_cstring( recv );
604 if ((dir = opendir(dir_path)) == NULL)
611 HashSet_of_String results;
615 results = new_HashSet_of_String();
617 while ( ( de = readdir( dir ) ) != NULL )
618 if ( strcmp( de->d_name, ".." ) != 0 &&
619 strcmp( de->d_name, "." ) != 0 )
621 file_name = NativeString_to_s( strdup( de->d_name ) );
622 HashSet_of_String_add( results, file_name );
626 return HashSet_of_String_as_Set_of_String( results );
631 redef class NativeString
632 private fun file_exists
: Bool is extern "string_NativeString_NativeString_file_exists_0"
633 private fun file_stat
: FileStat is extern "string_NativeString_NativeString_file_stat_0"
634 private fun file_lstat
: FileStat `{
635 struct stat* stat_element;
637 stat_element = malloc(sizeof(struct stat));
638 res = lstat(recv, stat_element);
639 if (res == -1) return NULL;
642 private fun file_mkdir
: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
643 private fun rmdir
: Bool `{ return rmdir(recv); `}
644 private fun file_delete: Bool is extern "string_NativeString_NativeString_file_delete_0"
645 private fun file_chdir is extern "string_NativeString_NativeString_file_chdir_0"
646 private fun file_realpath: NativeString is extern "file_NativeString_realpath"
649 # This class is system dependent ... must reify the vfs
650 extern class FileStat `{ struct stat * `}
651 # Returns the permission bits of file
652 fun mode
: Int is extern "file_FileStat_FileStat_mode_0"
653 # Returns the last access time
654 fun atime
: Int is extern "file_FileStat_FileStat_atime_0"
655 # Returns the last status change time
656 fun ctime
: Int is extern "file_FileStat_FileStat_ctime_0"
657 # Returns the last modification time
658 fun mtime
: Int is extern "file_FileStat_FileStat_mtime_0"
660 fun size
: Int is extern "file_FileStat_FileStat_size_0"
662 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
663 fun is_reg
: Bool `{ return S_ISREG(recv->st_mode); `}
664 # Returns true if it is a directory
665 fun is_dir: Bool `{ return S_ISDIR(recv->st_mode); `}
666 # Returns true if it is a character device
667 fun is_chr
: Bool `{ return S_ISCHR(recv->st_mode); `}
668 # Returns true if it is a block device
669 fun is_blk: Bool `{ return S_ISBLK(recv->st_mode); `}
670 # Returns true if the type is fifo
671 fun is_fifo
: Bool `{ return S_ISFIFO(recv->st_mode); `}
672 # Returns true if the type is a link
673 fun is_lnk: Bool `{ return S_ISLNK(recv->st_mode); `}
674 # Returns true if the type is a socket
675 fun is_sock
: Bool `{ return S_ISSOCK(recv->st_mode); `}
678 # Instance of this class are standard FILE * pointers
679 private extern class NativeFile `{ FILE* `}
680 fun io_read
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
681 fun io_write
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
682 fun io_close
: Int is extern "file_NativeFile_NativeFile_io_close_0"
683 fun file_stat
: FileStat is extern "file_NativeFile_NativeFile_file_stat_0"
684 fun fileno
: Int `{ return fileno(recv); `}
686 new io_open_read(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
687 new io_open_write(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
688 new native_stdin is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
689 new native_stdout is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
690 new native_stderr is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
696 var stdin: PollableIStream = new Stdin is protected writable
699 var stdout: OStream = new Stdout is protected writable
701 # Standard output for errors
702 var stderr: OStream = new Stderr is protected writable
704 # Enumeration for buffer mode full (flushes when buffer is full)
705 fun buffer_mode_full: Int is extern "file_Sys_Sys_buffer_mode_full_0"
706 # Enumeration for buffer mode line (flushes when a `\n
` is encountered)
707 fun buffer_mode_line: Int is extern "file_Sys_Sys_buffer_mode_line_0"
708 # Enumeration for buffer mode none (flushes ASAP when something is written)
709 fun buffer_mode_none: Int is extern "file_Sys_Sys_buffer_mode_none_0"
711 # returns first available stream to read or write to
712 # return null on interruption (possibly a signal)
713 protected fun poll( streams : Sequence[FStream] ) : nullable FStream
715 var in_fds = new Array[Int]
716 var out_fds = new Array[Int]
717 var fd_to_stream = new HashMap[Int,FStream]
720 if s isa IFStream then in_fds.add( fd )
721 if s isa OFStream then out_fds.add( fd )
726 var polled_fd = intern_poll( in_fds, out_fds )
728 if polled_fd == null then
731 return fd_to_stream[polled_fd]
735 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) `{
736 int in_len
, out_len
, total_len
;
737 struct pollfd
*c_fds
;
740 int first_polled_fd
= -1;
743 in_len
= Array_of_Int_length( in_fds
);
744 out_len
= Array_of_Int_length( out_fds
);
745 total_len
= in_len
+ out_len
;
746 c_fds
= malloc
( sizeof
(struct pollfd
) * total_len
);
749 for ( i
=0; i
<in_len
; i
++ ) {
751 fd
= Array_of_Int__index( in_fds
, i
);
754 c_fds
[i
].events
= POLLIN;
758 for ( i
=0; i
<out_len
; i
++ ) {
760 fd
= Array_of_Int__index( out_fds
, i
);
763 c_fds
[i
].events
= POLLOUT;
766 /* poll all fds
, unlimited timeout
*/
767 result
= poll
( c_fds
, total_len
, -1 );
770 /* analyse results
*/
771 for ( i
=0; i
<total_len
; i
++ )
772 if ( c_fds
[i
].revents
& c_fds
[i
].events
|| /* awaited event
*/
773 c_fds
[i
].revents
& POLLHUP ) /* closed
*/
775 first_polled_fd
= c_fds
[i
].fd
;
779 return Int_as_nullable( first_polled_fd
);
781 else if ( result
< 0 )
782 fprintf
( stderr
, "Error in Stream:poll: %s\n", strerror
( errno
) );
789 # Print `objects
` on the standard output (`stdout
`).
790 protected fun printn(objects: Object...)
792 sys.stdout.write(objects.to_s)
795 # Print an `object
` on the standard output (`stdout
`) and add a newline.
796 protected fun print(object: Object)
798 sys.stdout.write(object.to_s)
799 sys.stdout.write("\n")
802 # Read a character from the standard input (`stdin
`).
803 protected fun getc: Char
805 return sys.stdin.read_char.ascii
808 # Read a line from the standard input (`stdin
`).
809 protected fun gets: String
811 return sys.stdin.read_line
814 # Return the working (current) directory
815 protected fun getcwd: String do return file_getcwd.to_s
816 private fun file_getcwd: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"