lib/file: some methods return a nullable Error on error
[nit.git] / lib / standard / file.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
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>
6 #
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
13 # another product.
14
15 # File manipulations (create, read, write, etc.)
16 module file
17
18 intrude import stream
19 intrude import ropes
20 import string_search
21 import time
22 import gc
23
24 in "C Header" `{
25 #include <dirent.h>
26 #include <string.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30 #include <stdio.h>
31 #include <poll.h>
32 #include <errno.h>
33 `}
34
35 # `Stream` used to interact with a File or FileDescriptor
36 abstract class FileStream
37 super Stream
38 # The path of the file.
39 var path: nullable String = null
40
41 # The FILE *.
42 private var file: nullable NativeFile = null
43
44 # The status of a file. see POSIX stat(2).
45 #
46 # var f = new FileReader.open("/etc/issue")
47 # assert f.file_stat.is_file
48 #
49 # Return null in case of error
50 fun file_stat: nullable FileStat
51 do
52 var stat = _file.file_stat
53 if stat.address_is_null then return null
54 return new FileStat(stat)
55 end
56
57 # File descriptor of this file
58 fun fd: Int do return _file.fileno
59
60 redef fun close
61 do
62 if _file == null then return
63 if _file.address_is_null then
64 if last_error != null then return
65 last_error = new IOError("Cannot close unopened file")
66 return
67 end
68 var i = _file.io_close
69 if i != 0 then
70 last_error = new IOError("Close failed due to error {sys.errno.strerror}")
71 end
72 _file = null
73 end
74
75 # Sets the buffering mode for the current FileStream
76 #
77 # If the buf_size is <= 0, its value will be 512 by default
78 #
79 # The mode is any of the buffer_mode enumeration in `Sys`:
80 # - buffer_mode_full
81 # - buffer_mode_line
82 # - buffer_mode_none
83 fun set_buffering_mode(buf_size, mode: Int) do
84 if buf_size <= 0 then buf_size = 512
85 if _file.set_buffering_type(buf_size, mode) != 0 then
86 last_error = new IOError("Error while changing buffering type for FileStream, returned error {sys.errno.strerror}")
87 end
88 end
89 end
90
91 # `Stream` that can read from a File
92 class FileReader
93 super FileStream
94 super BufferedReader
95 super PollableReader
96 # Misc
97
98 # Open the same file again.
99 # The original path is reused, therefore the reopened file can be a different file.
100 #
101 # var f = new FileReader.open("/etc/issue")
102 # var l = f.read_line
103 # f.reopen
104 # assert l == f.read_line
105 fun reopen
106 do
107 if not eof and not _file.address_is_null then close
108 last_error = null
109 _file = new NativeFile.io_open_read(path.to_cstring)
110 if _file.address_is_null then
111 last_error = new IOError("Error: Opening file at '{path.as(not null)}' failed with '{sys.errno.strerror}'")
112 end_reached = true
113 return
114 end
115 end_reached = false
116 _buffer_pos = 0
117 _buffer.clear
118 end
119
120 redef fun close
121 do
122 super
123 _buffer.clear
124 end_reached = true
125 end
126
127 redef fun fill_buffer
128 do
129 var nb = _file.io_read(_buffer.items, _buffer.capacity)
130 if nb <= 0 then
131 end_reached = true
132 nb = 0
133 end
134 _buffer.length = nb
135 _buffer_pos = 0
136 end
137
138 # End of file?
139 redef var end_reached: Bool = false
140
141 # Open the file at `path` for reading.
142 #
143 # var f = new FileReader.open("/etc/issue")
144 # assert not f.end_reached
145 # f.close
146 #
147 # In case of error, `last_error` is set
148 #
149 # f = new FileReader.open("/fail/does not/exist")
150 # assert f.end_reached
151 # assert f.last_error != null
152 init open(path: String)
153 do
154 self.path = path
155 prepare_buffer(10)
156 _file = new NativeFile.io_open_read(path.to_cstring)
157 if _file.address_is_null then
158 last_error = new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
159 end_reached = true
160 end
161 end
162
163 # Creates a new File stream from a file descriptor
164 #
165 # This is a low-level method.
166 init from_fd(fd: Int) do
167 self.path = ""
168 prepare_buffer(1)
169 _file = fd.fd_to_stream(read_only)
170 if _file.address_is_null then
171 last_error = new IOError("Error: Converting fd {fd} to stream failed with '{sys.errno.strerror}'")
172 end_reached = true
173 end
174 end
175 end
176
177 # `Stream` that can write to a File
178 class FileWriter
179 super FileStream
180 super Writer
181
182 redef fun write(s)
183 do
184 if last_error != null then return
185 if not _is_writable then
186 last_error = new IOError("Cannot write to non-writable stream")
187 return
188 end
189 if s isa FlatText then
190 write_native(s.to_cstring, s.length)
191 else
192 for i in s.substrings do write_native(i.to_cstring, i.length)
193 end
194 end
195
196 redef fun close
197 do
198 super
199 _is_writable = false
200 end
201 redef var is_writable = false
202
203 # Write `len` bytes from `native`.
204 private fun write_native(native: NativeString, len: Int)
205 do
206 if last_error != null then return
207 if not _is_writable then
208 last_error = new IOError("Cannot write to non-writable stream")
209 return
210 end
211 if _file.address_is_null then
212 last_error = new IOError("Writing on a null stream")
213 _is_writable = false
214 return
215 end
216 var err = _file.io_write(native, len)
217 if err != len then
218 # Big problem
219 last_error = new IOError("Problem in writing : {err} {len} \n")
220 end
221 end
222
223 # Open the file at `path` for writing.
224 init open(path: String)
225 do
226 _file = new NativeFile.io_open_write(path.to_cstring)
227 self.path = path
228 _is_writable = true
229 if _file.address_is_null then
230 last_error = new IOError("Error: Opening file at '{path}' failed with '{sys.errno.strerror}'")
231 is_writable = false
232 end
233 end
234
235 # Creates a new File stream from a file descriptor
236 init from_fd(fd: Int) do
237 self.path = ""
238 _file = fd.fd_to_stream(wipe_write)
239 _is_writable = true
240 if _file.address_is_null then
241 last_error = new IOError("Error: Opening stream from file descriptor {fd} failed with '{sys.errno.strerror}'")
242 _is_writable = false
243 end
244 end
245 end
246
247 redef class Int
248 # Creates a file stream from a file descriptor `fd` using the file access `mode`.
249 #
250 # NOTE: The `mode` specified must be compatible with the one used in the file descriptor.
251 private fun fd_to_stream(mode: NativeString): NativeFile is extern "file_int_fdtostream"
252 end
253
254 # Constant for read-only file streams
255 private fun read_only: NativeString do return "r".to_cstring
256
257 # Constant for write-only file streams
258 #
259 # If a stream is opened on a file with this method,
260 # it will wipe the previous file if any.
261 # Else, it will create the file.
262 private fun wipe_write: NativeString do return "w".to_cstring
263
264 ###############################################################################
265
266 # Standard input stream.
267 #
268 # The class of the default value of `sys.stdin`.
269 class Stdin
270 super FileReader
271
272 init do
273 _file = new NativeFile.native_stdin
274 path = "/dev/stdin"
275 prepare_buffer(1)
276 end
277
278 redef fun poll_in: Bool is extern "file_stdin_poll_in"
279 end
280
281 # Standard output stream.
282 #
283 # The class of the default value of `sys.stdout`.
284 class Stdout
285 super FileWriter
286 init do
287 _file = new NativeFile.native_stdout
288 path = "/dev/stdout"
289 _is_writable = true
290 set_buffering_mode(256, sys.buffer_mode_line)
291 end
292 end
293
294 # Standard error stream.
295 #
296 # The class of the default value of `sys.stderr`.
297 class Stderr
298 super FileWriter
299 init do
300 _file = new NativeFile.native_stderr
301 path = "/dev/stderr"
302 _is_writable = true
303 end
304 end
305
306 ###############################################################################
307
308 redef class Writable
309 # Like `write_to` but take care of creating the file
310 fun write_to_file(filepath: String)
311 do
312 var stream = new FileWriter.open(filepath)
313 write_to(stream)
314 stream.close
315 end
316 end
317
318 # Utility class to access file system services
319 #
320 # Usually created with `Text::to_path`.
321 class Path
322
323 private var path: String
324
325 # Path to this file
326 redef fun to_s do return path
327
328 # Name of the file name at `to_s`
329 #
330 # ~~~
331 # var path = "/tmp/somefile".to_path
332 # assert path.filename == "somefile"
333 # ~~~
334 var filename: String = path.basename("") is lazy
335
336 # Does the file at `path` exists?
337 fun exists: Bool do return stat != null
338
339 # Information on the file at `self` following symbolic links
340 #
341 # Returns `null` if there is no file at `self`.
342 #
343 # assert "/etc/".to_path.stat.is_dir
344 # assert "/etc/issue".to_path.stat.is_file
345 # assert "/fail/does not/exist".to_path.stat == null
346 #
347 # ~~~
348 # var p = "/tmp/".to_path
349 # var stat = p.stat
350 # if stat != null then # Does `p` exist?
351 # print "It's size is {stat.size}"
352 # if stat.is_dir then print "It's a directory"
353 # end
354 # ~~~
355 fun stat: nullable FileStat
356 do
357 var stat = path.to_cstring.file_stat
358 if stat.address_is_null then return null
359 return new FileStat(stat)
360 end
361
362 # Information on the file or link at `self`
363 #
364 # Do not follow symbolic links.
365 fun link_stat: nullable FileStat
366 do
367 var stat = path.to_cstring.file_lstat
368 if stat.address_is_null then return null
369 return new FileStat(stat)
370 end
371
372 # Delete a file from the file system, return `true` on success
373 fun delete: Bool do return path.to_cstring.file_delete
374
375 # Copy content of file at `path` to `dest`
376 #
377 # Require: `exists`
378 fun copy(dest: Path)
379 do
380 var input = open_ro
381 var output = dest.open_wo
382
383 while not input.eof do
384 var buffer = input.read(1024)
385 output.write buffer
386 end
387
388 input.close
389 output.close
390 end
391
392 # Open this file for reading
393 #
394 # Require: `exists and not link_stat.is_dir`
395 fun open_ro: FileReader
396 do
397 # TODO manage streams error when they are merged
398 return new FileReader.open(path)
399 end
400
401 # Open this file for writing
402 #
403 # Require: `not exists or not stat.is_dir`
404 fun open_wo: FileWriter
405 do
406 # TODO manage streams error when they are merged
407 return new FileWriter.open(path)
408 end
409
410 # Read all the content of the file
411 #
412 # ~~~
413 # var content = "/etc/issue".to_path.read_all
414 # print content
415 # ~~~
416 #
417 # See `Reader::read_all` for details.
418 fun read_all: String
419 do
420 var s = open_ro
421 var res = s.read_all
422 s.close
423 return res
424 end
425
426 # Read all the lines of the file
427 #
428 # ~~~
429 # var lines = "/etc/passwd".to_path.read_lines
430 #
431 # print "{lines.length} users"
432 #
433 # for l in lines do
434 # var fields = l.split(":")
435 # print "name={fields[0]} uid={fields[2]}"
436 # end
437 # ~~~
438 #
439 # See `Reader::read_lines` for details.
440 fun read_lines: Array[String]
441 do
442 var s = open_ro
443 var res = s.read_lines
444 s.close
445 return res
446 end
447
448 # Return an iterator on each line of the file
449 #
450 # ~~~
451 # for l in "/etc/passwd".to_path.each_line do
452 # var fields = l.split(":")
453 # print "name={fields[0]} uid={fields[2]}"
454 # end
455 # ~~~
456 #
457 # Note: the stream is automatically closed at the end of the file (see `LineIterator::close_on_finish`)
458 #
459 # See `Reader::each_line` for details.
460 fun each_line: LineIterator
461 do
462 var s = open_ro
463 var res = s.each_line
464 res.close_on_finish = true
465 return res
466 end
467
468
469 # Lists the name of the files contained within the directory at `path`
470 #
471 # Require: `exists and is_dir`
472 fun files: Array[Path]
473 do
474 var files = new Array[Path]
475 for filename in path.files do
476 files.add new Path(path / filename)
477 end
478 return files
479 end
480
481 # Delete a directory and all of its content, return `true` on success
482 #
483 # Does not go through symbolic links and may get stuck in a cycle if there
484 # is a cycle in the file system.
485 fun rmdir: Bool
486 do
487 var ok = true
488 for file in self.files do
489 var stat = file.link_stat
490 if stat.is_dir then
491 ok = file.rmdir and ok
492 else
493 ok = file.delete and ok
494 end
495 end
496
497 # Delete the directory itself
498 if ok then ok = path.to_cstring.rmdir and ok
499
500 return ok
501 end
502
503 redef fun ==(other) do return other isa Path and path.simplify_path == other.path.simplify_path
504 redef fun hash do return path.simplify_path.hash
505 end
506
507 # Information on a file
508 #
509 # Created by `Path::stat` and `Path::link_stat`.
510 #
511 # The information within this class is gathered when the instance is initialized
512 # it will not be updated if the targeted file is modified.
513 class FileStat
514 super Finalizable
515
516 # TODO private init
517
518 # The low-level status of a file
519 #
520 # See: POSIX stat(2)
521 private var stat: NativeFileStat
522
523 private var finalized = false
524
525 redef fun finalize
526 do
527 if not finalized then
528 stat.free
529 finalized = true
530 end
531 end
532
533 # Returns the last access time in seconds since Epoch
534 fun last_access_time: Int
535 do
536 assert not finalized
537 return stat.atime
538 end
539
540 # Returns the last access time
541 #
542 # alias for `last_access_time`
543 fun atime: Int do return last_access_time
544
545 # Returns the last modification time in seconds since Epoch
546 fun last_modification_time: Int
547 do
548 assert not finalized
549 return stat.mtime
550 end
551
552 # Returns the last modification time
553 #
554 # alias for `last_modification_time`
555 fun mtime: Int do return last_modification_time
556
557
558 # Size of the file at `path`
559 fun size: Int
560 do
561 assert not finalized
562 return stat.size
563 end
564
565 # Is self a regular file and not a device file, pipe, socket, etc.?
566 fun is_file: Bool
567 do
568 assert not finalized
569 return stat.is_reg
570 end
571
572 # Alias for `is_file`
573 fun is_reg: Bool do return is_file
574
575 # Is this a directory?
576 fun is_dir: Bool
577 do
578 assert not finalized
579 return stat.is_dir
580 end
581
582 # Is this a symbolic link?
583 fun is_link: Bool
584 do
585 assert not finalized
586 return stat.is_lnk
587 end
588
589 # FIXME Make the following POSIX only? or implement in some other way on Windows
590
591 # Returns the last status change time in seconds since Epoch
592 fun last_status_change_time: Int
593 do
594 assert not finalized
595 return stat.ctime
596 end
597
598 # Returns the last status change time
599 #
600 # alias for `last_status_change_time`
601 fun ctime: Int do return last_status_change_time
602
603 # Returns the permission bits of file
604 fun mode: Int
605 do
606 assert not finalized
607 return stat.mode
608 end
609
610 # Is this a character device?
611 fun is_chr: Bool
612 do
613 assert not finalized
614 return stat.is_chr
615 end
616
617 # Is this a block device?
618 fun is_blk: Bool
619 do
620 assert not finalized
621 return stat.is_blk
622 end
623
624 # Is this a FIFO pipe?
625 fun is_fifo: Bool
626 do
627 assert not finalized
628 return stat.is_fifo
629 end
630
631 # Is this a UNIX socket
632 fun is_sock: Bool
633 do
634 assert not finalized
635 return stat.is_sock
636 end
637 end
638
639 redef class Text
640 # Access file system related services on the path at `self`
641 fun to_path: Path do return new Path(to_s)
642 end
643
644 redef class String
645 # return true if a file with this names exists
646 fun file_exists: Bool do return to_cstring.file_exists
647
648 # The status of a file. see POSIX stat(2).
649 fun file_stat: nullable FileStat
650 do
651 var stat = to_cstring.file_stat
652 if stat.address_is_null then return null
653 return new FileStat(stat)
654 end
655
656 # The status of a file or of a symlink. see POSIX lstat(2).
657 fun file_lstat: nullable FileStat
658 do
659 var stat = to_cstring.file_lstat
660 if stat.address_is_null then return null
661 return new FileStat(stat)
662 end
663
664 # Remove a file, return true if success
665 fun file_delete: Bool do return to_cstring.file_delete
666
667 # Copy content of file at `self` to `dest`
668 fun file_copy_to(dest: String) do to_path.copy(dest.to_path)
669
670 # Remove the trailing extension `ext`.
671 #
672 # `ext` usually starts with a dot but could be anything.
673 #
674 # assert "file.txt".strip_extension(".txt") == "file"
675 # assert "file.txt".strip_extension("le.txt") == "fi"
676 # assert "file.txt".strip_extension("xt") == "file.t"
677 #
678 # if `ext` is not present, `self` is returned unmodified.
679 #
680 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
681 fun strip_extension(ext: String): String
682 do
683 if has_suffix(ext) then
684 return substring(0, length - ext.length)
685 end
686 return self
687 end
688
689 # Extract the basename of a path and remove the extension
690 #
691 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
692 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
693 # assert "path/to".basename(".ext") == "to"
694 # assert "path/to/".basename(".ext") == "to"
695 # assert "path".basename("") == "path"
696 # assert "/path".basename("") == "path"
697 # assert "/".basename("") == "/"
698 # assert "".basename("") == ""
699 fun basename(ext: String): String
700 do
701 var l = length - 1 # Index of the last char
702 while l > 0 and self.chars[l] == '/' do l -= 1 # remove all trailing `/`
703 if l == 0 then return "/"
704 var pos = chars.last_index_of_from('/', l)
705 var n = self
706 if pos >= 0 then
707 n = substring(pos+1, l-pos)
708 end
709 return n.strip_extension(ext)
710 end
711
712 # Extract the dirname of a path
713 #
714 # assert "/path/to/a_file.ext".dirname == "/path/to"
715 # assert "path/to/a_file.ext".dirname == "path/to"
716 # assert "path/to".dirname == "path"
717 # assert "path/to/".dirname == "path"
718 # assert "path".dirname == "."
719 # assert "/path".dirname == "/"
720 # assert "/".dirname == "/"
721 # assert "".dirname == "."
722 fun dirname: String
723 do
724 var l = length - 1 # Index of the last char
725 while l > 0 and self.chars[l] == '/' do l -= 1 # remove all trailing `/`
726 var pos = chars.last_index_of_from('/', l)
727 if pos > 0 then
728 return substring(0, pos)
729 else if pos == 0 then
730 return "/"
731 else
732 return "."
733 end
734 end
735
736 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
737 fun realpath: String do
738 var cs = to_cstring.file_realpath
739 var res = cs.to_s_with_copy
740 # cs.free_malloc # FIXME memory leak
741 return res
742 end
743
744 # Simplify a file path by remove useless ".", removing "//", and resolving ".."
745 #
746 # * ".." are not resolved if they start the path
747 # * starting "/" is not removed
748 # * trailing "/" is removed
749 #
750 # Note that the method only work on the string:
751 #
752 # * no I/O access is performed
753 # * the validity of the path is not checked
754 #
755 # ~~~
756 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
757 # assert "../dir/file".simplify_path == "../dir/file"
758 # assert "dir/../../".simplify_path == ".."
759 # assert "dir/..".simplify_path == "."
760 # assert "//absolute//path/".simplify_path == "/absolute/path"
761 # assert "//absolute//../".simplify_path == "/"
762 # ~~~
763 fun simplify_path: String
764 do
765 var a = self.split_with("/")
766 var a2 = new Array[String]
767 for x in a do
768 if x == "." then continue
769 if x == "" and not a2.is_empty then continue
770 if x == ".." and not a2.is_empty and a2.last != ".." then
771 a2.pop
772 continue
773 end
774 a2.push(x)
775 end
776 if a2.is_empty then return "."
777 if a2.length == 1 and a2.first == "" then return "/"
778 return a2.join("/")
779 end
780
781 # Correctly join two path using the directory separator.
782 #
783 # Using a standard "{self}/{path}" does not work in the following cases:
784 #
785 # * `self` is empty.
786 # * `path` starts with `'/'`.
787 #
788 # This method ensures that the join is valid.
789 #
790 # assert "hello".join_path("world") == "hello/world"
791 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
792 # assert "".join_path("world") == "world"
793 # assert "hello".join_path("/world") == "/world"
794 # assert "hello/".join_path("world") == "hello/world"
795 # assert "hello/".join_path("/world") == "/world"
796 #
797 # Note: You may want to use `simplify_path` on the result.
798 #
799 # Note: This method works only with POSIX paths.
800 fun join_path(path: String): String
801 do
802 if path.is_empty then return self
803 if self.is_empty then return path
804 if path.chars[0] == '/' then return path
805 if self.last == '/' then return "{self}{path}"
806 return "{self}/{path}"
807 end
808
809 # Convert the path (`self`) to a program name.
810 #
811 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
812 # used as a program name. In order to do that, prepend `./` if needed.
813 #
814 # assert "foo".to_program_name == "./foo"
815 # assert "/foo".to_program_name == "/foo"
816 # assert "".to_program_name == "./" # At least, your shell will detect the error.
817 fun to_program_name: String do
818 if self.has_prefix("/") then
819 return self
820 else
821 return "./{self}"
822 end
823 end
824
825 # Alias for `join_path`
826 #
827 # assert "hello" / "world" == "hello/world"
828 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
829 # assert "" / "world" == "world"
830 # assert "/hello" / "/world" == "/world"
831 #
832 # This operator is quite useful for chaining changes of path.
833 # The next one being relative to the previous one.
834 #
835 # var a = "foo"
836 # var b = "/bar"
837 # var c = "baz/foobar"
838 # assert a/b/c == "/bar/baz/foobar"
839 fun /(path: String): String do return join_path(path)
840
841 # Returns the relative path needed to go from `self` to `dest`.
842 #
843 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
844 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
845 #
846 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
847 #
848 # In some cases, the result is still independent of the current directory:
849 #
850 # assert "foo/bar".relpath("..") == "../../.."
851 #
852 # In other cases, parts of the current directory may be exhibited:
853 #
854 # var p = "../foo/bar".relpath("baz")
855 # var c = getcwd.basename("")
856 # assert p == "../../{c}/baz"
857 #
858 # For path resolution independent of the current directory (eg. for paths in URL),
859 # or to use an other starting directory than the current directory,
860 # just force absolute paths:
861 #
862 # var start = "/a/b/c/d"
863 # var p2 = (start/"../foo/bar").relpath(start/"baz")
864 # assert p2 == "../../d/baz"
865 #
866 #
867 # Neither `self` or `dest` has to be real paths or to exist in directories since
868 # the resolution is only done with string manipulations and without any access to
869 # the underlying file system.
870 #
871 # If `self` and `dest` are the same directory, the empty string is returned:
872 #
873 # assert "foo".relpath("foo") == ""
874 # assert "foo/../bar".relpath("bar") == ""
875 #
876 # The empty string and "." designate both the current directory:
877 #
878 # assert "".relpath("foo/bar") == "foo/bar"
879 # assert ".".relpath("foo/bar") == "foo/bar"
880 # assert "foo/bar".relpath("") == "../.."
881 # assert "/" + "/".relpath(".") == getcwd
882 fun relpath(dest: String): String
883 do
884 var cwd = getcwd
885 var from = (cwd/self).simplify_path.split("/")
886 if from.last.is_empty then from.pop # case for the root directory
887 var to = (cwd/dest).simplify_path.split("/")
888 if to.last.is_empty then to.pop # case for the root directory
889
890 # Remove common prefixes
891 while not from.is_empty and not to.is_empty and from.first == to.first do
892 from.shift
893 to.shift
894 end
895
896 # Result is going up in `from` with ".." then going down following `to`
897 var from_len = from.length
898 if from_len == 0 then return to.join("/")
899 var up = "../"*(from_len-1) + ".."
900 if to.is_empty then return up
901 var res = up + "/" + to.join("/")
902 return res
903 end
904
905 # Create a directory (and all intermediate directories if needed)
906 #
907 # Return an error object in case of error.
908 #
909 # assert "/etc/".mkdir != null
910 fun mkdir: nullable Error
911 do
912 var dirs = self.split_with("/")
913 var path = new FlatBuffer
914 if dirs.is_empty then return null
915 if dirs[0].is_empty then
916 # it was a starting /
917 path.add('/')
918 end
919 var error: nullable Error = null
920 for d in dirs do
921 if d.is_empty then continue
922 path.append(d)
923 path.add('/')
924 var res = path.to_s.to_cstring.file_mkdir
925 if not res and error == null then
926 error = new IOError("Cannot create directory `{path}`: {sys.errno.strerror}")
927 end
928 end
929 return error
930 end
931
932 # Delete a directory and all of its content, return `true` on success
933 #
934 # Does not go through symbolic links and may get stuck in a cycle if there
935 # is a cycle in the filesystem.
936 #
937 # Return an error object in case of error.
938 #
939 # assert "/fail/does not/exist".rmdir != null
940 fun rmdir: nullable Error
941 do
942 var res = to_path.rmdir
943 if res then return null
944 var error = new IOError("Cannot change remove `{self}`: {sys.errno.strerror}")
945 return error
946 end
947
948 # Change the current working directory
949 #
950 # "/etc".chdir
951 # assert getcwd == "/etc"
952 # "..".chdir
953 # assert getcwd == "/"
954 #
955 # Return an error object in case of error.
956 #
957 # assert "/etc".chdir == null
958 # assert "/fail/does no/exist".chdir != null
959 # assert getcwd == "/etc" # unchanger
960 fun chdir: nullable Error
961 do
962 var res = to_cstring.file_chdir
963 if res then return null
964 var error = new IOError("Cannot change directory to `{self}`: {sys.errno.strerror}")
965 return error
966 end
967
968 # Return right-most extension (without the dot)
969 #
970 # Only the last extension is returned.
971 # There is no special case for combined extensions.
972 #
973 # assert "file.txt".file_extension == "txt"
974 # assert "file.tar.gz".file_extension == "gz"
975 #
976 # For file without extension, `null` is returned.
977 # Hoever, for trailing dot, `""` is returned.
978 #
979 # assert "file".file_extension == null
980 # assert "file.".file_extension == ""
981 #
982 # The starting dot of hidden files is never considered.
983 #
984 # assert ".file.txt".file_extension == "txt"
985 # assert ".file".file_extension == null
986 fun file_extension: nullable String
987 do
988 var last_slash = chars.last_index_of('.')
989 if last_slash > 0 then
990 return substring( last_slash+1, length )
991 else
992 return null
993 end
994 end
995
996 # Returns entries contained within the directory represented by self.
997 #
998 # var files = "/etc".files
999 # assert files.has("issue")
1000 #
1001 # Returns an empty array in case of error
1002 #
1003 # files = "/etc/issue".files
1004 # assert files.is_empty
1005 #
1006 # TODO find a better way to handle errors and to give them back to the user.
1007 fun files: Array[String] is extern import Array[String], Array[String].add, NativeString.to_s, String.to_cstring `{
1008 char *dir_path;
1009 DIR *dir;
1010
1011 dir_path = String_to_cstring( recv );
1012 if ((dir = opendir(dir_path)) == NULL)
1013 {
1014 //perror( dir_path );
1015 //exit( 1 );
1016 Array_of_String results;
1017 results = new_Array_of_String();
1018 return results;
1019 }
1020 else
1021 {
1022 Array_of_String results;
1023 String file_name;
1024 struct dirent *de;
1025
1026 results = new_Array_of_String();
1027
1028 while ( ( de = readdir( dir ) ) != NULL )
1029 if ( strcmp( de->d_name, ".." ) != 0 &&
1030 strcmp( de->d_name, "." ) != 0 )
1031 {
1032 file_name = NativeString_to_s( strdup( de->d_name ) );
1033 Array_of_String_add( results, file_name );
1034 }
1035
1036 closedir( dir );
1037 return results;
1038 }
1039 `}
1040 end
1041
1042 redef class NativeString
1043 private fun file_exists: Bool is extern "string_NativeString_NativeString_file_exists_0"
1044 private fun file_stat: NativeFileStat is extern "string_NativeString_NativeString_file_stat_0"
1045 private fun file_lstat: NativeFileStat `{
1046 struct stat* stat_element;
1047 int res;
1048 stat_element = malloc(sizeof(struct stat));
1049 res = lstat(recv, stat_element);
1050 if (res == -1) return NULL;
1051 return stat_element;
1052 `}
1053 private fun file_mkdir: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
1054 private fun rmdir: Bool `{ return !rmdir(recv); `}
1055 private fun file_delete: Bool is extern "string_NativeString_NativeString_file_delete_0"
1056 private fun file_chdir: Bool is extern "string_NativeString_NativeString_file_chdir_0"
1057 private fun file_realpath: NativeString is extern "file_NativeString_realpath"
1058 end
1059
1060 # This class is system dependent ... must reify the vfs
1061 private extern class NativeFileStat `{ struct stat * `}
1062 # Returns the permission bits of file
1063 fun mode: Int is extern "file_FileStat_FileStat_mode_0"
1064 # Returns the last access time
1065 fun atime: Int is extern "file_FileStat_FileStat_atime_0"
1066 # Returns the last status change time
1067 fun ctime: Int is extern "file_FileStat_FileStat_ctime_0"
1068 # Returns the last modification time
1069 fun mtime: Int is extern "file_FileStat_FileStat_mtime_0"
1070 # Returns the size
1071 fun size: Int is extern "file_FileStat_FileStat_size_0"
1072
1073 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
1074 fun is_reg: Bool `{ return S_ISREG(recv->st_mode); `}
1075 # Returns true if it is a directory
1076 fun is_dir: Bool `{ return S_ISDIR(recv->st_mode); `}
1077 # Returns true if it is a character device
1078 fun is_chr: Bool `{ return S_ISCHR(recv->st_mode); `}
1079 # Returns true if it is a block device
1080 fun is_blk: Bool `{ return S_ISBLK(recv->st_mode); `}
1081 # Returns true if the type is fifo
1082 fun is_fifo: Bool `{ return S_ISFIFO(recv->st_mode); `}
1083 # Returns true if the type is a link
1084 fun is_lnk: Bool `{ return S_ISLNK(recv->st_mode); `}
1085 # Returns true if the type is a socket
1086 fun is_sock: Bool `{ return S_ISSOCK(recv->st_mode); `}
1087 end
1088
1089 # Instance of this class are standard FILE * pointers
1090 private extern class NativeFile `{ FILE* `}
1091 fun io_read(buf: NativeString, len: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
1092 fun io_write(buf: NativeString, len: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
1093 fun io_close: Int is extern "file_NativeFile_NativeFile_io_close_0"
1094 fun file_stat: NativeFileStat is extern "file_NativeFile_NativeFile_file_stat_0"
1095 fun fileno: Int `{ return fileno(recv); `}
1096 # Flushes the buffer, forcing the write operation
1097 fun flush: Int is extern "fflush"
1098 # Used to specify how the buffering will be handled for the current stream.
1099 fun set_buffering_type(buf_length: Int, mode: Int): Int is extern "file_NativeFile_NativeFile_set_buffering_type_0"
1100
1101 new io_open_read(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
1102 new io_open_write(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
1103 new native_stdin is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
1104 new native_stdout is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
1105 new native_stderr is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
1106 end
1107
1108 redef class Sys
1109
1110 # Standard input
1111 var stdin: PollableReader = new Stdin is protected writable, lazy
1112
1113 # Standard output
1114 var stdout: Writer = new Stdout is protected writable, lazy
1115
1116 # Standard output for errors
1117 var stderr: Writer = new Stderr is protected writable, lazy
1118
1119 # Enumeration for buffer mode full (flushes when buffer is full)
1120 fun buffer_mode_full: Int is extern "file_Sys_Sys_buffer_mode_full_0"
1121 # Enumeration for buffer mode line (flushes when a `\n` is encountered)
1122 fun buffer_mode_line: Int is extern "file_Sys_Sys_buffer_mode_line_0"
1123 # Enumeration for buffer mode none (flushes ASAP when something is written)
1124 fun buffer_mode_none: Int is extern "file_Sys_Sys_buffer_mode_none_0"
1125
1126 # returns first available stream to read or write to
1127 # return null on interruption (possibly a signal)
1128 protected fun poll( streams : Sequence[FileStream] ) : nullable FileStream
1129 do
1130 var in_fds = new Array[Int]
1131 var out_fds = new Array[Int]
1132 var fd_to_stream = new HashMap[Int,FileStream]
1133 for s in streams do
1134 var fd = s.fd
1135 if s isa FileReader then in_fds.add( fd )
1136 if s isa FileWriter then out_fds.add( fd )
1137
1138 fd_to_stream[fd] = s
1139 end
1140
1141 var polled_fd = intern_poll( in_fds, out_fds )
1142
1143 if polled_fd == null then
1144 return null
1145 else
1146 return fd_to_stream[polled_fd]
1147 end
1148 end
1149
1150 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) `{
1151 int in_len, out_len, total_len;
1152 struct pollfd *c_fds;
1153 sigset_t sigmask;
1154 int i;
1155 int first_polled_fd = -1;
1156 int result;
1157
1158 in_len = Array_of_Int_length( in_fds );
1159 out_len = Array_of_Int_length( out_fds );
1160 total_len = in_len + out_len;
1161 c_fds = malloc( sizeof(struct pollfd) * total_len );
1162
1163 /* input streams */
1164 for ( i=0; i<in_len; i ++ ) {
1165 int fd;
1166 fd = Array_of_Int__index( in_fds, i );
1167
1168 c_fds[i].fd = fd;
1169 c_fds[i].events = POLLIN;
1170 }
1171
1172 /* output streams */
1173 for ( i=0; i<out_len; i ++ ) {
1174 int fd;
1175 fd = Array_of_Int__index( out_fds, i );
1176
1177 c_fds[i].fd = fd;
1178 c_fds[i].events = POLLOUT;
1179 }
1180
1181 /* poll all fds, unlimited timeout */
1182 result = poll( c_fds, total_len, -1 );
1183
1184 if ( result > 0 ) {
1185 /* analyse results */
1186 for ( i=0; i<total_len; i++ )
1187 if ( c_fds[i].revents & c_fds[i].events || /* awaited event */
1188 c_fds[i].revents & POLLHUP ) /* closed */
1189 {
1190 first_polled_fd = c_fds[i].fd;
1191 break;
1192 }
1193
1194 return Int_as_nullable( first_polled_fd );
1195 }
1196 else if ( result < 0 )
1197 fprintf( stderr, "Error in Stream:poll: %s\n", strerror( errno ) );
1198
1199 return null_Int();
1200 `}
1201
1202 end
1203
1204 # Print `objects` on the standard output (`stdout`).
1205 fun printn(objects: Object...)
1206 do
1207 sys.stdout.write(objects.to_s)
1208 end
1209
1210 # Print an `object` on the standard output (`stdout`) and add a newline.
1211 fun print(object: Object)
1212 do
1213 sys.stdout.write(object.to_s)
1214 sys.stdout.write("\n")
1215 end
1216
1217 # Read a character from the standard input (`stdin`).
1218 fun getc: Char
1219 do
1220 return sys.stdin.read_char.ascii
1221 end
1222
1223 # Read a line from the standard input (`stdin`).
1224 fun gets: String
1225 do
1226 return sys.stdin.read_line
1227 end
1228
1229 # Return the working (current) directory
1230 fun getcwd: String do return file_getcwd.to_s
1231 private fun file_getcwd: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"