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