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