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