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