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