Merge branch 'master' into 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 # 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 # * no I/O access is performed
622 # * the validity of the path is not checked
623 #
624 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
625 # assert "../dir/file".simplify_path == "../dir/file"
626 # assert "dir/../../".simplify_path == ".."
627 # assert "dir/..".simplify_path == "."
628 # assert "//absolute//path/".simplify_path == "/absolute/path"
629 # assert "//absolute//../".simplify_path == "/"
630 fun simplify_path: String
631 do
632 var a = self.split_with("/")
633 var a2 = new Array[String]
634 for x in a do
635 if x == "." then continue
636 if x == "" and not a2.is_empty then continue
637 if x == ".." and not a2.is_empty and a2.last != ".." then
638 a2.pop
639 continue
640 end
641 a2.push(x)
642 end
643 if a2.is_empty then return "."
644 if a2.length == 1 and a2.first == "" then return "/"
645 return a2.join("/")
646 end
647
648 # Correctly join two path using the directory separator.
649 #
650 # Using a standard "{self}/{path}" does not work in the following cases:
651 #
652 # * `self` is empty.
653 # * `path` ends with `'/'`.
654 # * `path` starts with `'/'`.
655 #
656 # This method ensures that the join is valid.
657 #
658 # assert "hello".join_path("world") == "hello/world"
659 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
660 # assert "".join_path("world") == "world"
661 # assert "hello".join_path("/world") == "/world"
662 # assert "hello/".join_path("world") == "hello/world"
663 # assert "hello/".join_path("/world") == "/world"
664 #
665 # Note: You may want to use `simplify_path` on the result.
666 #
667 # Note: This method works only with POSIX paths.
668 fun join_path(path: String): String
669 do
670 if path.is_empty then return self
671 if self.is_empty then return path
672 if path.chars[0] == '/' then return path
673 if self.last == '/' then return "{self}{path}"
674 return "{self}/{path}"
675 end
676
677 # Convert the path (`self`) to a program name.
678 #
679 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
680 # used as a program name. In order to do that, prepend `./` if needed.
681 #
682 # assert "foo".to_program_name == "./foo"
683 # assert "/foo".to_program_name == "/foo"
684 # assert "".to_program_name == "./" # At least, your shell will detect the error.
685 fun to_program_name: String do
686 if self.has_prefix("/") then
687 return self
688 else
689 return "./{self}"
690 end
691 end
692
693 # Alias for `join_path`
694 #
695 # assert "hello" / "world" == "hello/world"
696 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
697 # assert "" / "world" == "world"
698 # assert "/hello" / "/world" == "/world"
699 #
700 # This operator is quite useful for chaining changes of path.
701 # The next one being relative to the previous one.
702 #
703 # var a = "foo"
704 # var b = "/bar"
705 # var c = "baz/foobar"
706 # assert a/b/c == "/bar/baz/foobar"
707 fun /(path: String): String do return join_path(path)
708
709 # Returns the relative path needed to go from `self` to `dest`.
710 #
711 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
712 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
713 #
714 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
715 #
716 # In some cases, the result is still independent of the current directory:
717 #
718 # assert "foo/bar".relpath("..") == "../../.."
719 #
720 # In other cases, parts of the current directory may be exhibited:
721 #
722 # var p = "../foo/bar".relpath("baz")
723 # var c = getcwd.basename("")
724 # assert p == "../../{c}/baz"
725 #
726 # For path resolution independent of the current directory (eg. for paths in URL),
727 # or to use an other starting directory than the current directory,
728 # just force absolute paths:
729 #
730 # var start = "/a/b/c/d"
731 # var p2 = (start/"../foo/bar").relpath(start/"baz")
732 # assert p2 == "../../d/baz"
733 #
734 #
735 # Neither `self` or `dest` has to be real paths or to exist in directories since
736 # the resolution is only done with string manipulations and without any access to
737 # the underlying file system.
738 #
739 # If `self` and `dest` are the same directory, the empty string is returned:
740 #
741 # assert "foo".relpath("foo") == ""
742 # assert "foo/../bar".relpath("bar") == ""
743 #
744 # The empty string and "." designate both the current directory:
745 #
746 # assert "".relpath("foo/bar") == "foo/bar"
747 # assert ".".relpath("foo/bar") == "foo/bar"
748 # assert "foo/bar".relpath("") == "../.."
749 # assert "/" + "/".relpath(".") == getcwd
750 fun relpath(dest: String): String
751 do
752 var cwd = getcwd
753 var from = (cwd/self).simplify_path.split("/")
754 if from.last.is_empty then from.pop # case for the root directory
755 var to = (cwd/dest).simplify_path.split("/")
756 if to.last.is_empty then to.pop # case for the root directory
757
758 # Remove common prefixes
759 while not from.is_empty and not to.is_empty and from.first == to.first do
760 from.shift
761 to.shift
762 end
763
764 # Result is going up in `from` with ".." then going down following `to`
765 var from_len = from.length
766 if from_len == 0 then return to.join("/")
767 var up = "../"*(from_len-1) + ".."
768 if to.is_empty then return up
769 var res = up + "/" + to.join("/")
770 return res
771 end
772
773 # Create a directory (and all intermediate directories if needed)
774 fun mkdir
775 do
776 var dirs = self.split_with("/")
777 var path = new FlatBuffer
778 if dirs.is_empty then return
779 if dirs[0].is_empty then
780 # it was a starting /
781 path.add('/')
782 end
783 for d in dirs do
784 if d.is_empty then continue
785 path.append(d)
786 path.add('/')
787 path.to_s.to_cstring.file_mkdir
788 end
789 end
790
791 # Delete a directory and all of its content, return `true` on success
792 #
793 # Does not go through symbolic links and may get stuck in a cycle if there
794 # is a cycle in the filesystem.
795 fun rmdir: Bool do return to_path.rmdir
796
797 # Change the current working directory
798 #
799 # "/etc".chdir
800 # assert getcwd == "/etc"
801 # "..".chdir
802 # assert getcwd == "/"
803 #
804 # TODO: errno
805 fun chdir do to_cstring.file_chdir
806
807 # Return right-most extension (without the dot)
808 #
809 # Only the last extension is returned.
810 # There is no special case for combined extensions.
811 #
812 # assert "file.txt".file_extension == "txt"
813 # assert "file.tar.gz".file_extension == "gz"
814 #
815 # For file without extension, `null` is returned.
816 # Hoever, for trailing dot, `""` is returned.
817 #
818 # assert "file".file_extension == null
819 # assert "file.".file_extension == ""
820 #
821 # The starting dot of hidden files is never considered.
822 #
823 # assert ".file.txt".file_extension == "txt"
824 # assert ".file".file_extension == null
825 fun file_extension: nullable String
826 do
827 var last_slash = chars.last_index_of('.')
828 if last_slash > 0 then
829 return substring( last_slash+1, length )
830 else
831 return null
832 end
833 end
834
835 # returns files contained within the directory represented by self
836 fun files: Array[String] is extern import Array[String], Array[String].add, NativeString.to_s, String.to_cstring `{
837 char *dir_path;
838 DIR *dir;
839
840 dir_path = String_to_cstring( recv );
841 if ((dir = opendir(dir_path)) == NULL)
842 {
843 perror( dir_path );
844 exit( 1 );
845 }
846 else
847 {
848 Array_of_String results;
849 String file_name;
850 struct dirent *de;
851
852 results = new_Array_of_String();
853
854 while ( ( de = readdir( dir ) ) != NULL )
855 if ( strcmp( de->d_name, ".." ) != 0 &&
856 strcmp( de->d_name, "." ) != 0 )
857 {
858 file_name = NativeString_to_s( strdup( de->d_name ) );
859 Array_of_String_add( results, file_name );
860 }
861
862 closedir( dir );
863 return results;
864 }
865 `}
866 end
867
868 redef class NativeString
869 private fun file_exists: Bool is extern "string_NativeString_NativeString_file_exists_0"
870 private fun file_stat: NativeFileStat is extern "string_NativeString_NativeString_file_stat_0"
871 private fun file_lstat: NativeFileStat `{
872 struct stat* stat_element;
873 int res;
874 stat_element = malloc(sizeof(struct stat));
875 res = lstat(recv, stat_element);
876 if (res == -1) return NULL;
877 return stat_element;
878 `}
879 private fun file_mkdir: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
880 private fun rmdir: Bool `{ return rmdir(recv); `}
881 private fun file_delete: Bool is extern "string_NativeString_NativeString_file_delete_0"
882 private fun file_chdir is extern "string_NativeString_NativeString_file_chdir_0"
883 private fun file_realpath: NativeString is extern "file_NativeString_realpath"
884 end
885
886 # This class is system dependent ... must reify the vfs
887 extern class NativeFileStat `{ struct stat * `}
888 # Returns the permission bits of file
889 fun mode: Int is extern "file_FileStat_FileStat_mode_0"
890 # Returns the last access time
891 fun atime: Int is extern "file_FileStat_FileStat_atime_0"
892 # Returns the last status change time
893 fun ctime: Int is extern "file_FileStat_FileStat_ctime_0"
894 # Returns the last modification time
895 fun mtime: Int is extern "file_FileStat_FileStat_mtime_0"
896 # Returns the size
897 fun size: Int is extern "file_FileStat_FileStat_size_0"
898
899 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
900 fun is_reg: Bool `{ return S_ISREG(recv->st_mode); `}
901 # Returns true if it is a directory
902 fun is_dir: Bool `{ return S_ISDIR(recv->st_mode); `}
903 # Returns true if it is a character device
904 fun is_chr: Bool `{ return S_ISCHR(recv->st_mode); `}
905 # Returns true if it is a block device
906 fun is_blk: Bool `{ return S_ISBLK(recv->st_mode); `}
907 # Returns true if the type is fifo
908 fun is_fifo: Bool `{ return S_ISFIFO(recv->st_mode); `}
909 # Returns true if the type is a link
910 fun is_lnk: Bool `{ return S_ISLNK(recv->st_mode); `}
911 # Returns true if the type is a socket
912 fun is_sock: Bool `{ return S_ISSOCK(recv->st_mode); `}
913 end
914
915 # Instance of this class are standard FILE * pointers
916 private extern class NativeFile `{ FILE* `}
917 fun io_read(buf: NativeString, len: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
918 fun io_write(buf: NativeString, len: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
919 fun io_close: Int is extern "file_NativeFile_NativeFile_io_close_0"
920 fun file_stat: NativeFileStat is extern "file_NativeFile_NativeFile_file_stat_0"
921 fun fileno: Int `{ return fileno(recv); `}
922 # Flushes the buffer, forcing the write operation
923 fun flush: Int is extern "fflush"
924 # Used to specify how the buffering will be handled for the current stream.
925 fun set_buffering_type(buf_length: Int, mode: Int): Int is extern "file_NativeFile_NativeFile_set_buffering_type_0"
926
927 new io_open_read(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
928 new io_open_write(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
929 new native_stdin is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
930 new native_stdout is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
931 new native_stderr is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
932 end
933
934 redef class Sys
935
936 init do
937 if stdout isa FStream then stdout.as(FStream).set_buffering_mode(256, buffer_mode_line)
938 end
939
940 # Standard input
941 var stdin: PollableIStream = new Stdin is protected writable
942
943 # Standard output
944 var stdout: OStream = new Stdout is protected writable
945
946 # Standard output for errors
947 var stderr: OStream = new Stderr is protected writable
948
949 # Enumeration for buffer mode full (flushes when buffer is full)
950 fun buffer_mode_full: Int is extern "file_Sys_Sys_buffer_mode_full_0"
951 # Enumeration for buffer mode line (flushes when a `\n` is encountered)
952 fun buffer_mode_line: Int is extern "file_Sys_Sys_buffer_mode_line_0"
953 # Enumeration for buffer mode none (flushes ASAP when something is written)
954 fun buffer_mode_none: Int is extern "file_Sys_Sys_buffer_mode_none_0"
955
956 # returns first available stream to read or write to
957 # return null on interruption (possibly a signal)
958 protected fun poll( streams : Sequence[FStream] ) : nullable FStream
959 do
960 var in_fds = new Array[Int]
961 var out_fds = new Array[Int]
962 var fd_to_stream = new HashMap[Int,FStream]
963 for s in streams do
964 var fd = s.fd
965 if s isa IFStream then in_fds.add( fd )
966 if s isa OFStream then out_fds.add( fd )
967
968 fd_to_stream[fd] = s
969 end
970
971 var polled_fd = intern_poll( in_fds, out_fds )
972
973 if polled_fd == null then
974 return null
975 else
976 return fd_to_stream[polled_fd]
977 end
978 end
979
980 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) `{
981 int in_len, out_len, total_len;
982 struct pollfd *c_fds;
983 sigset_t sigmask;
984 int i;
985 int first_polled_fd = -1;
986 int result;
987
988 in_len = Array_of_Int_length( in_fds );
989 out_len = Array_of_Int_length( out_fds );
990 total_len = in_len + out_len;
991 c_fds = malloc( sizeof(struct pollfd) * total_len );
992
993 /* input streams */
994 for ( i=0; i<in_len; i ++ ) {
995 int fd;
996 fd = Array_of_Int__index( in_fds, i );
997
998 c_fds[i].fd = fd;
999 c_fds[i].events = POLLIN;
1000 }
1001
1002 /* output streams */
1003 for ( i=0; i<out_len; i ++ ) {
1004 int fd;
1005 fd = Array_of_Int__index( out_fds, i );
1006
1007 c_fds[i].fd = fd;
1008 c_fds[i].events = POLLOUT;
1009 }
1010
1011 /* poll all fds, unlimited timeout */
1012 result = poll( c_fds, total_len, -1 );
1013
1014 if ( result > 0 ) {
1015 /* analyse results */
1016 for ( i=0; i<total_len; i++ )
1017 if ( c_fds[i].revents & c_fds[i].events || /* awaited event */
1018 c_fds[i].revents & POLLHUP ) /* closed */
1019 {
1020 first_polled_fd = c_fds[i].fd;
1021 break;
1022 }
1023
1024 return Int_as_nullable( first_polled_fd );
1025 }
1026 else if ( result < 0 )
1027 fprintf( stderr, "Error in Stream:poll: %s\n", strerror( errno ) );
1028
1029 return null_Int();
1030 `}
1031
1032 end
1033
1034 # Print `objects` on the standard output (`stdout`).
1035 protected fun printn(objects: Object...)
1036 do
1037 sys.stdout.write(objects.to_s)
1038 end
1039
1040 # Print an `object` on the standard output (`stdout`) and add a newline.
1041 protected fun print(object: Object)
1042 do
1043 sys.stdout.write(object.to_s)
1044 sys.stdout.write("\n")
1045 end
1046
1047 # Read a character from the standard input (`stdin`).
1048 protected fun getc: Char
1049 do
1050 return sys.stdin.read_char.ascii
1051 end
1052
1053 # Read a line from the standard input (`stdin`).
1054 protected fun gets: String
1055 do
1056 return sys.stdin.read_line
1057 end
1058
1059 # Return the working (current) directory
1060 protected fun getcwd: String do return file_getcwd.to_s
1061 private fun file_getcwd: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"