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