Merge: Windows: fix bootstrap
[nit.git] / lib / core / 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 text::ropes
20 import text
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 <errno.h>
32 #ifndef _WIN32
33 #include <poll.h>
34 #endif
35 `}
36
37 in "C" `{
38 #ifdef _WIN32
39 #include <windows.h>
40 #endif
41 `}
42
43 # `Stream` used to interact with a File or FileDescriptor
44 abstract class FileStream
45 super Stream
46 # The path of the file.
47 var path: nullable String = null
48
49 # The FILE *.
50 private var file: nullable NativeFile = null
51
52 # The status of a file. see POSIX stat(2).
53 #
54 # var f = new FileReader.open("/etc/issue")
55 # assert f.file_stat.is_file
56 #
57 # Return null in case of error
58 fun file_stat: nullable FileStat
59 do
60 var stat = _file.as(not null).file_stat
61 if stat.address_is_null then return null
62 return new FileStat(stat)
63 end
64
65 # File descriptor of this file
66 fun fd: Int do return _file.as(not null).fileno
67
68 redef fun close
69 do
70 var file = _file
71 if file == null then return
72 if file.address_is_null then
73 if last_error != null then return
74 last_error = new IOError("Cannot close unopened file")
75 return
76 end
77 var i = file.io_close
78 if i != 0 then
79 last_error = new IOError("Close failed due to error {sys.errno.strerror}")
80 end
81 _file = null
82 end
83
84 # Sets the buffering mode for the current FileStream
85 #
86 # If the buf_size is <= 0, its value will be 512 by default
87 #
88 # The mode is any of the buffer_mode enumeration in `Sys`:
89 #
90 # * `buffer_mode_full`
91 # * `buffer_mode_line`
92 # * `buffer_mode_none`
93 fun set_buffering_mode(buf_size, mode: Int) do
94 if buf_size <= 0 then buf_size = 512
95 if _file.as(not null).set_buffering_type(buf_size, mode) != 0 then
96 last_error = new IOError("Error while changing buffering type for FileStream, returned error {sys.errno.strerror}")
97 end
98 end
99 end
100
101 # `Stream` that can read from a File
102 class FileReader
103 super FileStream
104 super PollableReader
105 # Misc
106
107 # Open the same file again.
108 # The original path is reused, therefore the reopened file can be a different file.
109 #
110 # var f = new FileReader.open("/etc/issue")
111 # var l = f.read_line
112 # f.reopen
113 # assert l == f.read_line
114 fun reopen
115 do
116 var fl = _file
117 if fl != null and not fl.address_is_null then close
118 last_error = null
119 _file = new NativeFile.io_open_read(path.as(not null).to_cstring)
120 if _file.as(not null).address_is_null then
121 last_error = new IOError("Cannot open `{path.as(not null)}`: {sys.errno.strerror}")
122 return
123 end
124 end
125
126 redef fun raw_read_byte
127 do
128 var nb = _file.as(not null).io_read(write_buffer, 1)
129 if last_error == null and _file.as(not null).ferror then
130 last_error = new IOError("Cannot read `{path.as(not null)}`: {sys.errno.strerror}")
131 end
132 if nb == 0 then return -1
133 return write_buffer[0].to_i
134 end
135
136 redef fun raw_read_bytes(cstr, max)
137 do
138 var nb = _file.as(not null).io_read(cstr, max)
139 if last_error == null and _file.as(not null).ferror then
140 last_error = new IOError("Cannot read `{path.as(not null)}`: {sys.errno.strerror}")
141 end
142 return nb
143 end
144
145 redef fun eof do
146 var fl = _file
147 if fl == null then return true
148 if fl.address_is_null then return true
149 if last_error != null then return true
150 if super then
151 if last_error != null then return true
152 return fl.feof
153 end
154 return false
155 end
156
157 # Open the file at `path` for reading.
158 #
159 # var f = new FileReader.open("/etc/issue")
160 # assert not f.eof
161 # f.close
162 #
163 # In case of error, `last_error` is set
164 #
165 # f = new FileReader.open("/fail/does not/exist")
166 # assert f.eof
167 # assert f.last_error != null
168 init open(path: String)
169 do
170 self.path = path
171 _file = new NativeFile.io_open_read(path.to_cstring)
172 if _file.as(not null).address_is_null then
173 last_error = new IOError("Cannot open `{path}`: {sys.errno.strerror}")
174 end
175 end
176
177 # Creates a new File stream from a file descriptor
178 #
179 # This is a low-level method.
180 init from_fd(fd: Int) do
181 self.path = ""
182 _file = fd.fd_to_stream(read_only)
183 if _file.as(not null).address_is_null then
184 last_error = new IOError("Error: Converting fd {fd} to stream failed with '{sys.errno.strerror}'")
185 end
186 end
187
188 redef fun poll_in
189 do
190 var res = native_poll_in(fd)
191 if res == -1 then
192 last_error = new IOError(errno.to_s)
193 return false
194 else return res > 0
195 end
196
197 private fun native_poll_in(fd: Int): Int `{
198 #ifndef _WIN32
199 struct pollfd fds = {(int)fd, POLLIN, 0};
200 return poll(&fds, 1, 0);
201 #else
202 return 0;
203 #endif
204 `}
205 end
206
207 # `Stream` that can write to a File
208 class FileWriter
209 super FileStream
210 super Writer
211
212 redef fun write_bytes_from_cstring(cs, len) do
213 if last_error != null then return
214 if not _is_writable then
215 last_error = new IOError("cannot write to non-writable stream")
216 return
217 end
218 write_native(cs, 0, len)
219 end
220
221 redef fun write(s)
222 do
223 if last_error != null then return
224 if not _is_writable then
225 last_error = new IOError("cannot write to non-writable stream")
226 return
227 end
228 s.write_native_to(self)
229 end
230
231 redef fun write_byte(value)
232 do
233 if last_error != null then return
234 if not _is_writable then
235 last_error = new IOError("Cannot write to non-writable stream")
236 return
237 end
238 if _file.as(not null).address_is_null then
239 last_error = new IOError("Writing on a null stream")
240 _is_writable = false
241 return
242 end
243
244 var err = _file.as(not null).write_byte(value)
245 if err != 1 then
246 # Big problem
247 last_error = new IOError("Problem writing a byte: {err}")
248 end
249 end
250
251 redef fun close
252 do
253 super
254 _is_writable = false
255 end
256 redef var is_writable = false
257
258 # Write `len` bytes from `native`.
259 private fun write_native(native: CString, from, len: Int)
260 do
261 if last_error != null then return
262 if not _is_writable then
263 last_error = new IOError("Cannot write to non-writable stream")
264 return
265 end
266 if _file.as(not null).address_is_null then
267 last_error = new IOError("Writing on a null stream")
268 _is_writable = false
269 return
270 end
271 var err = _file.as(not null).io_write(native, from, len)
272 if err != len then
273 # Big problem
274 last_error = new IOError("Problem in writing : {err} {len} \n")
275 end
276 end
277
278 # Open the file at `path` for writing.
279 init open(path: String)
280 do
281 _file = new NativeFile.io_open_write(path.to_cstring)
282 self.path = path
283 _is_writable = true
284 if _file.as(not null).address_is_null then
285 last_error = new IOError("Cannot open `{path}`: {sys.errno.strerror}")
286 is_writable = false
287 end
288 end
289
290 # Creates a new File stream from a file descriptor
291 init from_fd(fd: Int) do
292 self.path = ""
293 _file = fd.fd_to_stream(wipe_write)
294 _is_writable = true
295 if _file.as(not null).address_is_null then
296 last_error = new IOError("Error: Opening stream from file descriptor {fd} failed with '{sys.errno.strerror}'")
297 _is_writable = false
298 end
299 end
300 end
301
302 redef class Int
303 # Creates a file stream from a file descriptor `fd` using the file access `mode`.
304 #
305 # NOTE: The `mode` specified must be compatible with the one used in the file descriptor.
306 private fun fd_to_stream(mode: CString): NativeFile `{
307 return fdopen((int)self, mode);
308 `}
309
310 # Does the file descriptor `self` refer to a terminal?
311 fun isatty: Bool `{ return isatty(self); `}
312 end
313
314 # Constant for read-only file streams
315 private fun read_only: CString do return once "r".to_cstring
316
317 # Constant for write-only file streams
318 #
319 # If a stream is opened on a file with this method,
320 # it will wipe the previous file if any.
321 # Else, it will create the file.
322 private fun wipe_write: CString do return once "w".to_cstring
323
324 ###############################################################################
325
326 # Standard input stream.
327 #
328 # The class of the default value of `sys.stdin`.
329 class Stdin
330 super FileReader
331
332 init do
333 _file = new NativeFile.native_stdin
334 path = "/dev/stdin"
335 end
336 end
337
338 # Standard output stream.
339 #
340 # The class of the default value of `sys.stdout`.
341 class Stdout
342 super FileWriter
343 init do
344 _file = new NativeFile.native_stdout
345 path = "/dev/stdout"
346 _is_writable = true
347 set_buffering_mode(256, sys.buffer_mode_line)
348 end
349 end
350
351 # Standard error stream.
352 #
353 # The class of the default value of `sys.stderr`.
354 class Stderr
355 super FileWriter
356 init do
357 _file = new NativeFile.native_stderr
358 path = "/dev/stderr"
359 _is_writable = true
360 end
361 end
362
363 ###############################################################################
364
365 redef class Writable
366 # Like `write_to` but take care of creating the file
367 fun write_to_file(filepath: String)
368 do
369 var stream = new FileWriter.open(filepath)
370 write_to(stream)
371 stream.close
372 end
373 end
374
375 # Utility class to access file system services.
376 #
377 # Usually created with `Text::to_path`.
378 #
379 # `Path` objects does not necessarily represent existing files in a file system.
380 # They are sate-less objects that efficiently represent path information.
381 # They also provide an easy to use API on file-system services and are used to store their error status (see `last_error`)
382 class Path
383
384 private var path: String
385
386 # Path to this file
387 redef fun to_s do return path
388
389 # Short name of the file at `to_s`
390 #
391 # ~~~
392 # var path = "/tmp/somefile".to_path
393 # assert path.filename == "somefile"
394 # ~~~
395 #
396 # The result does not depend of the file system, thus is cached for efficiency.
397 var filename: String = path.basename is lazy
398
399 # The path simplified by removing useless `.`, removing `//`, and resolving `..`
400 #
401 # ~~~
402 # var path = "somedir/./tmp/../somefile".to_path
403 # assert path.simplified.to_s == "somedir/somefile"
404 # ~~~
405 #
406 # See `String:simplify_path` for details.
407 #
408 # The result does not depend of the file system, thus is cached for efficiency.
409 var simplified: Path is lazy do
410 var res = path.simplify_path.to_path
411 res.simplified = res
412 return res
413 end
414
415 # Return the directory part of the path.
416 #
417 # ~~~
418 # var path = "/foo/bar/baz".to_path
419 # assert path.dir.to_s == "/foo/bar"
420 # assert path.dir.dir.to_s == "/foo"
421 # assert path.dir.dir.dir.to_s == "/"
422 # ~~~
423 #
424 # See `String:dirname` for details.
425 #
426 # The result does not depend of the file system, thus is cached for efficiency.
427 var dir: Path is lazy do
428 return path.dirname.to_path
429 end
430
431 # Last error produced by I/O operations.
432 #
433 # ~~~
434 # var path = "/does/not/exists".to_path
435 # assert path.last_error == null
436 # path.read_all
437 # assert path.last_error != null
438 # ~~~
439 #
440 # Since `Path` objects are stateless, `last_error` is reset on most operations and reflect its status.
441 var last_error: nullable IOError = null is writable
442
443 # Does the file at `path` exists?
444 #
445 # If the file does not exists, `last_error` is set to the information.
446 fun exists: Bool do return stat != null
447
448 # Information on the file at `self` following symbolic links
449 #
450 # Returns `null` if there is no file at `self`.
451 # `last_error` is updated to contains the error information on error, and null on success.
452 #
453 # assert "/etc/".to_path.stat.is_dir
454 # assert "/etc/issue".to_path.stat.is_file
455 # assert "/fail/does not/exist".to_path.stat == null
456 #
457 # ~~~
458 # var p = "/tmp/".to_path
459 # var stat = p.stat
460 # if stat != null then # Does `p` exist?
461 # print "It's size is {stat.size}"
462 # if stat.is_dir then print "It's a directory"
463 # else
464 # print p.last_error.to_s
465 # end
466 # ~~~
467 fun stat: nullable FileStat
468 do
469 var stat = path.to_cstring.file_stat
470 if stat.address_is_null then
471 last_error = new IOError("Cannot open `{path}`: {sys.errno.strerror}")
472 return null
473 end
474 last_error = null
475 return new FileStat(stat)
476 end
477
478 # Information on the file or link at `self`
479 #
480 # Do not follow symbolic links.
481 fun link_stat: nullable FileStat
482 do
483 var stat = path.to_cstring.file_lstat
484 if stat.address_is_null then
485 last_error = new IOError("Cannot open `{path}`: {sys.errno.strerror}")
486 return null
487 end
488 last_error = null
489 return new FileStat(stat)
490 end
491
492 # Delete a file from the file system.
493 #
494 # `last_error` is updated to contains the error information on error, and null on success.
495 fun delete
496 do
497 var res = path.to_cstring.file_delete
498 if not res then
499 last_error = new IOError("Cannot delete `{path}`: {sys.errno.strerror}")
500 else
501 last_error = null
502 end
503 end
504
505 # Copy content of file at `path` to `dest`.
506 #
507 # `last_error` is updated to contains the error information on error, and null on success.
508 fun copy(dest: Path)
509 do
510 last_error = null
511 var input = open_ro
512 var output = dest.open_wo
513
514 var buffer = new CString(4096)
515 while not input.eof do
516 var read = input.read_bytes_to_cstring(buffer, 4096)
517 output.write_bytes_from_cstring(buffer, read)
518 end
519
520 input.close
521 output.close
522 last_error = input.last_error or else output.last_error
523 end
524
525 # Open this file for reading.
526 #
527 # ~~~
528 # var file = "/etc/issue".to_path.open_ro
529 # print file.read_line
530 # file.close
531 # ~~~
532 #
533 # Note that it is the user's responsibility to close the stream.
534 # Therefore, for simple use case, look at `read_all` or `each_line`.
535 #
536 # ENSURE `last_error == result.last_error`
537 fun open_ro: FileReader
538 do
539 var res = new FileReader.open(path)
540 last_error = res.last_error
541 return res
542 end
543
544 # Open this file for writing
545 #
546 # ~~~
547 # var file = "bla.log".to_path.open_wo
548 # file.write "Blabla\n"
549 # file.close
550 # ~~~
551 #
552 # Note that it is the user's responsibility to close the stream.
553 # Therefore, for simple use case, look at `Writable::write_to_file`.
554 #
555 # ENSURE `last_error == result.last_error`
556 fun open_wo: FileWriter
557 do
558 var res = new FileWriter.open(path)
559 last_error = res.last_error
560 return res
561 end
562
563 # Read all the content of the file as a string.
564 #
565 # ~~~
566 # var content = "/etc/issue".to_path.read_all
567 # print content
568 # ~~~
569 #
570 # `last_error` is updated to contains the error information on error, and null on success.
571 # In case of error, the result might be empty or truncated.
572 #
573 # See `Reader::read_all` for details.
574 fun read_all: String do return read_all_bytes.to_s
575
576 # Read all the content on the file as a raw sequence of bytes.
577 #
578 # ~~~
579 # var content = "/etc/issue".to_path.read_all_bytes
580 # print content.to_s
581 # ~~~
582 #
583 # `last_error` is updated to contains the error information on error, and null on success.
584 # In case of error, the result might be empty or truncated.
585 fun read_all_bytes: Bytes
586 do
587 var s = open_ro
588 var res = s.read_all_bytes
589 s.close
590 last_error = s.last_error
591 return res
592 end
593
594 # Read all the lines of the file
595 #
596 # ~~~
597 # var lines = "/etc/passwd".to_path.read_lines
598 #
599 # print "{lines.length} users"
600 #
601 # for l in lines do
602 # var fields = l.split(":")
603 # print "name={fields[0]} uid={fields[2]}"
604 # end
605 # ~~~
606 #
607 # `last_error` is updated to contains the error information on error, and null on success.
608 # In case of error, the result might be empty or truncated.
609 #
610 # See `Reader::read_lines` for details.
611 fun read_lines: Array[String]
612 do
613 var s = open_ro
614 var res = s.read_lines
615 s.close
616 last_error = s.last_error
617 return res
618 end
619
620 # Return an iterator on each line of the file
621 #
622 # ~~~
623 # for l in "/etc/passwd".to_path.each_line do
624 # var fields = l.split(":")
625 # print "name={fields[0]} uid={fields[2]}"
626 # end
627 # ~~~
628 #
629 # Note: the stream is automatically closed at the end of the file (see `LineIterator::close_on_finish`)
630 #
631 # `last_error` is updated to contains the error information on error, and null on success.
632 #
633 # See `Reader::each_line` for details.
634 fun each_line: LineIterator
635 do
636 var s = open_ro
637 var res = s.each_line
638 res.close_on_finish = true
639 last_error = s.last_error
640 return res
641 end
642
643 # Correctly join `self` with `subpath` using the directory separator.
644 #
645 # Using a standard "{self}/{path}" does not work in the following cases:
646 #
647 # * `self` is empty.
648 # * `path` starts with `'/'`.
649 #
650 # This method ensures that the join is valid.
651 #
652 # var hello = "hello".to_path
653 # assert (hello/"world").to_s == "hello/world"
654 # assert ("hel/lo".to_path / "wor/ld").to_s == "hel/lo/wor/ld"
655 # assert ("".to_path / "world").to_s == "world"
656 # assert (hello / "/world").to_s == "/world"
657 # assert ("hello/".to_path / "world").to_s == "hello/world"
658 fun /(subpath: String): Path do return new Path(path / subpath)
659
660 # Lists the files contained within the directory at `path`.
661 #
662 # var files = "/etc".to_path.files
663 # assert files.has("/etc/issue".to_path)
664 #
665 # `last_error` is updated to contains the error information on error, and null on success.
666 # In case of error, the result might be empty or truncated.
667 #
668 # var path = "/etc/issue".to_path
669 # files = path.files
670 # assert files.is_empty
671 # assert path.last_error != null
672 fun files: Array[Path]
673 do
674 last_error = null
675 var res = new Array[Path]
676 var d = new NativeDir.opendir(path.to_cstring)
677 if d.address_is_null then
678 last_error = new IOError("Cannot list directory `{path}`: {sys.errno.strerror}")
679 return res
680 end
681
682 loop
683 var de = d.readdir
684 if de.address_is_null then
685 # readdir cannot fail, so null means end of list
686 break
687 end
688 var name = de.to_s
689 if name == "." or name == ".." then continue
690 res.add self / name
691 end
692 d.closedir
693
694 return res
695 end
696
697 # Is `self` the path to an existing directory ?
698 #
699 # ~~~nit
700 # assert ".".to_path.is_dir
701 # assert not "/etc/issue".to_path.is_dir
702 # assert not "/should/not/exist".to_path.is_dir
703 # ~~~
704 fun is_dir: Bool do
705 var st = stat
706 if st == null then return false
707 return st.is_dir
708 end
709
710 # Recursively delete a directory and all of its content
711 #
712 # Does not go through symbolic links and may get stuck in a cycle if there
713 # is a cycle in the file system.
714 #
715 # `last_error` is updated with the first encountered error, or null on success.
716 # The method does not stop on the first error and tries to remove the most files and directories.
717 #
718 # ~~~
719 # var path = "/does/not/exists/".to_path
720 # path.rmdir
721 # assert path.last_error != null
722 #
723 # path = "/tmp/path/to/create".to_path
724 # path.to_s.mkdir
725 # assert path.exists
726 # path.rmdir
727 # assert path.last_error == null
728 # ~~~
729 fun rmdir
730 do
731 var first_error = null
732 for file in self.files do
733 var stat = file.link_stat
734 if stat == null then
735 if first_error == null then first_error = file.last_error
736 continue
737 end
738 if stat.is_dir then
739 # Recursively rmdir
740 file.rmdir
741 else
742 file.delete
743 end
744 if first_error == null then first_error = file.last_error
745 end
746
747 # Delete the directory itself if things are fine
748 if first_error == null then
749 if not path.to_cstring.rmdir then
750 first_error = new IOError("Cannot remove `{self}`: {sys.errno.strerror}")
751 end
752 end
753 self.last_error = first_error
754 end
755
756 redef fun ==(other) do return other isa Path and simplified.path == other.simplified.path
757 redef fun hash do return simplified.path.hash
758 end
759
760 # Information on a file
761 #
762 # Created by `Path::stat` and `Path::link_stat`.
763 #
764 # The information within this class is gathered when the instance is initialized
765 # it will not be updated if the targeted file is modified.
766 class FileStat
767 super Finalizable
768
769 # TODO private init
770
771 # The low-level status of a file
772 #
773 # See: POSIX stat(2)
774 private var stat: NativeFileStat
775
776 private var finalized = false
777
778 redef fun finalize
779 do
780 if not finalized then
781 stat.free
782 finalized = true
783 end
784 end
785
786 # Returns the last access time in seconds since Epoch
787 fun last_access_time: Int
788 do
789 assert not finalized
790 return stat.atime
791 end
792
793 # Returns the last access time
794 #
795 # alias for `last_access_time`
796 fun atime: Int do return last_access_time
797
798 # Returns the last modification time in seconds since Epoch
799 fun last_modification_time: Int
800 do
801 assert not finalized
802 return stat.mtime
803 end
804
805 # Returns the last modification time
806 #
807 # alias for `last_modification_time`
808 fun mtime: Int do return last_modification_time
809
810
811 # Size of the file at `path`
812 fun size: Int
813 do
814 assert not finalized
815 return stat.size
816 end
817
818 # Is self a regular file and not a device file, pipe, socket, etc.?
819 fun is_file: Bool
820 do
821 assert not finalized
822 return stat.is_reg
823 end
824
825 # Alias for `is_file`
826 fun is_reg: Bool do return is_file
827
828 # Is this a directory?
829 fun is_dir: Bool
830 do
831 assert not finalized
832 return stat.is_dir
833 end
834
835 # Is this a symbolic link?
836 fun is_link: Bool
837 do
838 assert not finalized
839 return stat.is_lnk
840 end
841
842 # FIXME Make the following POSIX only? or implement in some other way on Windows
843
844 # Returns the last status change time in seconds since Epoch
845 fun last_status_change_time: Int
846 do
847 assert not finalized
848 return stat.ctime
849 end
850
851 # Returns the last status change time
852 #
853 # alias for `last_status_change_time`
854 fun ctime: Int do return last_status_change_time
855
856 # Returns the permission bits of file
857 fun mode: Int
858 do
859 assert not finalized
860 return stat.mode
861 end
862
863 # Is this a character device?
864 fun is_chr: Bool
865 do
866 assert not finalized
867 return stat.is_chr
868 end
869
870 # Is this a block device?
871 fun is_blk: Bool
872 do
873 assert not finalized
874 return stat.is_blk
875 end
876
877 # Is this a FIFO pipe?
878 fun is_fifo: Bool
879 do
880 assert not finalized
881 return stat.is_fifo
882 end
883
884 # Is this a UNIX socket
885 fun is_sock: Bool
886 do
887 assert not finalized
888 return stat.is_sock
889 end
890 end
891
892 redef class Text
893 # Access file system related services on the path at `self`
894 fun to_path: Path do return new Path(to_s)
895
896 private fun write_native_to(s: FileWriter)
897 do
898 for i in substrings do s.write_native(i.to_cstring, 0, i.byte_length)
899 end
900
901 # return true if a file with this names exists
902 fun file_exists: Bool do return to_cstring.file_exists
903
904 # The status of a file. see POSIX stat(2).
905 fun file_stat: nullable FileStat
906 do
907 var stat = to_cstring.file_stat
908 if stat.address_is_null then return null
909 return new FileStat(stat)
910 end
911
912 # The status of a file or of a symlink. see POSIX lstat(2).
913 fun file_lstat: nullable FileStat
914 do
915 var stat = to_cstring.file_lstat
916 if stat.address_is_null then return null
917 return new FileStat(stat)
918 end
919
920 # Remove a file, return true if success
921 fun file_delete: Bool do return to_cstring.file_delete
922
923 # Copy content of file at `self` to `dest`
924 fun file_copy_to(dest: String) do to_path.copy(dest.to_path)
925
926 # Remove the trailing `extension`.
927 #
928 # `extension` usually starts with a dot but could be anything.
929 #
930 # assert "file.txt".strip_extension(".txt") == "file"
931 # assert "file.txt".strip_extension("le.txt") == "fi"
932 # assert "file.txt".strip_extension("xt") == "file.t"
933 #
934 # If `extension == null`, the rightmost extension is stripped, including the last dot.
935 #
936 # assert "file.txt".strip_extension == "file"
937 #
938 # If `extension` is not present, `self` is returned unmodified.
939 #
940 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
941 fun strip_extension(extension: nullable String): String
942 do
943 if extension == null then
944 extension = file_extension
945 if extension == null then
946 return self.to_s
947 else extension = ".{extension}"
948 end
949
950 if has_suffix(extension) then
951 return substring(0, length - extension.length).to_s
952 end
953 return self.to_s
954 end
955
956 # Extract the basename of a path and strip the `extension`
957 #
958 # The extension is stripped only if `extension != null`.
959 #
960 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
961 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
962 # assert "path/to/a_file.ext".basename == "a_file.ext"
963 # assert "path/to".basename(".ext") == "to"
964 # assert "path/to/".basename(".ext") == "to"
965 # assert "path/to".basename == "to"
966 # assert "path".basename == "path"
967 # assert "/path".basename == "path"
968 # assert "/".basename == "/"
969 # assert "".basename == ""
970 #
971 # On Windows, '\' are replaced by '/':
972 #
973 # ~~~nitish
974 # assert "C:\\path\\to\\a_file.ext".basename(".ext") == "a_file"
975 # assert "C:\\".basename == "C:"
976 # ~~~
977 fun basename(extension: nullable String): String
978 do
979 var n = self
980 if is_windows then n = n.replace("\\", "/")
981
982 var l = length - 1 # Index of the last char
983 while l > 0 and self.chars[l] == '/' do l -= 1 # remove all trailing `/`
984 if l == 0 then return "/"
985 var pos = chars.last_index_of_from('/', l)
986 if pos >= 0 then
987 n = substring(pos+1, l-pos)
988 end
989
990 if extension != null then
991 return n.strip_extension(extension)
992 else return n.to_s
993 end
994
995 # Extract the dirname of a path
996 #
997 # assert "/path/to/a_file.ext".dirname == "/path/to"
998 # assert "path/to/a_file.ext".dirname == "path/to"
999 # assert "path/to".dirname == "path"
1000 # assert "path/to/".dirname == "path"
1001 # assert "path".dirname == "."
1002 # assert "/path".dirname == "/"
1003 # assert "/".dirname == "/"
1004 # assert "".dirname == "."
1005 #
1006 # On Windows, '\' are replaced by '/':
1007 #
1008 # ~~~nitish
1009 # assert "C:\\path\\to\\a_file.ext".dirname == "C:/path/to"
1010 # assert "C:\\file".dirname == "C:"
1011 # ~~~
1012 fun dirname: String
1013 do
1014 var s = self
1015 if is_windows then s = s.replace("\\", "/")
1016
1017 var l = length - 1 # Index of the last char
1018 while l > 0 and s.chars[l] == '/' do l -= 1 # remove all trailing `/`
1019 var pos = s.chars.last_index_of_from('/', l)
1020 if pos > 0 then
1021 return s.substring(0, pos).to_s
1022 else if pos == 0 then
1023 return "/"
1024 else
1025 return "."
1026 end
1027 end
1028
1029 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
1030 #
1031 # Require: `file_exists`
1032 fun realpath: String do
1033 var cs = to_cstring.file_realpath
1034 assert file_exists
1035 var res = cs.to_s
1036 cs.free
1037 return res
1038 end
1039
1040 # Simplify a file path by remove useless `.`, removing `//`, and resolving `..`
1041 #
1042 # * `..` are not resolved if they start the path
1043 # * starting `.` is simplified unless the path is empty
1044 # * starting `/` is not removed
1045 # * trailing `/` is removed
1046 #
1047 # Note that the method only work on the string:
1048 #
1049 # * no I/O access is performed
1050 # * the validity of the path is not checked
1051 #
1052 # ~~~
1053 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
1054 # assert "../dir/file".simplify_path == "../dir/file"
1055 # assert "dir/../../".simplify_path == ".."
1056 # assert "dir/..".simplify_path == "."
1057 # assert "//absolute//path/".simplify_path == "/absolute/path"
1058 # assert "//absolute//../".simplify_path == "/"
1059 # assert "/".simplify_path == "/"
1060 # assert "../".simplify_path == ".."
1061 # assert "./".simplify_path == "."
1062 # assert "././././././".simplify_path == "."
1063 # assert "./../dir".simplify_path == "../dir"
1064 # assert "./dir".simplify_path == "dir"
1065 # ~~~
1066 #
1067 # On Windows, '\' are replaced by '/':
1068 #
1069 # ~~~nitish
1070 # assert "C:\\some\\.\\complex\\../../path/to/a_file.ext".simplify_path == "C:/path/to/a_file.ext"
1071 # assert "C:\\".simplify_path == "C:"
1072 # ~~~
1073 fun simplify_path: String
1074 do
1075 var s = self
1076 if is_windows then s = s.replace("\\", "/")
1077 var a = s.split_with("/")
1078 var a2 = new Array[String]
1079 for x in a do
1080 if x == "." and not a2.is_empty then continue # skip `././`
1081 if x == "" and not a2.is_empty then continue # skip `//`
1082 if x == ".." and not a2.is_empty and a2.last != ".." then
1083 if a2.last == "." then # do not skip `./../`
1084 a2.pop # reduce `./../` in `../`
1085 else # reduce `dir/../` in `/`
1086 a2.pop
1087 continue
1088 end
1089 else if not a2.is_empty and a2.last == "." then
1090 a2.pop # reduce `./dir` in `dir`
1091 end
1092 a2.push(x)
1093 end
1094 if a2.is_empty then return "."
1095 if a2.length == 1 and a2.first == "" then return "/"
1096 return a2.join("/")
1097 end
1098
1099 # Correctly join two path using the directory separator.
1100 #
1101 # Using a standard "{self}/{path}" does not work in the following cases:
1102 #
1103 # * `self` is empty.
1104 # * `path` starts with `'/'`.
1105 #
1106 # This method ensures that the join is valid.
1107 #
1108 # assert "hello".join_path("world") == "hello/world"
1109 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
1110 # assert "".join_path("world") == "world"
1111 # assert "hello".join_path("/world") == "/world"
1112 # assert "hello/".join_path("world") == "hello/world"
1113 # assert "hello/".join_path("/world") == "/world"
1114 #
1115 # Note: You may want to use `simplify_path` on the result.
1116 #
1117 # Note: This method works only with POSIX paths.
1118 fun join_path(path: Text): String
1119 do
1120 if path.is_empty then return self.to_s
1121 if self.is_empty then return path.to_s
1122 if path.chars[0] == '/' then return path.to_s
1123 if self.last == '/' then return "{self}{path}"
1124 return "{self}/{path}"
1125 end
1126
1127 # Convert the path (`self`) to a program name.
1128 #
1129 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
1130 # used as a program name. In order to do that, prepend `./` if needed.
1131 #
1132 # assert "foo".to_program_name == "./foo"
1133 # assert "/foo".to_program_name == "/foo"
1134 # assert "".to_program_name == "./" # At least, your shell will detect the error.
1135 fun to_program_name: String do
1136 if self.has_prefix("/") then
1137 return self.to_s
1138 else
1139 return "./{self}"
1140 end
1141 end
1142
1143 # Alias for `join_path`
1144 #
1145 # assert "hello" / "world" == "hello/world"
1146 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
1147 # assert "" / "world" == "world"
1148 # assert "/hello" / "/world" == "/world"
1149 #
1150 # This operator is quite useful for chaining changes of path.
1151 # The next one being relative to the previous one.
1152 #
1153 # var a = "foo"
1154 # var b = "/bar"
1155 # var c = "baz/foobar"
1156 # assert a/b/c == "/bar/baz/foobar"
1157 fun /(path: Text): String do return join_path(path)
1158
1159 # Returns the relative path needed to go from `self` to `dest`.
1160 #
1161 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
1162 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
1163 #
1164 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
1165 #
1166 # In some cases, the result is still independent of the current directory:
1167 #
1168 # assert "foo/bar".relpath("..") == "../../.."
1169 #
1170 # In other cases, parts of the current directory may be exhibited:
1171 #
1172 # var p = "../foo/bar".relpath("baz")
1173 # var c = getcwd.basename
1174 # assert p == "../../{c}/baz"
1175 #
1176 # For path resolution independent of the current directory (eg. for paths in URL),
1177 # or to use an other starting directory than the current directory,
1178 # just force absolute paths:
1179 #
1180 # var start = "/a/b/c/d"
1181 # var p2 = (start/"../foo/bar").relpath(start/"baz")
1182 # assert p2 == "../../d/baz"
1183 #
1184 #
1185 # Neither `self` or `dest` has to be real paths or to exist in directories since
1186 # the resolution is only done with string manipulations and without any access to
1187 # the underlying file system.
1188 #
1189 # If `self` and `dest` are the same directory, the empty string is returned:
1190 #
1191 # assert "foo".relpath("foo") == ""
1192 # assert "foo/../bar".relpath("bar") == ""
1193 #
1194 # The empty string and "." designate both the current directory:
1195 #
1196 # assert "".relpath("foo/bar") == "foo/bar"
1197 # assert ".".relpath("foo/bar") == "foo/bar"
1198 # assert "foo/bar".relpath("") == "../.."
1199 # assert "/" + "/".relpath(".") == getcwd
1200 fun relpath(dest: String): String
1201 do
1202 # TODO windows support
1203 var cwd = getcwd
1204 var from = (cwd/self).simplify_path.split("/")
1205 if from.last.is_empty then from.pop # case for the root directory
1206 var to = (cwd/dest).simplify_path.split("/")
1207 if to.last.is_empty then to.pop # case for the root directory
1208
1209 # Remove common prefixes
1210 while not from.is_empty and not to.is_empty and from.first == to.first do
1211 from.shift
1212 to.shift
1213 end
1214
1215 # Result is going up in `from` with ".." then going down following `to`
1216 var from_len = from.length
1217 if from_len == 0 then return to.join("/")
1218 var up = "../"*(from_len-1) + ".."
1219 if to.is_empty then return up
1220 var res = up + "/" + to.join("/")
1221 return res
1222 end
1223
1224 # Create a directory (and all intermediate directories if needed)
1225 #
1226 # The optional `mode` parameter specifies the permissions of the directory,
1227 # the default value is `0o777`.
1228 #
1229 # Return an error object in case of error.
1230 #
1231 # assert "/etc/".mkdir != null
1232 fun mkdir(mode: nullable Int): nullable Error
1233 do
1234 mode = mode or else 0o777
1235 var s = self
1236 if is_windows then s = s.replace("\\", "/")
1237
1238 var dirs = s.split_with("/")
1239 var path = new FlatBuffer
1240 if dirs.is_empty then return null
1241 if dirs[0].is_empty then
1242 # it was a starting /
1243 path.add('/')
1244 end
1245 var error: nullable Error = null
1246 for i in [0 .. dirs.length - 1[ do
1247 var d = dirs[i]
1248 if d.is_empty then continue
1249 path.append(d)
1250 path.add('/')
1251 if path.file_exists then continue
1252 var res = path.to_cstring.file_mkdir(mode)
1253 if not res and error == null then
1254 error = new IOError("Cannot create directory `{path}`: {sys.errno.strerror}")
1255 end
1256 end
1257 var res = s.to_cstring.file_mkdir(mode)
1258 if not res and error == null then
1259 error = new IOError("Cannot create directory `{path}`: {sys.errno.strerror}")
1260 end
1261 return error
1262 end
1263
1264 # Delete a directory and all of its content, return `true` on success
1265 #
1266 # Does not go through symbolic links and may get stuck in a cycle if there
1267 # is a cycle in the filesystem.
1268 #
1269 # Return an error object in case of error.
1270 #
1271 # assert "/fail/does not/exist".rmdir != null
1272 fun rmdir: nullable Error
1273 do
1274 var p = to_path
1275 p.rmdir
1276 return p.last_error
1277 end
1278
1279 # Change the current working directory
1280 #
1281 # "/etc".chdir
1282 # assert getcwd == "/etc"
1283 # "..".chdir
1284 # assert getcwd == "/"
1285 #
1286 # Return an error object in case of error.
1287 #
1288 # assert "/etc".chdir == null
1289 # assert "/fail/does no/exist".chdir != null
1290 # assert getcwd == "/etc" # unchanger
1291 fun chdir: nullable Error
1292 do
1293 var res = to_cstring.file_chdir
1294 if res then return null
1295 var error = new IOError("Cannot change directory to `{self}`: {sys.errno.strerror}")
1296 return error
1297 end
1298
1299 # Return right-most extension (without the dot)
1300 #
1301 # Only the last extension is returned.
1302 # There is no special case for combined extensions.
1303 #
1304 # assert "file.txt".file_extension == "txt"
1305 # assert "file.tar.gz".file_extension == "gz"
1306 #
1307 # For file without extension, `null` is returned.
1308 # Hoever, for trailing dot, `""` is returned.
1309 #
1310 # assert "file".file_extension == null
1311 # assert "file.".file_extension == ""
1312 #
1313 # The starting dot of hidden files is never considered.
1314 #
1315 # assert ".file.txt".file_extension == "txt"
1316 # assert ".file".file_extension == null
1317 fun file_extension: nullable String
1318 do
1319 var last_slash = chars.last_index_of('.')
1320 if last_slash > 0 then
1321 return substring( last_slash+1, length ).to_s
1322 else
1323 return null
1324 end
1325 end
1326
1327 # Returns entries contained within the directory represented by self.
1328 #
1329 # var files = "/etc".files
1330 # assert files.has("issue")
1331 #
1332 # Returns an empty array in case of error
1333 #
1334 # files = "/etc/issue".files
1335 # assert files.is_empty
1336 #
1337 # TODO find a better way to handle errors and to give them back to the user.
1338 fun files: Array[String]
1339 do
1340 var res = new Array[String]
1341 var d = new NativeDir.opendir(to_cstring)
1342 if d.address_is_null then return res
1343
1344 loop
1345 var de = d.readdir
1346 if de.address_is_null then break
1347 var name = de.to_s
1348 if name == "." or name == ".." then continue
1349 res.add name
1350 end
1351 d.closedir
1352
1353 return res
1354 end
1355 end
1356
1357 redef class FlatString
1358 redef fun write_native_to(s)
1359 do
1360 s.write_native(items, first_byte, byte_length)
1361 end
1362
1363 redef fun file_extension do
1364 var its = _items
1365 var p = last_byte
1366 var c = its[p]
1367 var st = _first_byte
1368 while p >= st and c != u'.' do
1369 p -= 1
1370 c = its[p]
1371 end
1372 if p <= st then return null
1373 var ls = last_byte
1374 return new FlatString.with_infos(its, ls - p, p + 1)
1375 end
1376
1377 redef fun basename(extension) do
1378 var s = self
1379 if is_windows then s = s.replace("\\", "/").as(FlatString)
1380
1381 var bname
1382 var l = s.last_byte
1383 var its = s._items
1384 var min = s._first_byte
1385 var sl = u'/'
1386 while l > min and its[l] == sl do l -= 1
1387 if l == min then return "/"
1388 var ns = l
1389 while ns >= min and its[ns] != sl do ns -= 1
1390 bname = new FlatString.with_infos(its, l - ns, ns + 1)
1391
1392 return if extension != null then bname.strip_extension(extension) else bname
1393 end
1394 end
1395
1396 redef class CString
1397 private fun file_exists: Bool `{
1398 #ifdef _WIN32
1399 DWORD attribs = GetFileAttributesA(self);
1400 return attribs != INVALID_FILE_ATTRIBUTES;
1401 #else
1402 FILE *hdl = fopen(self,"r");
1403 if(hdl != NULL){
1404 fclose(hdl);
1405 }
1406 return hdl != NULL;
1407 #endif
1408 `}
1409
1410 private fun file_stat: NativeFileStat `{
1411 struct stat buff;
1412 if(stat(self, &buff) != -1) {
1413 struct stat* stat_element;
1414 stat_element = malloc(sizeof(struct stat));
1415 return memcpy(stat_element, &buff, sizeof(struct stat));
1416 }
1417 return 0;
1418 `}
1419
1420 private fun file_lstat: NativeFileStat `{
1421 #ifdef _WIN32
1422 // FIXME use a higher level abstraction to support WIN32
1423 return NULL;
1424 #else
1425 struct stat* stat_element;
1426 int res;
1427 stat_element = malloc(sizeof(struct stat));
1428 res = lstat(self, stat_element);
1429 if (res == -1) return NULL;
1430 return stat_element;
1431 #endif
1432 `}
1433
1434 private fun file_mkdir(mode: Int): Bool `{
1435 #ifdef _WIN32
1436 return !mkdir(self);
1437 #else
1438 return !mkdir(self, mode);
1439 #endif
1440 `}
1441
1442 private fun rmdir: Bool `{ return !rmdir(self); `}
1443
1444 private fun file_delete: Bool `{
1445 return remove(self) == 0;
1446 `}
1447
1448 private fun file_chdir: Bool `{ return !chdir(self); `}
1449
1450 private fun file_realpath: CString `{
1451 #ifdef _WIN32
1452 DWORD len = GetFullPathName(self, 0, NULL, NULL);
1453 char *buf = malloc(len+1); // FIXME don't leak memory
1454 len = GetFullPathName(self, len+1, buf, NULL);
1455 return buf;
1456 #else
1457 return realpath(self, NULL);
1458 #endif
1459 `}
1460 end
1461
1462 # This class is system dependent ... must reify the vfs
1463 private extern class NativeFileStat `{ struct stat * `}
1464
1465 # Returns the permission bits of file
1466 fun mode: Int `{ return self->st_mode; `}
1467
1468 # Returns the last access time
1469 fun atime: Int `{ return self->st_atime; `}
1470
1471 # Returns the last status change time
1472 fun ctime: Int `{ return self->st_ctime; `}
1473
1474 # Returns the last modification time
1475 fun mtime: Int `{ return self->st_mtime; `}
1476
1477 # Returns the size
1478 fun size: Int `{ return self->st_size; `}
1479
1480 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
1481 fun is_reg: Bool `{ return S_ISREG(self->st_mode); `}
1482
1483 # Returns true if it is a directory
1484 fun is_dir: Bool `{ return S_ISDIR(self->st_mode); `}
1485
1486 # Returns true if it is a character device
1487 fun is_chr: Bool `{ return S_ISCHR(self->st_mode); `}
1488
1489 # Returns true if it is a block device
1490 fun is_blk: Bool `{ return S_ISBLK(self->st_mode); `}
1491
1492 # Returns true if the type is fifo
1493 fun is_fifo: Bool `{ return S_ISFIFO(self->st_mode); `}
1494
1495 # Returns true if the type is a link
1496 fun is_lnk: Bool `{
1497 #ifdef _WIN32
1498 return 0;
1499 #else
1500 return S_ISLNK(self->st_mode);
1501 #endif
1502 `}
1503
1504 # Returns true if the type is a socket
1505 fun is_sock: Bool `{
1506 #ifdef _WIN32
1507 return 0;
1508 #else
1509 return S_ISSOCK(self->st_mode);
1510 #endif
1511 `}
1512 end
1513
1514 # Instance of this class are standard FILE * pointers
1515 private extern class NativeFile `{ FILE* `}
1516 fun io_read(buf: CString, len: Int): Int `{
1517 return fread(buf, 1, len, self);
1518 `}
1519
1520 fun io_write(buf: CString, from, len: Int): Int `{
1521 size_t res = fwrite(buf+from, 1, len, self);
1522 #ifdef _WIN32
1523 // Force flushing buffer because end of line does not trigger a flush
1524 fflush(self);
1525 #endif
1526 return (long)res;
1527 `}
1528
1529 fun write_byte(value: Int): Int `{
1530 unsigned char b = (unsigned char)value;
1531 return fwrite(&b, 1, 1, self);
1532 `}
1533
1534 fun io_close: Int `{ return fclose(self); `}
1535
1536 fun file_stat: NativeFileStat `{
1537 struct stat buff;
1538 if(fstat(fileno(self), &buff) != -1) {
1539 struct stat* stat_element;
1540 stat_element = malloc(sizeof(struct stat));
1541 return memcpy(stat_element, &buff, sizeof(struct stat));
1542 }
1543 return 0;
1544 `}
1545
1546 fun ferror: Bool `{ return ferror(self); `}
1547
1548 fun feof: Bool `{ return feof(self); `}
1549
1550 fun fileno: Int `{ return fileno(self); `}
1551
1552 # Flushes the buffer, forcing the write operation
1553 fun flush: Int `{ return fflush(self); `}
1554
1555 # Used to specify how the buffering will be handled for the current stream.
1556 fun set_buffering_type(buf_length, mode: Int): Int `{
1557 return setvbuf(self, NULL, (int)mode, buf_length);
1558 `}
1559
1560 new io_open_read(path: CString) `{ return fopen(path, "r"); `}
1561
1562 new io_open_write(path: CString) `{ return fopen(path, "w"); `}
1563
1564 new native_stdin `{ return stdin; `}
1565
1566 new native_stdout `{ return stdout; `}
1567
1568 new native_stderr `{ return stderr; `}
1569 end
1570
1571 # Standard `DIR*` pointer
1572 private extern class NativeDir `{ DIR* `}
1573
1574 # Open a directory
1575 new opendir(path: CString) `{ return opendir(path); `}
1576
1577 # Close a directory
1578 fun closedir `{ closedir(self); `}
1579
1580 # Read the next directory entry
1581 fun readdir: CString `{
1582 struct dirent *de;
1583 de = readdir(self);
1584 if (!de) return NULL;
1585 return de->d_name;
1586 `}
1587 end
1588
1589 redef class Sys
1590
1591 # Standard input
1592 var stdin: PollableReader = new Stdin is protected writable, lazy
1593
1594 # Standard output
1595 var stdout: Writer = new Stdout is protected writable, lazy
1596
1597 # Standard output for errors
1598 var stderr: Writer = new Stderr is protected writable, lazy
1599
1600 # Enumeration for buffer mode full (flushes when buffer is full)
1601 fun buffer_mode_full: Int `{ return _IOFBF; `}
1602
1603 # Enumeration for buffer mode line (flushes when a `\n` is encountered)
1604 fun buffer_mode_line: Int `{ return _IONBF; `}
1605
1606 # Enumeration for buffer mode none (flushes ASAP when something is written)
1607 fun buffer_mode_none: Int `{ return _IOLBF; `}
1608
1609 # returns first available stream to read or write to
1610 # return null on interruption (possibly a signal)
1611 protected fun poll( streams : Sequence[FileStream] ) : nullable FileStream
1612 do
1613 var in_fds = new Array[Int]
1614 var out_fds = new Array[Int]
1615 var fd_to_stream = new HashMap[Int,FileStream]
1616 for s in streams do
1617 var fd = s.fd
1618 if s isa FileReader then in_fds.add( fd )
1619 if s isa FileWriter then out_fds.add( fd )
1620
1621 fd_to_stream[fd] = s
1622 end
1623
1624 var polled_fd = intern_poll( in_fds, out_fds )
1625
1626 if polled_fd == null then
1627 return null
1628 else
1629 return fd_to_stream[polled_fd]
1630 end
1631 end
1632
1633 private fun intern_poll(in_fds: Array[Int], out_fds: Array[Int]): nullable Int
1634 import Array[Int].length, Array[Int].[], Int.as(nullable Int) `{
1635 #ifndef _WIN32
1636 // FIXME use a higher level abstraction to support WIN32
1637
1638 int in_len, out_len, total_len;
1639 struct pollfd *c_fds;
1640 int i;
1641 int first_polled_fd = -1;
1642 int result;
1643
1644 in_len = (int)Array_of_Int_length( in_fds );
1645 out_len = (int)Array_of_Int_length( out_fds );
1646 total_len = in_len + out_len;
1647 c_fds = malloc( sizeof(struct pollfd) * total_len );
1648
1649 /* input streams */
1650 for ( i=0; i<in_len; i ++ ) {
1651 int fd = (int)Array_of_Int__index( in_fds, i );
1652
1653 c_fds[i].fd = fd;
1654 c_fds[i].events = POLLIN;
1655 }
1656
1657 /* output streams */
1658 for ( i=0; i<out_len; i ++ ) {
1659 int fd = (int)Array_of_Int__index( out_fds, i );
1660
1661 c_fds[i].fd = fd;
1662 c_fds[i].events = POLLOUT;
1663 }
1664
1665 /* poll all fds, unlimited timeout */
1666 result = poll( c_fds, total_len, -1 );
1667
1668 if ( result > 0 ) {
1669 /* analyse results */
1670 for ( i=0; i<total_len; i++ )
1671 if ( c_fds[i].revents & c_fds[i].events || /* awaited event */
1672 c_fds[i].revents & POLLHUP ) /* closed */
1673 {
1674 first_polled_fd = c_fds[i].fd;
1675 break;
1676 }
1677
1678 return Int_as_nullable( first_polled_fd );
1679 }
1680 else if ( result < 0 )
1681 fprintf( stderr, "Error in Stream:poll: %s\n", strerror( errno ) );
1682 #endif
1683
1684 return null_Int();
1685 `}
1686
1687 end
1688
1689 # Print `objects` on the standard output (`stdout`).
1690 fun printn(objects: Object...)
1691 do
1692 sys.stdout.write(objects.plain_to_s)
1693 end
1694
1695 # Print an `object` on the standard output (`stdout`) and add a newline.
1696 fun print(object: Object)
1697 do
1698 sys.stdout.write(object.to_s)
1699 sys.stdout.write("\n")
1700 end
1701
1702 # Print `object` on the error output (`stderr` or a log system)
1703 fun print_error(object: Object)
1704 do
1705 sys.stderr.write object.to_s
1706 sys.stderr.write "\n"
1707 end
1708
1709 # Read a character from the standard input (`stdin`).
1710 fun getc: Char
1711 do
1712 var c = sys.stdin.read_char
1713 if c == null then return '\1'
1714 return c
1715 end
1716
1717 # Read a line from the standard input (`stdin`).
1718 fun gets: String
1719 do
1720 return sys.stdin.read_line
1721 end
1722
1723 # Return the working (current) directory
1724 fun getcwd: String do return native_getcwd.to_s
1725
1726 private fun native_getcwd: CString `{ return getcwd(NULL, 0); `}