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