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