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