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