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>
32 # File Abstract Stream
33 abstract class FStream
35 # The path of the file.
36 var path
: nullable String = null
39 private var file
: nullable NativeFile = null
41 fun file_stat
: FileStat do return _file
.file_stat
43 # File descriptor of this file
44 fun fd
: Int do return _file
.fileno
54 # Open the same file again.
55 # The original path is reused, therefore the reopened file can be a different file.
58 if not eof
and not _file
.address_is_null
then close
60 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
61 if _file
.address_is_null
then
62 last_error
= new IOError("Error: Opening file at '{path.as(not null)}' failed with '{sys.errno.strerror}'")
73 if _file
.address_is_null
then return
74 var i
= _file
.io_close
81 var nb
= _file
.io_read
(_buffer
.items
, _buffer
.capacity
)
91 redef var end_reached
: Bool = false
93 # Open the file at `path` for reading.
94 init open
(path
: String)
98 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
99 if _file
.address_is_null
then
100 last_error
= new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
114 if last_error
!= null then return
115 if not _is_writable
then
116 last_error
= new IOError("Cannot write to non-writable stream")
119 if s
isa FlatText then
120 write_native
(s
.to_cstring
, s
.length
)
122 for i
in s
.substrings
do write_native
(i
.to_cstring
, i
.length
)
128 if _file
.address_is_null
then
129 if last_error
!= null then return
130 last_error
= new IOError("Cannot close unopened write stream")
134 var i
= _file
.io_close
136 last_error
= new IOError("Close failed due to error {sys.errno.strerror}")
140 redef var is_writable
= false
142 # Write `len` bytes from `native`.
143 private fun write_native
(native
: NativeString, len
: Int)
145 if last_error
!= null then return
146 if not _is_writable
then
147 last_error
= new IOError("Cannot write to non-writable stream")
150 if _file
.address_is_null
then
151 last_error
= new IOError("Writing on a null stream")
155 var err
= _file
.io_write
(native
, len
)
158 last_error
= new IOError("Problem in writing : {err} {len} \n")
162 # Open the file at `path` for writing.
163 init open
(path
: String)
165 _file
= new NativeFile.io_open_write
(path
.to_cstring
)
168 if _file
.address_is_null
then
169 last_error
= new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
175 ###############################################################################
181 _file
= new NativeFile.native_stdin
186 redef fun poll_in
: Bool is extern "file_stdin_poll_in"
192 _file
= new NativeFile.native_stdout
201 _file
= new NativeFile.native_stderr
207 ###############################################################################
209 redef class Streamable
210 # Like `write_to` but take care of creating the file
211 fun write_to_file
(filepath
: String)
213 var stream
= new OFStream.open
(filepath
)
220 # return true if a file with this names exists
221 fun file_exists
: Bool do return to_cstring
.file_exists
223 # The status of a file. see POSIX stat(2).
224 fun file_stat
: FileStat do return to_cstring
.file_stat
226 # The status of a file or of a symlink. see POSIX lstat(2).
227 fun file_lstat
: FileStat do return to_cstring
.file_lstat
229 # Remove a file, return true if success
230 fun file_delete
: Bool do return to_cstring
.file_delete
232 # Copy content of file at `self` to `dest`
233 fun file_copy_to
(dest
: String)
235 var input
= new IFStream.open
(self)
236 var output
= new OFStream.open
(dest
)
238 while not input
.eof
do
239 var buffer
= input
.read
(1024)
247 # Remove the trailing extension `ext`.
249 # `ext` usually starts with a dot but could be anything.
251 # assert "file.txt".strip_extension(".txt") == "file"
252 # assert "file.txt".strip_extension("le.txt") == "fi"
253 # assert "file.txt".strip_extension("xt") == "file.t"
255 # if `ext` is not present, `self` is returned unmodified.
257 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
258 fun strip_extension
(ext
: String): String
260 if has_suffix
(ext
) then
261 return substring
(0, length
- ext
.length
)
266 # Extract the basename of a path and remove the extension
268 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
269 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
270 # assert "path/to".basename(".ext") == "to"
271 # assert "path/to/".basename(".ext") == "to"
272 # assert "path".basename("") == "path"
273 # assert "/path".basename("") == "path"
274 # assert "/".basename("") == "/"
275 # assert "".basename("") == ""
276 fun basename
(ext
: String): String
278 var l
= length
- 1 # Index of the last char
279 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
280 if l
== 0 then return "/"
281 var pos
= chars
.last_index_of_from
('/', l
)
284 n
= substring
(pos
+1, l-pos
)
286 return n
.strip_extension
(ext
)
289 # Extract the dirname of a path
291 # assert "/path/to/a_file.ext".dirname == "/path/to"
292 # assert "path/to/a_file.ext".dirname == "path/to"
293 # assert "path/to".dirname == "path"
294 # assert "path/to/".dirname == "path"
295 # assert "path".dirname == "."
296 # assert "/path".dirname == "/"
297 # assert "/".dirname == "/"
298 # assert "".dirname == "."
301 var l
= length
- 1 # Index of the last char
302 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
303 var pos
= chars
.last_index_of_from
('/', l
)
305 return substring
(0, pos
)
306 else if pos
== 0 then
313 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
314 fun realpath
: String do
315 var cs
= to_cstring
.file_realpath
316 var res
= cs
.to_s_with_copy
317 # cs.free_malloc # FIXME memory leak
321 # Simplify a file path by remove useless ".", removing "//", and resolving ".."
322 # ".." are not resolved if they start the path
323 # starting "/" is not removed
324 # trainling "/" is removed
326 # Note that the method only wonrk on the string:
327 # * no I/O access is performed
328 # * the validity of the path is not checked
330 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
331 # assert "../dir/file".simplify_path == "../dir/file"
332 # assert "dir/../../".simplify_path == ".."
333 # assert "dir/..".simplify_path == "."
334 # assert "//absolute//path/".simplify_path == "/absolute/path"
335 # assert "//absolute//../".simplify_path == "/"
336 fun simplify_path
: String
338 var a
= self.split_with
("/")
339 var a2
= new Array[String]
341 if x
== "." then continue
342 if x
== "" and not a2
.is_empty
then continue
343 if x
== ".." and not a2
.is_empty
and a2
.last
!= ".." then
349 if a2
.is_empty
then return "."
350 if a2
.length
== 1 and a2
.first
== "" then return "/"
354 # Correctly join two path using the directory separator.
356 # Using a standard "{self}/{path}" does not work in the following cases:
359 # * `path` ends with `'/'`.
360 # * `path` starts with `'/'`.
362 # This method ensures that the join is valid.
364 # assert "hello".join_path("world") == "hello/world"
365 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
366 # assert "".join_path("world") == "world"
367 # assert "hello".join_path("/world") == "/world"
368 # assert "hello/".join_path("world") == "hello/world"
369 # assert "hello/".join_path("/world") == "/world"
371 # Note: You may want to use `simplify_path` on the result.
373 # Note: This method works only with POSIX paths.
374 fun join_path
(path
: String): String
376 if path
.is_empty
then return self
377 if self.is_empty
then return path
378 if path
.chars
[0] == '/' then return path
379 if self.last
== '/' then return "{self}{path}"
380 return "{self}/{path}"
383 # Convert the path (`self`) to a program name.
385 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
386 # used as a program name. In order to do that, prepend `./` if needed.
388 # assert "foo".to_program_name == "./foo"
389 # assert "/foo".to_program_name == "/foo"
390 # assert "".to_program_name == "./" # At least, your shell will detect the error.
391 fun to_program_name
: String do
392 if self.has_prefix
("/") then
399 # Alias for `join_path`
401 # assert "hello" / "world" == "hello/world"
402 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
403 # assert "" / "world" == "world"
404 # assert "/hello" / "/world" == "/world"
406 # This operator is quite useful for chaining changes of path.
407 # The next one being relative to the previous one.
411 # var c = "baz/foobar"
412 # assert a/b/c == "/bar/baz/foobar"
413 fun /(path
: String): String do return join_path
(path
)
415 # Returns the relative path needed to go from `self` to `dest`.
417 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
418 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
420 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
422 # In some cases, the result is still independent of the current directory:
424 # assert "foo/bar".relpath("..") == "../../.."
426 # In other cases, parts of the current directory may be exhibited:
428 # var p = "../foo/bar".relpath("baz")
429 # var c = getcwd.basename("")
430 # assert p == "../../{c}/baz"
432 # For path resolution independent of the current directory (eg. for paths in URL),
433 # or to use an other starting directory than the current directory,
434 # just force absolute paths:
436 # var start = "/a/b/c/d"
437 # var p2 = (start/"../foo/bar").relpath(start/"baz")
438 # assert p2 == "../../d/baz"
441 # Neither `self` or `dest` has to be real paths or to exist in directories since
442 # the resolution is only done with string manipulations and without any access to
443 # the underlying file system.
445 # If `self` and `dest` are the same directory, the empty string is returned:
447 # assert "foo".relpath("foo") == ""
448 # assert "foo/../bar".relpath("bar") == ""
450 # The empty string and "." designate both the current directory:
452 # assert "".relpath("foo/bar") == "foo/bar"
453 # assert ".".relpath("foo/bar") == "foo/bar"
454 # assert "foo/bar".relpath("") == "../.."
455 # assert "/" + "/".relpath(".") == getcwd
456 fun relpath
(dest
: String): String
459 var from
= (cwd
/self).simplify_path
.split
("/")
460 if from
.last
.is_empty
then from
.pop
# case for the root directory
461 var to
= (cwd
/dest
).simplify_path
.split
("/")
462 if to
.last
.is_empty
then to
.pop
# case for the root directory
464 # Remove common prefixes
465 while not from
.is_empty
and not to
.is_empty
and from
.first
== to
.first
do
470 # Result is going up in `from` with ".." then going down following `to`
471 var from_len
= from
.length
472 if from_len
== 0 then return to
.join
("/")
473 var up
= "../"*(from_len-1
) + ".."
474 if to
.is_empty
then return up
475 var res
= up
+ "/" + to
.join
("/")
479 # Create a directory (and all intermediate directories if needed)
482 var dirs
= self.split_with
("/")
483 var path
= new FlatBuffer
484 if dirs
.is_empty
then return
485 if dirs
[0].is_empty
then
486 # it was a starting /
490 if d
.is_empty
then continue
493 path
.to_s
.to_cstring
.file_mkdir
497 # Delete a directory and all of its content, return `true` on success
499 # Does not go through symbolic links and may get stuck in a cycle if there
500 # is a cycle in the filesystem.
504 for file
in self.files
do
505 var file_path
= self.join_path
(file
)
506 var stat
= file_path
.file_lstat
508 ok
= file_path
.rmdir
and ok
510 ok
= file_path
.file_delete
and ok
515 # Delete the directory itself
516 if ok
then to_cstring
.rmdir
521 # Change the current working directory
524 # assert getcwd == "/etc"
526 # assert getcwd == "/"
529 fun chdir
do to_cstring
.file_chdir
531 # Return right-most extension (without the dot)
533 # Only the last extension is returned.
534 # There is no special case for combined extensions.
536 # assert "file.txt".file_extension == "txt"
537 # assert "file.tar.gz".file_extension == "gz"
539 # For file without extension, `null` is returned.
540 # Hoever, for trailing dot, `""` is returned.
542 # assert "file".file_extension == null
543 # assert "file.".file_extension == ""
545 # The starting dot of hidden files is never considered.
547 # assert ".file.txt".file_extension == "txt"
548 # assert ".file".file_extension == null
549 fun file_extension
: nullable String
551 var last_slash
= chars
.last_index_of
('.')
552 if last_slash
> 0 then
553 return substring
( last_slash
+1, length
)
559 # returns files contained within the directory represented by self
560 fun files
: Set[ String ] is extern import HashSet[String], HashSet[String].add
, NativeString.to_s
, String.to_cstring
, HashSet[String].as(Set[String]) `{
564 dir_path = String_to_cstring( recv );
565 if ((dir = opendir(dir_path)) == NULL)
572 HashSet_of_String results;
576 results = new_HashSet_of_String();
578 while ( ( de = readdir( dir ) ) != NULL )
579 if ( strcmp( de->d_name, ".." ) != 0 &&
580 strcmp( de->d_name, "." ) != 0 )
582 file_name = NativeString_to_s( strdup( de->d_name ) );
583 HashSet_of_String_add( results, file_name );
587 return HashSet_of_String_as_Set_of_String( results );
592 redef class NativeString
593 private fun file_exists
: Bool is extern "string_NativeString_NativeString_file_exists_0"
594 private fun file_stat
: FileStat is extern "string_NativeString_NativeString_file_stat_0"
595 private fun file_lstat
: FileStat `{
596 struct stat* stat_element;
598 stat_element = malloc(sizeof(struct stat));
599 res = lstat(recv, stat_element);
600 if (res == -1) return NULL;
603 private fun file_mkdir
: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
604 private fun rmdir
: Bool `{ return rmdir(recv); `}
605 private fun file_delete: Bool is extern "string_NativeString_NativeString_file_delete_0"
606 private fun file_chdir is extern "string_NativeString_NativeString_file_chdir_0"
607 private fun file_realpath: NativeString is extern "file_NativeString_realpath"
610 # This class is system dependent ... must reify the vfs
611 extern class FileStat `{ struct stat * `}
612 # Returns the permission bits of file
613 fun mode
: Int is extern "file_FileStat_FileStat_mode_0"
614 # Returns the last access time
615 fun atime
: Int is extern "file_FileStat_FileStat_atime_0"
616 # Returns the last status change time
617 fun ctime
: Int is extern "file_FileStat_FileStat_ctime_0"
618 # Returns the last modification time
619 fun mtime
: Int is extern "file_FileStat_FileStat_mtime_0"
621 fun size
: Int is extern "file_FileStat_FileStat_size_0"
623 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
624 fun is_reg
: Bool `{ return S_ISREG(recv->st_mode); `}
625 # Returns true if it is a directory
626 fun is_dir: Bool `{ return S_ISDIR(recv->st_mode); `}
627 # Returns true if it is a character device
628 fun is_chr
: Bool `{ return S_ISCHR(recv->st_mode); `}
629 # Returns true if it is a block device
630 fun is_blk: Bool `{ return S_ISBLK(recv->st_mode); `}
631 # Returns true if the type is fifo
632 fun is_fifo
: Bool `{ return S_ISFIFO(recv->st_mode); `}
633 # Returns true if the type is a link
634 fun is_lnk: Bool `{ return S_ISLNK(recv->st_mode); `}
635 # Returns true if the type is a socket
636 fun is_sock
: Bool `{ return S_ISSOCK(recv->st_mode); `}
639 # Instance of this class are standard FILE * pointers
640 private extern class NativeFile `{ FILE* `}
641 fun io_read
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
642 fun io_write
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
643 fun io_close
: Int is extern "file_NativeFile_NativeFile_io_close_0"
644 fun file_stat
: FileStat is extern "file_NativeFile_NativeFile_file_stat_0"
645 fun fileno
: Int `{ return fileno(recv); `}
647 new io_open_read(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
648 new io_open_write(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
649 new native_stdin is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
650 new native_stdout is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
651 new native_stderr is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
657 var stdin: PollableIStream = new Stdin is protected writable
660 var stdout: OStream = new Stdout is protected writable
662 # Standard output for errors
663 var stderr: OStream = new Stderr is protected writable
667 # Print `objects
` on the standard output (`stdout
`).
668 protected fun printn(objects: Object...)
670 sys.stdout.write(objects.to_s)
673 # Print an `object
` on the standard output (`stdout
`) and add a newline.
674 protected fun print(object: Object)
676 sys.stdout.write(object.to_s)
677 sys.stdout.write("\n")
680 # Read a character from the standard input (`stdin
`).
681 protected fun getc: Char
683 return sys.stdin.read_char.ascii
686 # Read a line from the standard input (`stdin
`).
687 protected fun gets: String
689 return sys.stdin.read_line
692 # Return the working (current) directory
693 protected fun getcwd: String do return file_getcwd.to_s
694 private fun file_getcwd: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"