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