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