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