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.
59 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
67 var i
= _file
.io_close
74 var nb
= _file
.io_read
(_buffer
.items
, _buffer
.capacity
)
84 redef var end_reached
: Bool = false
86 # Open the file at `path` for reading.
87 init open
(path
: String)
91 _file
= new NativeFile.io_open_read
(path
.to_cstring
)
92 assert not _file
.address_is_null
else
93 print
"Error: Opening file at '{path}' failed with '{sys.errno.strerror}'"
98 private init without_file
do end
109 if s
isa FlatText then
110 write_native
(s
.to_cstring
, s
.length
)
112 for i
in s
.substrings
do write_native
(i
.to_cstring
, i
.length
)
118 var i
= _file
.io_close
122 redef var is_writable
= false
124 # Write `len` bytes from `native`.
125 private fun write_native
(native
: NativeString, len
: Int)
128 var err
= _file
.io_write
(native
, len
)
131 printn
("Problem in writing : ", err
, " ", len
, "\n")
135 # Open the file at `path` for writing.
136 init open
(path
: String)
138 _file
= new NativeFile.io_open_write
(path
.to_cstring
)
139 assert not _file
.address_is_null
else
140 print
"Error: Opening file at '{path}' failed with '{sys.errno.strerror}'"
147 private init without_file
do end
150 ###############################################################################
156 _file
= new NativeFile.native_stdin
161 redef fun poll_in
: Bool is extern "file_stdin_poll_in"
167 _file
= new NativeFile.native_stdout
176 _file
= new NativeFile.native_stderr
182 ###############################################################################
184 redef class Streamable
185 # Like `write_to` but take care of creating the file
186 fun write_to_file
(filepath
: String)
188 var stream
= new OFStream.open
(filepath
)
195 # return true if a file with this names exists
196 fun file_exists
: Bool do return to_cstring
.file_exists
198 # The status of a file. see POSIX stat(2).
199 fun file_stat
: FileStat do return to_cstring
.file_stat
201 # The status of a file or of a symlink. see POSIX lstat(2).
202 fun file_lstat
: FileStat do return to_cstring
.file_lstat
204 # Remove a file, return true if success
205 fun file_delete
: Bool do return to_cstring
.file_delete
207 # Copy content of file at `self` to `dest`
208 fun file_copy_to
(dest
: String)
210 var input
= new IFStream.open
(self)
211 var output
= new OFStream.open
(dest
)
213 while not input
.eof
do
214 var buffer
= input
.read
(1024)
222 # Remove the trailing extension `ext`.
224 # `ext` usually starts with a dot but could be anything.
226 # assert "file.txt".strip_extension(".txt") == "file"
227 # assert "file.txt".strip_extension("le.txt") == "fi"
228 # assert "file.txt".strip_extension("xt") == "file.t"
230 # if `ext` is not present, `self` is returned unmodified.
232 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
233 fun strip_extension
(ext
: String): String
235 if has_suffix
(ext
) then
236 return substring
(0, length
- ext
.length
)
241 # Extract the basename of a path and remove the extension
243 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
244 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
245 # assert "path/to".basename(".ext") == "to"
246 # assert "path/to/".basename(".ext") == "to"
247 # assert "path".basename("") == "path"
248 # assert "/path".basename("") == "path"
249 # assert "/".basename("") == "/"
250 # assert "".basename("") == ""
251 fun basename
(ext
: String): String
253 var l
= length
- 1 # Index of the last char
254 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
255 if l
== 0 then return "/"
256 var pos
= chars
.last_index_of_from
('/', l
)
259 n
= substring
(pos
+1, l-pos
)
261 return n
.strip_extension
(ext
)
264 # Extract the dirname of a path
266 # assert "/path/to/a_file.ext".dirname == "/path/to"
267 # assert "path/to/a_file.ext".dirname == "path/to"
268 # assert "path/to".dirname == "path"
269 # assert "path/to/".dirname == "path"
270 # assert "path".dirname == "."
271 # assert "/path".dirname == "/"
272 # assert "/".dirname == "/"
273 # assert "".dirname == "."
276 var l
= length
- 1 # Index of the last char
277 while l
> 0 and self.chars
[l
] == '/' do l
-= 1 # remove all trailing `/`
278 var pos
= chars
.last_index_of_from
('/', l
)
280 return substring
(0, pos
)
281 else if pos
== 0 then
288 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
289 fun realpath
: String do
290 var cs
= to_cstring
.file_realpath
291 var res
= cs
.to_s_with_copy
292 # cs.free_malloc # FIXME memory leak
296 # Simplify a file path by remove useless ".", removing "//", and resolving ".."
297 # ".." are not resolved if they start the path
298 # starting "/" is not removed
299 # trainling "/" is removed
301 # Note that the method only wonrk on the string:
302 # * no I/O access is performed
303 # * the validity of the path is not checked
305 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
306 # assert "../dir/file".simplify_path == "../dir/file"
307 # assert "dir/../../".simplify_path == ".."
308 # assert "dir/..".simplify_path == "."
309 # assert "//absolute//path/".simplify_path == "/absolute/path"
310 # assert "//absolute//../".simplify_path == "/"
311 fun simplify_path
: String
313 var a
= self.split_with
("/")
314 var a2
= new Array[String]
316 if x
== "." then continue
317 if x
== "" and not a2
.is_empty
then continue
318 if x
== ".." and not a2
.is_empty
and a2
.last
!= ".." then
324 if a2
.is_empty
then return "."
325 if a2
.length
== 1 and a2
.first
== "" then return "/"
329 # Correctly join two path using the directory separator.
331 # Using a standard "{self}/{path}" does not work when `self` is the empty string.
332 # This method ensure that the join is valid.
334 # assert "hello".join_path("world") == "hello/world"
335 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
336 # assert "".join_path("world") == "world"
337 # assert "/hello".join_path("/world") == "/world"
339 # Note: you may want to use `simplify_path` on the result
341 # Note: I you want to join a great number of path, you can write
343 # [p1, p2, p3, p4].join("/")
344 fun join_path
(path
: String): String
346 if path
.is_empty
then return self
347 if self.is_empty
then return path
348 if path
.chars
[0] == '/' then return path
349 return "{self}/{path}"
352 # Convert the path (`self`) to a program name.
354 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
355 # used as a program name. In order to do that, prepend `./` if needed.
357 # assert "foo".to_program_name == "./foo"
358 # assert "/foo".to_program_name == "/foo"
359 # assert "".to_program_name == "./" # At least, your shell will detect the error.
360 fun to_program_name
: String do
361 if self.has_prefix
("/") then
368 # Alias for `join_path`
370 # assert "hello" / "world" == "hello/world"
371 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
372 # assert "" / "world" == "world"
373 # assert "/hello" / "/world" == "/world"
375 # This operator is quite useful for chaining changes of path.
376 # The next one being relative to the previous one.
380 # var c = "baz/foobar"
381 # assert a/b/c == "/bar/baz/foobar"
382 fun /(path
: String): String do return join_path
(path
)
384 # Returns the relative path needed to go from `self` to `dest`.
386 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
387 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
389 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
391 # In some cases, the result is still independent of the current directory:
393 # assert "foo/bar".relpath("..") == "../../.."
395 # In other cases, parts of the current directory may be exhibited:
397 # var p = "../foo/bar".relpath("baz")
398 # var c = getcwd.basename("")
399 # assert p == "../../{c}/baz"
401 # For path resolution independent of the current directory (eg. for paths in URL),
402 # or to use an other starting directory than the current directory,
403 # just force absolute paths:
405 # var start = "/a/b/c/d"
406 # var p2 = (start/"../foo/bar").relpath(start/"baz")
407 # assert p2 == "../../d/baz"
410 # Neither `self` or `dest` has to be real paths or to exist in directories since
411 # the resolution is only done with string manipulations and without any access to
412 # the underlying file system.
414 # If `self` and `dest` are the same directory, the empty string is returned:
416 # assert "foo".relpath("foo") == ""
417 # assert "foo/../bar".relpath("bar") == ""
419 # The empty string and "." designate both the current directory:
421 # assert "".relpath("foo/bar") == "foo/bar"
422 # assert ".".relpath("foo/bar") == "foo/bar"
423 # assert "foo/bar".relpath("") == "../.."
424 # assert "/" + "/".relpath(".") == getcwd
425 fun relpath
(dest
: String): String
428 var from
= (cwd
/self).simplify_path
.split
("/")
429 if from
.last
.is_empty
then from
.pop
# case for the root directory
430 var to
= (cwd
/dest
).simplify_path
.split
("/")
431 if to
.last
.is_empty
then to
.pop
# case for the root directory
433 # Remove common prefixes
434 while not from
.is_empty
and not to
.is_empty
and from
.first
== to
.first
do
439 # Result is going up in `from` with ".." then going down following `to`
440 var from_len
= from
.length
441 if from_len
== 0 then return to
.join
("/")
442 var up
= "../"*(from_len-1
) + ".."
443 if to
.is_empty
then return up
444 var res
= up
+ "/" + to
.join
("/")
448 # Create a directory (and all intermediate directories if needed)
451 var dirs
= self.split_with
("/")
452 var path
= new FlatBuffer
453 if dirs
.is_empty
then return
454 if dirs
[0].is_empty
then
455 # it was a starting /
459 if d
.is_empty
then continue
462 path
.to_s
.to_cstring
.file_mkdir
466 # Delete a directory and all of its content, return `true` on success
468 # Does not go through symbolic links and may get stuck in a cycle if there
469 # is a cycle in the filesystem.
473 for file
in self.files
do
474 var file_path
= self.join_path
(file
)
475 var stat
= file_path
.file_lstat
477 ok
= file_path
.rmdir
and ok
479 ok
= file_path
.file_delete
and ok
484 # Delete the directory itself
485 if ok
then to_cstring
.rmdir
490 # Change the current working directory
493 # assert getcwd == "/etc"
495 # assert getcwd == "/"
498 fun chdir
do to_cstring
.file_chdir
500 # Return right-most extension (without the dot)
502 # Only the last extension is returned.
503 # There is no special case for combined extensions.
505 # assert "file.txt".file_extension == "txt"
506 # assert "file.tar.gz".file_extension == "gz"
508 # For file without extension, `null` is returned.
509 # Hoever, for trailing dot, `""` is returned.
511 # assert "file".file_extension == null
512 # assert "file.".file_extension == ""
514 # The starting dot of hidden files is never considered.
516 # assert ".file.txt".file_extension == "txt"
517 # assert ".file".file_extension == null
518 fun file_extension
: nullable String
520 var last_slash
= chars
.last_index_of
('.')
521 if last_slash
> 0 then
522 return substring
( last_slash
+1, length
)
528 # returns files contained within the directory represented by self
529 fun files
: Set[ String ] is extern import HashSet[String], HashSet[String].add
, NativeString.to_s
, String.to_cstring
, HashSet[String].as(Set[String]) `{
533 dir_path = String_to_cstring( recv );
534 if ((dir = opendir(dir_path)) == NULL)
541 HashSet_of_String results;
545 results = new_HashSet_of_String();
547 while ( ( de = readdir( dir ) ) != NULL )
548 if ( strcmp( de->d_name, ".." ) != 0 &&
549 strcmp( de->d_name, "." ) != 0 )
551 file_name = NativeString_to_s( strdup( de->d_name ) );
552 HashSet_of_String_add( results, file_name );
556 return HashSet_of_String_as_Set_of_String( results );
561 redef class NativeString
562 private fun file_exists
: Bool is extern "string_NativeString_NativeString_file_exists_0"
563 private fun file_stat
: FileStat is extern "string_NativeString_NativeString_file_stat_0"
564 private fun file_lstat
: FileStat `{
565 struct stat* stat_element;
567 stat_element = malloc(sizeof(struct stat));
568 res = lstat(recv, stat_element);
569 if (res == -1) return NULL;
572 private fun file_mkdir
: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
573 private fun rmdir
: Bool `{ return rmdir(recv); `}
574 private fun file_delete: Bool is extern "string_NativeString_NativeString_file_delete_0"
575 private fun file_chdir is extern "string_NativeString_NativeString_file_chdir_0"
576 private fun file_realpath: NativeString is extern "file_NativeString_realpath"
579 # This class is system dependent ... must reify the vfs
580 extern class FileStat `{ struct stat * `}
581 # Returns the permission bits of file
582 fun mode
: Int is extern "file_FileStat_FileStat_mode_0"
583 # Returns the last access time
584 fun atime
: Int is extern "file_FileStat_FileStat_atime_0"
585 # Returns the last status change time
586 fun ctime
: Int is extern "file_FileStat_FileStat_ctime_0"
587 # Returns the last modification time
588 fun mtime
: Int is extern "file_FileStat_FileStat_mtime_0"
590 fun size
: Int is extern "file_FileStat_FileStat_size_0"
592 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
593 fun is_reg
: Bool `{ return S_ISREG(recv->st_mode); `}
594 # Returns true if it is a directory
595 fun is_dir: Bool `{ return S_ISDIR(recv->st_mode); `}
596 # Returns true if it is a character device
597 fun is_chr
: Bool `{ return S_ISCHR(recv->st_mode); `}
598 # Returns true if it is a block device
599 fun is_blk: Bool `{ return S_ISBLK(recv->st_mode); `}
600 # Returns true if the type is fifo
601 fun is_fifo
: Bool `{ return S_ISFIFO(recv->st_mode); `}
602 # Returns true if the type is a link
603 fun is_lnk: Bool `{ return S_ISLNK(recv->st_mode); `}
604 # Returns true if the type is a socket
605 fun is_sock
: Bool `{ return S_ISSOCK(recv->st_mode); `}
608 # Instance of this class are standard FILE * pointers
609 private extern class NativeFile `{ FILE* `}
610 fun io_read
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
611 fun io_write
(buf
: NativeString, len
: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
612 fun io_close
: Int is extern "file_NativeFile_NativeFile_io_close_0"
613 fun file_stat
: FileStat is extern "file_NativeFile_NativeFile_file_stat_0"
614 fun fileno
: Int `{ return fileno(recv); `}
616 new io_open_read(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
617 new io_open_write(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
618 new native_stdin is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
619 new native_stdout is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
620 new native_stderr is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
626 var stdin: PollableIStream = new Stdin is protected writable
629 var stdout: OStream = new Stdout is protected writable
631 # Standard output for errors
632 var stderr: OStream = new Stderr is protected writable
636 # Print `objects
` on the standard output (`stdout
`).
637 protected fun printn(objects: Object...)
639 sys.stdout.write(objects.to_s)
642 # Print an `object
` on the standard output (`stdout
`) and add a newline.
643 protected fun print(object: Object)
645 sys.stdout.write(object.to_s)
646 sys.stdout.write("\n")
649 # Read a character from the standard input (`stdin
`).
650 protected fun getc: Char
652 return sys.stdin.read_char.ascii
655 # Read a line from the standard input (`stdin
`).
656 protected fun gets: String
658 return sys.stdin.read_line
661 # Return the working (current) directory
662 protected fun getcwd: String do return file_getcwd.to_s
663 private fun file_getcwd: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"