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 # The status of a file. see POSIX stat(2).
42 fun file_stat
: FileStat do return _file
.file_stat
44 # File descriptor of this file
45 fun fd
: Int do return _file
.fileno
55 # Open the same file again.
56 # The original path is reused, therefore the reopened file can be a different file.
60 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
75 var nb
= _file
.io_read
(_buffer
.items
, _buffer
.capacity
)
85 redef var end_reached
: Bool = false
87 # Open the file at `path` for reading.
88 init open
(path
: String)
92 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
93 assert not _file
.address_is_null
else
94 print
"Error: Opening file at '{path}' failed with '{sys.errno.strerror}'"
108 if s
isa FlatText then
109 write_native
(s
.to_cstring
, s
.length
)
111 for i
in s
.substrings
do write_native
(i
.to_cstring
, i
.length
)
121 redef var is_writable
= false
123 # Write `len` bytes from `native`.
124 private fun write_native
(native
: NativeString, len
: Int)
127 var err
= _file
.io_write
(native
, len
)
130 printn
("Problem in writing : ", err
, " ", len
, "\n")
134 # Open the file at `path` for writing.
135 init open
(path
: String)
137 _file
= new NativeFile.io_open_write
(path
.to_cstring
)
138 assert not _file
.address_is_null
else
139 print
"Error: Opening file at '{path}' failed with '{sys.errno.strerror}'"
146 ###############################################################################
148 # Standard input stream.
153 _file
= new NativeFile.native_stdin
158 redef fun poll_in
: Bool is extern "file_stdin_poll_in"
161 # Standard output stream.
165 _file
= new NativeFile.native_stdout
171 # Standard error stream.
175 _file
= new NativeFile.native_stderr
181 ###############################################################################
183 redef class Streamable
184 # Like `write_to` but take care of creating the file
185 fun write_to_file
(filepath
: String)
187 var stream
= new OFStream.open
(filepath
)
194 # return true if a file with this names exists
195 fun file_exists
: Bool do return to_cstring
.file_exists
197 # The status of a file. see POSIX stat(2).
198 fun file_stat
: FileStat do return to_cstring
.file_stat
200 # The status of a file or of a symlink. see POSIX lstat(2).
201 fun file_lstat
: FileStat do return to_cstring
.file_lstat
203 # Remove a file, return true if success
204 fun file_delete
: Bool do return to_cstring
.file_delete
206 # Copy content of file at `self` to `dest`
207 fun file_copy_to
(dest
: String)
209 var input
= new IFStream.open
(self)
210 var output
= new OFStream.open
(dest
)
212 while not input
.eof
do
213 var buffer
= input
.read
(1024)
221 # Remove the trailing extension `ext`.
223 # `ext` usually starts with a dot but could be anything.
225 # assert "file.txt".strip_extension(".txt") == "file"
226 # assert "file.txt".strip_extension("le.txt") == "fi"
227 # assert "file.txt".strip_extension("xt") == "file.t"
229 # if `ext` is not present, `self` is returned unmodified.
231 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
232 fun strip_extension
(ext
: String): String
234 if has_suffix
(ext
) then
235 return substring
(0, length
- ext
.length
)
240 # Extract the basename of a path and remove the extension
242 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
243 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
244 # assert "path/to".basename(".ext") == "to"
245 # assert "path/to/".basename(".ext") == "to"
246 # assert "path".basename("") == "path"
247 # assert "/path".basename("") == "path"
248 # assert "/".basename("") == "/"
249 # assert "".basename("") == ""
250 fun basename
(ext
: String): String
252 var l
= length
- 1 # Index of the last char
253 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
254 if l
== 0 then return "/"
255 var pos
= chars
.last_index_of_from
('/', l
)
258 n
= substring
(pos
+1, l-pos
)
260 return n
.strip_extension
(ext
)
263 # Extract the dirname of a path
265 # assert "/path/to/a_file.ext".dirname == "/path/to"
266 # assert "path/to/a_file.ext".dirname == "path/to"
267 # assert "path/to".dirname == "path"
268 # assert "path/to/".dirname == "path"
269 # assert "path".dirname == "."
270 # assert "/path".dirname == "/"
271 # assert "/".dirname == "/"
272 # assert "".dirname == "."
275 var l
= length
- 1 # Index of the last char
276 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
277 var pos
= chars
.last_index_of_from
('/', l
)
279 return substring
(0, pos
)
280 else if pos
== 0 then
287 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
288 fun realpath
: String do
289 var cs
= to_cstring
.file_realpath
290 var res
= cs
.to_s_with_copy
291 # cs.free_malloc # FIXME memory leak
295 # Simplify a file path by remove useless ".", removing "//", and resolving ".."
296 # ".." are not resolved if they start the path
297 # starting "/" is not removed
298 # trainling "/" is removed
300 # Note that the method only wonrk on the string:
301 # * no I/O access is performed
302 # * the validity of the path is not checked
304 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
305 # assert "../dir/file".simplify_path == "../dir/file"
306 # assert "dir/../../".simplify_path == ".."
307 # assert "dir/..".simplify_path == "."
308 # assert "//absolute//path/".simplify_path == "/absolute/path"
309 # assert "//absolute//../".simplify_path == "/"
310 fun simplify_path
: String
312 var a
= self.split_with
("/")
313 var a2
= new Array[String]
315 if x
== "." then continue
316 if x
== "" and not a2
.is_empty
then continue
317 if x
== ".." and not a2
.is_empty
and a2
.last
!= ".." then
323 if a2
.is_empty
then return "."
324 if a2
.length
== 1 and a2
.first
== "" then return "/"
328 # Correctly join two path using the directory separator.
330 # Using a standard "{self}/{path}" does not work in the following cases:
333 # * `path` ends with `'/'`.
334 # * `path` starts with `'/'`.
336 # This method ensures that the join is valid.
338 # assert "hello".join_path("world") == "hello/world"
339 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
340 # assert "".join_path("world") == "world"
341 # assert "hello".join_path("/world") == "/world"
342 # assert "hello/".join_path("world") == "hello/world"
343 # assert "hello/".join_path("/world") == "/world"
345 # Note: You may want to use `simplify_path` on the result.
347 # Note: This method works only with POSIX paths.
348 fun join_path
(path
: String): String
350 if path
.is_empty
then return self
351 if self.is_empty
then return path
352 if path
.chars
[0] == '/' then return path
353 if self.last
== '/' then return "{self}{path}"
354 return "{self}/{path}"
357 # Convert the path (`self`) to a program name.
359 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
360 # used as a program name. In order to do that, prepend `./` if needed.
362 # assert "foo".to_program_name == "./foo"
363 # assert "/foo".to_program_name == "/foo"
364 # assert "".to_program_name == "./" # At least, your shell will detect the error.
365 fun to_program_name
: String do
366 if self.has_prefix
("/") then
373 # Alias for `join_path`
375 # assert "hello" / "world" == "hello/world"
376 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
377 # assert "" / "world" == "world"
378 # assert "/hello" / "/world" == "/world"
380 # This operator is quite useful for chaining changes of path.
381 # The next one being relative to the previous one.
385 # var c = "baz/foobar"
386 # assert a/b/c == "/bar/baz/foobar"
387 fun /(path
: String): String do return join_path
(path
)
389 # Returns the relative path needed to go from `self` to `dest`.
391 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
392 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
394 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
396 # In some cases, the result is still independent of the current directory:
398 # assert "foo/bar".relpath("..") == "../../.."
400 # In other cases, parts of the current directory may be exhibited:
402 # var p = "../foo/bar".relpath("baz")
403 # var c = getcwd.basename("")
404 # assert p == "../../{c}/baz"
406 # For path resolution independent of the current directory (eg. for paths in URL),
407 # or to use an other starting directory than the current directory,
408 # just force absolute paths:
410 # var start = "/a/b/c/d"
411 # var p2 = (start/"../foo/bar").relpath(start/"baz")
412 # assert p2 == "../../d/baz"
415 # Neither `self` or `dest` has to be real paths or to exist in directories since
416 # the resolution is only done with string manipulations and without any access to
417 # the underlying file system.
419 # If `self` and `dest` are the same directory, the empty string is returned:
421 # assert "foo".relpath("foo") == ""
422 # assert "foo/../bar".relpath("bar") == ""
424 # The empty string and "." designate both the current directory:
426 # assert "".relpath("foo/bar") == "foo/bar"
427 # assert ".".relpath("foo/bar") == "foo/bar"
428 # assert "foo/bar".relpath("") == "../.."
429 # assert "/" + "/".relpath(".") == getcwd
430 fun relpath
(dest
: String): String
433 var from
= (cwd
/self).simplify_path
.split
("/")
434 if from
.last
.is_empty
then from
.pop
# case for the root directory
435 var to
= (cwd
/dest
).simplify_path
.split
("/")
436 if to
.last
.is_empty
then to
.pop
# case for the root directory
438 # Remove common prefixes
439 while not from
.is_empty
and not to
.is_empty
and from
.first
== to
.first
do
444 # Result is going up in `from` with ".." then going down following `to`
445 var from_len
= from
.length
446 if from_len
== 0 then return to
.join
("/")
447 var up
= "../"*(from_len-1
) + ".."
448 if to
.is_empty
then return up
449 var res
= up
+ "/" + to
.join
("/")
453 # Create a directory (and all intermediate directories if needed)
456 var dirs
= self.split_with
("/")
457 var path
= new FlatBuffer
458 if dirs
.is_empty
then return
459 if dirs
[0].is_empty
then
460 # it was a starting /
464 if d
.is_empty
then continue
467 path
.to_s
.to_cstring
.file_mkdir
471 # Delete a directory and all of its content, return `true` on success
473 # Does not go through symbolic links and may get stuck in a cycle if there
474 # is a cycle in the filesystem.
478 for file
in self.files
do
479 var file_path
= self.join_path
(file
)
480 var stat
= file_path
.file_lstat
482 ok
= file_path
.rmdir
and ok
484 ok
= file_path
.file_delete
and ok
489 # Delete the directory itself
490 if ok
then to_cstring
.rmdir
495 # Change the current working directory
498 # assert getcwd == "/etc"
500 # assert getcwd == "/"
503 fun chdir
do to_cstring
.file_chdir
505 # Return right-most extension (without the dot)
507 # Only the last extension is returned.
508 # There is no special case for combined extensions.
510 # assert "file.txt".file_extension == "txt"
511 # assert "file.tar.gz".file_extension == "gz"
513 # For file without extension, `null` is returned.
514 # Hoever, for trailing dot, `""` is returned.
516 # assert "file".file_extension == null
517 # assert "file.".file_extension == ""
519 # The starting dot of hidden files is never considered.
521 # assert ".file.txt".file_extension == "txt"
522 # assert ".file".file_extension == null
523 fun file_extension
: nullable String
525 var last_slash
= chars
.last_index_of
('.')
526 if last_slash
> 0 then
527 return substring
( last_slash
+1, length
)
533 # returns files contained within the directory represented by self
534 fun files
: Array[String] is extern import Array[String], Array[String].add
, NativeString.to_s
, String.to_cstring
`{
538 dir_path = String_to_cstring( recv );
539 if ((dir = opendir(dir_path)) == NULL)
546 Array_of_String results;
550 results = new_Array_of_String();
552 while ( ( de = readdir( dir ) ) != NULL )
553 if ( strcmp( de->d_name, ".." ) != 0 &&
554 strcmp( de->d_name, "." ) != 0 )
556 file_name = NativeString_to_s( strdup( de->d_name ) );
557 Array_of_String_add( results, file_name );
566 redef class NativeString
567 private fun file_exists
: Bool is extern "string_NativeString_NativeString_file_exists_0"
568 private fun file_stat
: FileStat is extern "string_NativeString_NativeString_file_stat_0"
569 private fun file_lstat
: FileStat `{
570 struct stat* stat_element;
572 stat_element = malloc(sizeof(struct stat));
573 res = lstat(recv, stat_element);
574 if (res == -1) return NULL;
577 private fun file_mkdir
: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
578 private fun rmdir
: Bool `{ return rmdir(recv); `}
579 private fun file_delete: Bool is extern "string_NativeString_NativeString_file_delete_0"
580 private fun file_chdir is extern "string_NativeString_NativeString_file_chdir_0"
581 private fun file_realpath: NativeString is extern "file_NativeString_realpath"
584 # This class is system dependent ... must reify the vfs
585 extern class FileStat `{ struct stat * `}
586 # Returns the permission bits of file
587 fun mode
: Int is extern "file_FileStat_FileStat_mode_0"
588 # Returns the last access time
589 fun atime
: Int is extern "file_FileStat_FileStat_atime_0"
590 # Returns the last status change time
591 fun ctime
: Int is extern "file_FileStat_FileStat_ctime_0"
592 # Returns the last modification time
593 fun mtime
: Int is extern "file_FileStat_FileStat_mtime_0"
595 fun size
: Int is extern "file_FileStat_FileStat_size_0"
597 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
598 fun is_reg
: Bool `{ return S_ISREG(recv->st_mode); `}
599 # Returns true if it is a directory
600 fun is_dir: Bool `{ return S_ISDIR(recv->st_mode); `}
601 # Returns true if it is a character device
602 fun is_chr
: Bool `{ return S_ISCHR(recv->st_mode); `}
603 # Returns true if it is a block device
604 fun is_blk: Bool `{ return S_ISBLK(recv->st_mode); `}
605 # Returns true if the type is fifo
606 fun is_fifo
: Bool `{ return S_ISFIFO(recv->st_mode); `}
607 # Returns true if the type is a link
608 fun is_lnk: Bool `{ return S_ISLNK(recv->st_mode); `}
609 # Returns true if the type is a socket
610 fun is_sock
: Bool `{ return S_ISSOCK(recv->st_mode); `}
613 # Instance of this class are standard FILE * pointers
614 private extern class NativeFile `{ FILE* `}
615 fun io_read
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
616 fun io_write
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
617 fun io_close
: Int is extern "file_NativeFile_NativeFile_io_close_0"
618 fun file_stat
: FileStat is extern "file_NativeFile_NativeFile_file_stat_0"
619 fun fileno
: Int `{ return fileno(recv); `}
621 new io_open_read(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
622 new io_open_write(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
623 new native_stdin is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
624 new native_stdout is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
625 new native_stderr is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
631 var stdin: PollableIStream = new Stdin is protected writable
634 var stdout: OStream = new Stdout is protected writable
636 # Standard output for errors
637 var stderr: OStream = new Stderr is protected writable
641 # Print `objects
` on the standard output (`stdout
`).
642 protected fun printn(objects: Object...)
644 sys.stdout.write(objects.to_s)
647 # Print an `object
` on the standard output (`stdout
`) and add a newline.
648 protected fun print(object: Object)
650 sys.stdout.write(object.to_s)
651 sys.stdout.write("\n")
654 # Read a character from the standard input (`stdin
`).
655 protected fun getc: Char
657 return sys.stdin.read_char.ascii
660 # Read a line from the standard input (`stdin
`).
661 protected fun gets: String
663 return sys.stdin.read_line
666 # Return the working (current) directory
667 protected fun getcwd: String do return file_getcwd.to_s
668 private fun file_getcwd: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"