Merge: Doc down
[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 # Lists the name of the files contained within the directory at `path`
370 #
371 # Require: `exists and is_dir`
372 fun files: Array[Path]
373 do
374 var files = new Array[Path]
375 for filename in path.files do
376 files.add new Path(path / filename)
377 end
378 return files
379 end
380
381 # Delete a directory and all of its content, return `true` on success
382 #
383 # Does not go through symbolic links and may get stuck in a cycle if there
384 # is a cycle in the file system.
385 fun rmdir: Bool
386 do
387 var ok = true
388 for file in self.files do
389 var stat = file.link_stat
390 if stat.is_dir then
391 ok = file.rmdir and ok
392 else
393 ok = file.delete and ok
394 end
395 end
396
397 # Delete the directory itself
398 if ok then path.to_cstring.rmdir
399
400 return ok
401 end
402
403 redef fun ==(other) do return other isa Path and path.simplify_path == other.path.simplify_path
404 redef fun hash do return path.simplify_path.hash
405 end
406
407 # Information on a file
408 #
409 # Created by `Path::stat` and `Path::link_stat`.
410 #
411 # The information within this class is gathered when the instance is initialized
412 # it will not be updated if the targeted file is modified.
413 class FileStat
414 super Finalizable
415
416 # TODO private init
417
418 # The low-level status of a file
419 #
420 # See: POSIX stat(2)
421 private var stat: NativeFileStat
422
423 private var finalized = false
424
425 redef fun finalize
426 do
427 if not finalized then
428 stat.free
429 finalized = true
430 end
431 end
432
433 # Returns the last access time in seconds since Epoch
434 fun last_access_time: Int
435 do
436 assert not finalized
437 return stat.atime
438 end
439
440 # Returns the last modification time in seconds since Epoch
441 fun last_modification_time: Int
442 do
443 assert not finalized
444 return stat.mtime
445 end
446
447 # Size of the file at `path`
448 fun size: Int
449 do
450 assert not finalized
451 return stat.size
452 end
453
454 # Is this a regular file and not a device file, pipe, socket, etc.?
455 fun is_file: Bool
456 do
457 assert not finalized
458 return stat.is_reg
459 end
460
461 # Is this a directory?
462 fun is_dir: Bool
463 do
464 assert not finalized
465 return stat.is_dir
466 end
467
468 # Is this a symbolic link?
469 fun is_link: Bool
470 do
471 assert not finalized
472 return stat.is_lnk
473 end
474
475 # FIXME Make the following POSIX only? or implement in some other way on Windows
476
477 # Returns the last status change time in seconds since Epoch
478 fun last_status_change_time: Int
479 do
480 assert not finalized
481 return stat.ctime
482 end
483
484 # Returns the permission bits of file
485 fun mode: Int
486 do
487 assert not finalized
488 return stat.mode
489 end
490
491 # Is this a character device?
492 fun is_chr: Bool
493 do
494 assert not finalized
495 return stat.is_chr
496 end
497
498 # Is this a block device?
499 fun is_blk: Bool
500 do
501 assert not finalized
502 return stat.is_blk
503 end
504
505 # Is this a FIFO pipe?
506 fun is_fifo: Bool
507 do
508 assert not finalized
509 return stat.is_fifo
510 end
511
512 # Is this a UNIX socket
513 fun is_sock: Bool
514 do
515 assert not finalized
516 return stat.is_sock
517 end
518 end
519
520 redef class Text
521 # Access file system related services on the path at `self`
522 fun to_path: Path do return new Path(to_s)
523 end
524
525 redef class String
526 # return true if a file with this names exists
527 fun file_exists: Bool do return to_cstring.file_exists
528
529 # The status of a file. see POSIX stat(2).
530 fun file_stat: NativeFileStat do return to_cstring.file_stat
531
532 # The status of a file or of a symlink. see POSIX lstat(2).
533 fun file_lstat: NativeFileStat do return to_cstring.file_lstat
534
535 # Remove a file, return true if success
536 fun file_delete: Bool do return to_cstring.file_delete
537
538 # Copy content of file at `self` to `dest`
539 fun file_copy_to(dest: String) do to_path.copy(dest.to_path)
540
541 # Remove the trailing extension `ext`.
542 #
543 # `ext` usually starts with a dot but could be anything.
544 #
545 # assert "file.txt".strip_extension(".txt") == "file"
546 # assert "file.txt".strip_extension("le.txt") == "fi"
547 # assert "file.txt".strip_extension("xt") == "file.t"
548 #
549 # if `ext` is not present, `self` is returned unmodified.
550 #
551 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
552 fun strip_extension(ext: String): String
553 do
554 if has_suffix(ext) then
555 return substring(0, length - ext.length)
556 end
557 return self
558 end
559
560 # Extract the basename of a path and remove the extension
561 #
562 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
563 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
564 # assert "path/to".basename(".ext") == "to"
565 # assert "path/to/".basename(".ext") == "to"
566 # assert "path".basename("") == "path"
567 # assert "/path".basename("") == "path"
568 # assert "/".basename("") == "/"
569 # assert "".basename("") == ""
570 fun basename(ext: String): String
571 do
572 var l = length - 1 # Index of the last char
573 while l > 0 and self.chars[l] == '/' do l -= 1 # remove all trailing `/`
574 if l == 0 then return "/"
575 var pos = chars.last_index_of_from('/', l)
576 var n = self
577 if pos >= 0 then
578 n = substring(pos+1, l-pos)
579 end
580 return n.strip_extension(ext)
581 end
582
583 # Extract the dirname of a path
584 #
585 # assert "/path/to/a_file.ext".dirname == "/path/to"
586 # assert "path/to/a_file.ext".dirname == "path/to"
587 # assert "path/to".dirname == "path"
588 # assert "path/to/".dirname == "path"
589 # assert "path".dirname == "."
590 # assert "/path".dirname == "/"
591 # assert "/".dirname == "/"
592 # assert "".dirname == "."
593 fun dirname: String
594 do
595 var l = length - 1 # Index of the last char
596 while l > 0 and self.chars[l] == '/' do l -= 1 # remove all trailing `/`
597 var pos = chars.last_index_of_from('/', l)
598 if pos > 0 then
599 return substring(0, pos)
600 else if pos == 0 then
601 return "/"
602 else
603 return "."
604 end
605 end
606
607 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
608 fun realpath: String do
609 var cs = to_cstring.file_realpath
610 var res = cs.to_s_with_copy
611 # cs.free_malloc # FIXME memory leak
612 return res
613 end
614
615 # Simplify a file path by remove useless ".", removing "//", and resolving ".."
616 # ".." are not resolved if they start the path
617 # starting "/" is not removed
618 # trainling "/" is removed
619 #
620 # Note that the method only wonrk on the string:
621 #
622 # * no I/O access is performed
623 # * the validity of the path is not checked
624 #
625 # ~~~
626 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
627 # assert "../dir/file".simplify_path == "../dir/file"
628 # assert "dir/../../".simplify_path == ".."
629 # assert "dir/..".simplify_path == "."
630 # assert "//absolute//path/".simplify_path == "/absolute/path"
631 # assert "//absolute//../".simplify_path == "/"
632 # ~~~
633 fun simplify_path: String
634 do
635 var a = self.split_with("/")
636 var a2 = new Array[String]
637 for x in a do
638 if x == "." then continue
639 if x == "" and not a2.is_empty then continue
640 if x == ".." and not a2.is_empty and a2.last != ".." then
641 a2.pop
642 continue
643 end
644 a2.push(x)
645 end
646 if a2.is_empty then return "."
647 if a2.length == 1 and a2.first == "" then return "/"
648 return a2.join("/")
649 end
650
651 # Correctly join two path using the directory separator.
652 #
653 # Using a standard "{self}/{path}" does not work in the following cases:
654 #
655 # * `self` is empty.
656 # * `path` ends with `'/'`.
657 # * `path` starts with `'/'`.
658 #
659 # This method ensures that the join is valid.
660 #
661 # assert "hello".join_path("world") == "hello/world"
662 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
663 # assert "".join_path("world") == "world"
664 # assert "hello".join_path("/world") == "/world"
665 # assert "hello/".join_path("world") == "hello/world"
666 # assert "hello/".join_path("/world") == "/world"
667 #
668 # Note: You may want to use `simplify_path` on the result.
669 #
670 # Note: This method works only with POSIX paths.
671 fun join_path(path: String): String
672 do
673 if path.is_empty then return self
674 if self.is_empty then return path
675 if path.chars[0] == '/' then return path
676 if self.last == '/' then return "{self}{path}"
677 return "{self}/{path}"
678 end
679
680 # Convert the path (`self`) to a program name.
681 #
682 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
683 # used as a program name. In order to do that, prepend `./` if needed.
684 #
685 # assert "foo".to_program_name == "./foo"
686 # assert "/foo".to_program_name == "/foo"
687 # assert "".to_program_name == "./" # At least, your shell will detect the error.
688 fun to_program_name: String do
689 if self.has_prefix("/") then
690 return self
691 else
692 return "./{self}"
693 end
694 end
695
696 # Alias for `join_path`
697 #
698 # assert "hello" / "world" == "hello/world"
699 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
700 # assert "" / "world" == "world"
701 # assert "/hello" / "/world" == "/world"
702 #
703 # This operator is quite useful for chaining changes of path.
704 # The next one being relative to the previous one.
705 #
706 # var a = "foo"
707 # var b = "/bar"
708 # var c = "baz/foobar"
709 # assert a/b/c == "/bar/baz/foobar"
710 fun /(path: String): String do return join_path(path)
711
712 # Returns the relative path needed to go from `self` to `dest`.
713 #
714 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
715 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
716 #
717 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
718 #
719 # In some cases, the result is still independent of the current directory:
720 #
721 # assert "foo/bar".relpath("..") == "../../.."
722 #
723 # In other cases, parts of the current directory may be exhibited:
724 #
725 # var p = "../foo/bar".relpath("baz")
726 # var c = getcwd.basename("")
727 # assert p == "../../{c}/baz"
728 #
729 # For path resolution independent of the current directory (eg. for paths in URL),
730 # or to use an other starting directory than the current directory,
731 # just force absolute paths:
732 #
733 # var start = "/a/b/c/d"
734 # var p2 = (start/"../foo/bar").relpath(start/"baz")
735 # assert p2 == "../../d/baz"
736 #
737 #
738 # Neither `self` or `dest` has to be real paths or to exist in directories since
739 # the resolution is only done with string manipulations and without any access to
740 # the underlying file system.
741 #
742 # If `self` and `dest` are the same directory, the empty string is returned:
743 #
744 # assert "foo".relpath("foo") == ""
745 # assert "foo/../bar".relpath("bar") == ""
746 #
747 # The empty string and "." designate both the current directory:
748 #
749 # assert "".relpath("foo/bar") == "foo/bar"
750 # assert ".".relpath("foo/bar") == "foo/bar"
751 # assert "foo/bar".relpath("") == "../.."
752 # assert "/" + "/".relpath(".") == getcwd
753 fun relpath(dest: String): String
754 do
755 var cwd = getcwd
756 var from = (cwd/self).simplify_path.split("/")
757 if from.last.is_empty then from.pop # case for the root directory
758 var to = (cwd/dest).simplify_path.split("/")
759 if to.last.is_empty then to.pop # case for the root directory
760
761 # Remove common prefixes
762 while not from.is_empty and not to.is_empty and from.first == to.first do
763 from.shift
764 to.shift
765 end
766
767 # Result is going up in `from` with ".." then going down following `to`
768 var from_len = from.length
769 if from_len == 0 then return to.join("/")
770 var up = "../"*(from_len-1) + ".."
771 if to.is_empty then return up
772 var res = up + "/" + to.join("/")
773 return res
774 end
775
776 # Create a directory (and all intermediate directories if needed)
777 fun mkdir
778 do
779 var dirs = self.split_with("/")
780 var path = new FlatBuffer
781 if dirs.is_empty then return
782 if dirs[0].is_empty then
783 # it was a starting /
784 path.add('/')
785 end
786 for d in dirs do
787 if d.is_empty then continue
788 path.append(d)
789 path.add('/')
790 path.to_s.to_cstring.file_mkdir
791 end
792 end
793
794 # Delete a directory and all of its content, return `true` on success
795 #
796 # Does not go through symbolic links and may get stuck in a cycle if there
797 # is a cycle in the filesystem.
798 fun rmdir: Bool do return to_path.rmdir
799
800 # Change the current working directory
801 #
802 # "/etc".chdir
803 # assert getcwd == "/etc"
804 # "..".chdir
805 # assert getcwd == "/"
806 #
807 # TODO: errno
808 fun chdir do to_cstring.file_chdir
809
810 # Return right-most extension (without the dot)
811 #
812 # Only the last extension is returned.
813 # There is no special case for combined extensions.
814 #
815 # assert "file.txt".file_extension == "txt"
816 # assert "file.tar.gz".file_extension == "gz"
817 #
818 # For file without extension, `null` is returned.
819 # Hoever, for trailing dot, `""` is returned.
820 #
821 # assert "file".file_extension == null
822 # assert "file.".file_extension == ""
823 #
824 # The starting dot of hidden files is never considered.
825 #
826 # assert ".file.txt".file_extension == "txt"
827 # assert ".file".file_extension == null
828 fun file_extension: nullable String
829 do
830 var last_slash = chars.last_index_of('.')
831 if last_slash > 0 then
832 return substring( last_slash+1, length )
833 else
834 return null
835 end
836 end
837
838 # returns files contained within the directory represented by self
839 fun files: Array[String] is extern import Array[String], Array[String].add, NativeString.to_s, String.to_cstring `{
840 char *dir_path;
841 DIR *dir;
842
843 dir_path = String_to_cstring( recv );
844 if ((dir = opendir(dir_path)) == NULL)
845 {
846 perror( dir_path );
847 exit( 1 );
848 }
849 else
850 {
851 Array_of_String results;
852 String file_name;
853 struct dirent *de;
854
855 results = new_Array_of_String();
856
857 while ( ( de = readdir( dir ) ) != NULL )
858 if ( strcmp( de->d_name, ".." ) != 0 &&
859 strcmp( de->d_name, "." ) != 0 )
860 {
861 file_name = NativeString_to_s( strdup( de->d_name ) );
862 Array_of_String_add( results, file_name );
863 }
864
865 closedir( dir );
866 return results;
867 }
868 `}
869 end
870
871 redef class NativeString
872 private fun file_exists: Bool is extern "string_NativeString_NativeString_file_exists_0"
873 private fun file_stat: NativeFileStat is extern "string_NativeString_NativeString_file_stat_0"
874 private fun file_lstat: NativeFileStat `{
875 struct stat* stat_element;
876 int res;
877 stat_element = malloc(sizeof(struct stat));
878 res = lstat(recv, stat_element);
879 if (res == -1) return NULL;
880 return stat_element;
881 `}
882 private fun file_mkdir: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
883 private fun rmdir: Bool `{ return rmdir(recv); `}
884 private fun file_delete: Bool is extern "string_NativeString_NativeString_file_delete_0"
885 private fun file_chdir is extern "string_NativeString_NativeString_file_chdir_0"
886 private fun file_realpath: NativeString is extern "file_NativeString_realpath"
887 end
888
889 # This class is system dependent ... must reify the vfs
890 extern class NativeFileStat `{ struct stat * `}
891 # Returns the permission bits of file
892 fun mode: Int is extern "file_FileStat_FileStat_mode_0"
893 # Returns the last access time
894 fun atime: Int is extern "file_FileStat_FileStat_atime_0"
895 # Returns the last status change time
896 fun ctime: Int is extern "file_FileStat_FileStat_ctime_0"
897 # Returns the last modification time
898 fun mtime: Int is extern "file_FileStat_FileStat_mtime_0"
899 # Returns the size
900 fun size: Int is extern "file_FileStat_FileStat_size_0"
901
902 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
903 fun is_reg: Bool `{ return S_ISREG(recv->st_mode); `}
904 # Returns true if it is a directory
905 fun is_dir: Bool `{ return S_ISDIR(recv->st_mode); `}
906 # Returns true if it is a character device
907 fun is_chr: Bool `{ return S_ISCHR(recv->st_mode); `}
908 # Returns true if it is a block device
909 fun is_blk: Bool `{ return S_ISBLK(recv->st_mode); `}
910 # Returns true if the type is fifo
911 fun is_fifo: Bool `{ return S_ISFIFO(recv->st_mode); `}
912 # Returns true if the type is a link
913 fun is_lnk: Bool `{ return S_ISLNK(recv->st_mode); `}
914 # Returns true if the type is a socket
915 fun is_sock: Bool `{ return S_ISSOCK(recv->st_mode); `}
916 end
917
918 # Instance of this class are standard FILE * pointers
919 private extern class NativeFile `{ FILE* `}
920 fun io_read(buf: NativeString, len: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
921 fun io_write(buf: NativeString, len: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
922 fun io_close: Int is extern "file_NativeFile_NativeFile_io_close_0"
923 fun file_stat: NativeFileStat is extern "file_NativeFile_NativeFile_file_stat_0"
924 fun fileno: Int `{ return fileno(recv); `}
925 # Flushes the buffer, forcing the write operation
926 fun flush: Int is extern "fflush"
927 # Used to specify how the buffering will be handled for the current stream.
928 fun set_buffering_type(buf_length: Int, mode: Int): Int is extern "file_NativeFile_NativeFile_set_buffering_type_0"
929
930 new io_open_read(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
931 new io_open_write(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
932 new native_stdin is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
933 new native_stdout is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
934 new native_stderr is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
935 end
936
937 redef class Sys
938
939 init do
940 if stdout isa FStream then stdout.as(FStream).set_buffering_mode(256, buffer_mode_line)
941 end
942
943 # Standard input
944 var stdin: PollableIStream = new Stdin is protected writable
945
946 # Standard output
947 var stdout: OStream = new Stdout is protected writable
948
949 # Standard output for errors
950 var stderr: OStream = new Stderr is protected writable
951
952 # Enumeration for buffer mode full (flushes when buffer is full)
953 fun buffer_mode_full: Int is extern "file_Sys_Sys_buffer_mode_full_0"
954 # Enumeration for buffer mode line (flushes when a `\n` is encountered)
955 fun buffer_mode_line: Int is extern "file_Sys_Sys_buffer_mode_line_0"
956 # Enumeration for buffer mode none (flushes ASAP when something is written)
957 fun buffer_mode_none: Int is extern "file_Sys_Sys_buffer_mode_none_0"
958
959 # returns first available stream to read or write to
960 # return null on interruption (possibly a signal)
961 protected fun poll( streams : Sequence[FStream] ) : nullable FStream
962 do
963 var in_fds = new Array[Int]
964 var out_fds = new Array[Int]
965 var fd_to_stream = new HashMap[Int,FStream]
966 for s in streams do
967 var fd = s.fd
968 if s isa IFStream then in_fds.add( fd )
969 if s isa OFStream then out_fds.add( fd )
970
971 fd_to_stream[fd] = s
972 end
973
974 var polled_fd = intern_poll( in_fds, out_fds )
975
976 if polled_fd == null then
977 return null
978 else
979 return fd_to_stream[polled_fd]
980 end
981 end
982
983 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) `{
984 int in_len, out_len, total_len;
985 struct pollfd *c_fds;
986 sigset_t sigmask;
987 int i;
988 int first_polled_fd = -1;
989 int result;
990
991 in_len = Array_of_Int_length( in_fds );
992 out_len = Array_of_Int_length( out_fds );
993 total_len = in_len + out_len;
994 c_fds = malloc( sizeof(struct pollfd) * total_len );
995
996 /* input streams */
997 for ( i=0; i<in_len; i ++ ) {
998 int fd;
999 fd = Array_of_Int__index( in_fds, i );
1000
1001 c_fds[i].fd = fd;
1002 c_fds[i].events = POLLIN;
1003 }
1004
1005 /* output streams */
1006 for ( i=0; i<out_len; i ++ ) {
1007 int fd;
1008 fd = Array_of_Int__index( out_fds, i );
1009
1010 c_fds[i].fd = fd;
1011 c_fds[i].events = POLLOUT;
1012 }
1013
1014 /* poll all fds, unlimited timeout */
1015 result = poll( c_fds, total_len, -1 );
1016
1017 if ( result > 0 ) {
1018 /* analyse results */
1019 for ( i=0; i<total_len; i++ )
1020 if ( c_fds[i].revents & c_fds[i].events || /* awaited event */
1021 c_fds[i].revents & POLLHUP ) /* closed */
1022 {
1023 first_polled_fd = c_fds[i].fd;
1024 break;
1025 }
1026
1027 return Int_as_nullable( first_polled_fd );
1028 }
1029 else if ( result < 0 )
1030 fprintf( stderr, "Error in Stream:poll: %s\n", strerror( errno ) );
1031
1032 return null_Int();
1033 `}
1034
1035 end
1036
1037 # Print `objects` on the standard output (`stdout`).
1038 protected fun printn(objects: Object...)
1039 do
1040 sys.stdout.write(objects.to_s)
1041 end
1042
1043 # Print an `object` on the standard output (`stdout`) and add a newline.
1044 protected fun print(object: Object)
1045 do
1046 sys.stdout.write(object.to_s)
1047 sys.stdout.write("\n")
1048 end
1049
1050 # Read a character from the standard input (`stdin`).
1051 protected fun getc: Char
1052 do
1053 return sys.stdin.read_char.ascii
1054 end
1055
1056 # Read a line from the standard input (`stdin`).
1057 protected fun gets: String
1058 do
1059 return sys.stdin.read_line
1060 end
1061
1062 # Return the working (current) directory
1063 protected fun getcwd: String do return file_getcwd.to_s
1064 private fun file_getcwd: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"