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