core: move more servies to Text (receiver and args only)
[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(s) 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(s.items, 0, s.length)
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 while not input.eof do
514 var buffer = input.read_bytes(1024)
515 output.write_bytes buffer
516 end
517
518 input.close
519 output.close
520 last_error = input.last_error or else output.last_error
521 end
522
523 # Open this file for reading.
524 #
525 # ~~~
526 # var file = "/etc/issue".to_path.open_ro
527 # print file.read_line
528 # file.close
529 # ~~~
530 #
531 # Note that it is the user's responsibility to close the stream.
532 # Therefore, for simple use case, look at `read_all` or `each_line`.
533 #
534 # ENSURE `last_error == result.last_error`
535 fun open_ro: FileReader
536 do
537 var res = new FileReader.open(path)
538 last_error = res.last_error
539 return res
540 end
541
542 # Open this file for writing
543 #
544 # ~~~
545 # var file = "bla.log".to_path.open_wo
546 # file.write "Blabla\n"
547 # file.close
548 # ~~~
549 #
550 # Note that it is the user's responsibility to close the stream.
551 # Therefore, for simple use case, look at `Writable::write_to_file`.
552 #
553 # ENSURE `last_error == result.last_error`
554 fun open_wo: FileWriter
555 do
556 var res = new FileWriter.open(path)
557 last_error = res.last_error
558 return res
559 end
560
561 # Read all the content of the file as a string.
562 #
563 # ~~~
564 # var content = "/etc/issue".to_path.read_all
565 # print content
566 # ~~~
567 #
568 # `last_error` is updated to contains the error information on error, and null on success.
569 # In case of error, the result might be empty or truncated.
570 #
571 # See `Reader::read_all` for details.
572 fun read_all: String do return read_all_bytes.to_s
573
574 # Read all the content on the file as a raw sequence of bytes.
575 #
576 # ~~~
577 # var content = "/etc/issue".to_path.read_all_bytes
578 # print content.to_s
579 # ~~~
580 #
581 # `last_error` is updated to contains the error information on error, and null on success.
582 # In case of error, the result might be empty or truncated.
583 fun read_all_bytes: Bytes
584 do
585 var s = open_ro
586 var res = s.read_all_bytes
587 s.close
588 last_error = s.last_error
589 return res
590 end
591
592 # Read all the lines of the file
593 #
594 # ~~~
595 # var lines = "/etc/passwd".to_path.read_lines
596 #
597 # print "{lines.length} users"
598 #
599 # for l in lines do
600 # var fields = l.split(":")
601 # print "name={fields[0]} uid={fields[2]}"
602 # end
603 # ~~~
604 #
605 # `last_error` is updated to contains the error information on error, and null on success.
606 # In case of error, the result might be empty or truncated.
607 #
608 # See `Reader::read_lines` for details.
609 fun read_lines: Array[String]
610 do
611 var s = open_ro
612 var res = s.read_lines
613 s.close
614 last_error = s.last_error
615 return res
616 end
617
618 # Return an iterator on each line of the file
619 #
620 # ~~~
621 # for l in "/etc/passwd".to_path.each_line do
622 # var fields = l.split(":")
623 # print "name={fields[0]} uid={fields[2]}"
624 # end
625 # ~~~
626 #
627 # Note: the stream is automatically closed at the end of the file (see `LineIterator::close_on_finish`)
628 #
629 # `last_error` is updated to contains the error information on error, and null on success.
630 #
631 # See `Reader::each_line` for details.
632 fun each_line: LineIterator
633 do
634 var s = open_ro
635 var res = s.each_line
636 res.close_on_finish = true
637 last_error = s.last_error
638 return res
639 end
640
641 # Correctly join `self` with `subpath` using the directory separator.
642 #
643 # Using a standard "{self}/{path}" does not work in the following cases:
644 #
645 # * `self` is empty.
646 # * `path` starts with `'/'`.
647 #
648 # This method ensures that the join is valid.
649 #
650 # var hello = "hello".to_path
651 # assert (hello/"world").to_s == "hello/world"
652 # assert ("hel/lo".to_path / "wor/ld").to_s == "hel/lo/wor/ld"
653 # assert ("".to_path / "world").to_s == "world"
654 # assert (hello / "/world").to_s == "/world"
655 # assert ("hello/".to_path / "world").to_s == "hello/world"
656 fun /(subpath: String): Path do return new Path(path / subpath)
657
658 # Lists the files contained within the directory at `path`.
659 #
660 # var files = "/etc".to_path.files
661 # assert files.has("/etc/issue".to_path)
662 #
663 # `last_error` is updated to contains the error information on error, and null on success.
664 # In case of error, the result might be empty or truncated.
665 #
666 # var path = "/etc/issue".to_path
667 # files = path.files
668 # assert files.is_empty
669 # assert path.last_error != null
670 fun files: Array[Path]
671 do
672 last_error = null
673 var res = new Array[Path]
674 var d = new NativeDir.opendir(path.to_cstring)
675 if d.address_is_null then
676 last_error = new IOError("Cannot list directory `{path}`: {sys.errno.strerror}")
677 return res
678 end
679
680 loop
681 var de = d.readdir
682 if de.address_is_null then
683 # readdir cannot fail, so null means end of list
684 break
685 end
686 var name = de.to_s
687 if name == "." or name == ".." then continue
688 res.add self / name
689 end
690 d.closedir
691
692 return res
693 end
694
695 # Is `self` the path to an existing directory ?
696 #
697 # ~~~nit
698 # assert ".".to_path.is_dir
699 # assert not "/etc/issue".to_path.is_dir
700 # assert not "/should/not/exist".to_path.is_dir
701 # ~~~
702 fun is_dir: Bool do
703 var st = stat
704 if st == null then return false
705 return st.is_dir
706 end
707
708 # Recursively delete a directory and all of its content
709 #
710 # Does not go through symbolic links and may get stuck in a cycle if there
711 # is a cycle in the file system.
712 #
713 # `last_error` is updated with the first encountered error, or null on success.
714 # The method does not stop on the first error and tries to remove the most files and directories.
715 #
716 # ~~~
717 # var path = "/does/not/exists/".to_path
718 # path.rmdir
719 # assert path.last_error != null
720 #
721 # path = "/tmp/path/to/create".to_path
722 # path.to_s.mkdir
723 # assert path.exists
724 # path.rmdir
725 # assert path.last_error == null
726 # ~~~
727 fun rmdir
728 do
729 var first_error = null
730 for file in self.files do
731 var stat = file.link_stat
732 if stat == null then
733 if first_error == null then first_error = file.last_error
734 continue
735 end
736 if stat.is_dir then
737 # Recursively rmdir
738 file.rmdir
739 else
740 file.delete
741 end
742 if first_error == null then first_error = file.last_error
743 end
744
745 # Delete the directory itself if things are fine
746 if first_error == null then
747 if not path.to_cstring.rmdir then
748 first_error = new IOError("Cannot remove `{self}`: {sys.errno.strerror}")
749 end
750 end
751 self.last_error = first_error
752 end
753
754 redef fun ==(other) do return other isa Path and simplified.path == other.simplified.path
755 redef fun hash do return simplified.path.hash
756 end
757
758 # Information on a file
759 #
760 # Created by `Path::stat` and `Path::link_stat`.
761 #
762 # The information within this class is gathered when the instance is initialized
763 # it will not be updated if the targeted file is modified.
764 class FileStat
765 super Finalizable
766
767 # TODO private init
768
769 # The low-level status of a file
770 #
771 # See: POSIX stat(2)
772 private var stat: NativeFileStat
773
774 private var finalized = false
775
776 redef fun finalize
777 do
778 if not finalized then
779 stat.free
780 finalized = true
781 end
782 end
783
784 # Returns the last access time in seconds since Epoch
785 fun last_access_time: Int
786 do
787 assert not finalized
788 return stat.atime
789 end
790
791 # Returns the last access time
792 #
793 # alias for `last_access_time`
794 fun atime: Int do return last_access_time
795
796 # Returns the last modification time in seconds since Epoch
797 fun last_modification_time: Int
798 do
799 assert not finalized
800 return stat.mtime
801 end
802
803 # Returns the last modification time
804 #
805 # alias for `last_modification_time`
806 fun mtime: Int do return last_modification_time
807
808
809 # Size of the file at `path`
810 fun size: Int
811 do
812 assert not finalized
813 return stat.size
814 end
815
816 # Is self a regular file and not a device file, pipe, socket, etc.?
817 fun is_file: Bool
818 do
819 assert not finalized
820 return stat.is_reg
821 end
822
823 # Alias for `is_file`
824 fun is_reg: Bool do return is_file
825
826 # Is this a directory?
827 fun is_dir: Bool
828 do
829 assert not finalized
830 return stat.is_dir
831 end
832
833 # Is this a symbolic link?
834 fun is_link: Bool
835 do
836 assert not finalized
837 return stat.is_lnk
838 end
839
840 # FIXME Make the following POSIX only? or implement in some other way on Windows
841
842 # Returns the last status change time in seconds since Epoch
843 fun last_status_change_time: Int
844 do
845 assert not finalized
846 return stat.ctime
847 end
848
849 # Returns the last status change time
850 #
851 # alias for `last_status_change_time`
852 fun ctime: Int do return last_status_change_time
853
854 # Returns the permission bits of file
855 fun mode: Int
856 do
857 assert not finalized
858 return stat.mode
859 end
860
861 # Is this a character device?
862 fun is_chr: Bool
863 do
864 assert not finalized
865 return stat.is_chr
866 end
867
868 # Is this a block device?
869 fun is_blk: Bool
870 do
871 assert not finalized
872 return stat.is_blk
873 end
874
875 # Is this a FIFO pipe?
876 fun is_fifo: Bool
877 do
878 assert not finalized
879 return stat.is_fifo
880 end
881
882 # Is this a UNIX socket
883 fun is_sock: Bool
884 do
885 assert not finalized
886 return stat.is_sock
887 end
888 end
889
890 redef class Text
891 # Access file system related services on the path at `self`
892 fun to_path: Path do return new Path(to_s)
893
894 private fun write_native_to(s: FileWriter)
895 do
896 for i in substrings do s.write_native(i.to_cstring, 0, i.byte_length)
897 end
898
899 # return true if a file with this names exists
900 fun file_exists: Bool do return to_cstring.file_exists
901
902 # The status of a file. see POSIX stat(2).
903 fun file_stat: nullable FileStat
904 do
905 var stat = to_cstring.file_stat
906 if stat.address_is_null then return null
907 return new FileStat(stat)
908 end
909
910 # The status of a file or of a symlink. see POSIX lstat(2).
911 fun file_lstat: nullable FileStat
912 do
913 var stat = to_cstring.file_lstat
914 if stat.address_is_null then return null
915 return new FileStat(stat)
916 end
917
918 # Remove a file, return true if success
919 fun file_delete: Bool do return to_cstring.file_delete
920
921 # Copy content of file at `self` to `dest`
922 fun file_copy_to(dest: String) do to_path.copy(dest.to_path)
923
924 # Remove the trailing `extension`.
925 #
926 # `extension` usually starts with a dot but could be anything.
927 #
928 # assert "file.txt".strip_extension(".txt") == "file"
929 # assert "file.txt".strip_extension("le.txt") == "fi"
930 # assert "file.txt".strip_extension("xt") == "file.t"
931 #
932 # If `extension == null`, the rightmost extension is stripped, including the last dot.
933 #
934 # assert "file.txt".strip_extension == "file"
935 #
936 # If `extension` is not present, `self` is returned unmodified.
937 #
938 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
939 fun strip_extension(extension: nullable String): String
940 do
941 if extension == null then
942 extension = file_extension
943 if extension == null then
944 return self.to_s
945 else extension = ".{extension}"
946 end
947
948 if has_suffix(extension) then
949 return substring(0, length - extension.length).to_s
950 end
951 return self.to_s
952 end
953
954 # Extract the basename of a path and strip the `extension`
955 #
956 # The extension is stripped only if `extension != null`.
957 #
958 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
959 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
960 # assert "path/to/a_file.ext".basename == "a_file.ext"
961 # assert "path/to".basename(".ext") == "to"
962 # assert "path/to/".basename(".ext") == "to"
963 # assert "path/to".basename == "to"
964 # assert "path".basename == "path"
965 # assert "/path".basename == "path"
966 # assert "/".basename == "/"
967 # assert "".basename == ""
968 #
969 # On Windows, '\' are replaced by '/':
970 #
971 # ~~~nitish
972 # assert "C:\\path\\to\\a_file.ext".basename(".ext") == "a_file"
973 # assert "C:\\".basename == "C:"
974 # ~~~
975 fun basename(extension: nullable String): String
976 do
977 var n = self
978 if is_windows then n = n.replace("\\", "/")
979
980 var l = length - 1 # Index of the last char
981 while l > 0 and self.chars[l] == '/' do l -= 1 # remove all trailing `/`
982 if l == 0 then return "/"
983 var pos = chars.last_index_of_from('/', l)
984 if pos >= 0 then
985 n = substring(pos+1, l-pos)
986 end
987
988 if extension != null then
989 return n.strip_extension(extension)
990 else return n.to_s
991 end
992
993 # Extract the dirname of a path
994 #
995 # assert "/path/to/a_file.ext".dirname == "/path/to"
996 # assert "path/to/a_file.ext".dirname == "path/to"
997 # assert "path/to".dirname == "path"
998 # assert "path/to/".dirname == "path"
999 # assert "path".dirname == "."
1000 # assert "/path".dirname == "/"
1001 # assert "/".dirname == "/"
1002 # assert "".dirname == "."
1003 #
1004 # On Windows, '\' are replaced by '/':
1005 #
1006 # ~~~nitish
1007 # assert "C:\\path\\to\\a_file.ext".dirname == "C:/path/to"
1008 # assert "C:\\file".dirname == "C:"
1009 # ~~~
1010 fun dirname: String
1011 do
1012 var s = self
1013 if is_windows then s = s.replace("\\", "/")
1014
1015 var l = length - 1 # Index of the last char
1016 while l > 0 and s.chars[l] == '/' do l -= 1 # remove all trailing `/`
1017 var pos = s.chars.last_index_of_from('/', l)
1018 if pos > 0 then
1019 return s.substring(0, pos).to_s
1020 else if pos == 0 then
1021 return "/"
1022 else
1023 return "."
1024 end
1025 end
1026
1027 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
1028 #
1029 # Require: `file_exists`
1030 fun realpath: String do
1031 var cs = to_cstring.file_realpath
1032 assert file_exists
1033 var res = cs.to_s
1034 cs.free
1035 return res
1036 end
1037
1038 # Simplify a file path by remove useless `.`, removing `//`, and resolving `..`
1039 #
1040 # * `..` are not resolved if they start the path
1041 # * starting `.` is simplified unless the path is empty
1042 # * starting `/` is not removed
1043 # * trailing `/` is removed
1044 #
1045 # Note that the method only work on the string:
1046 #
1047 # * no I/O access is performed
1048 # * the validity of the path is not checked
1049 #
1050 # ~~~
1051 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
1052 # assert "../dir/file".simplify_path == "../dir/file"
1053 # assert "dir/../../".simplify_path == ".."
1054 # assert "dir/..".simplify_path == "."
1055 # assert "//absolute//path/".simplify_path == "/absolute/path"
1056 # assert "//absolute//../".simplify_path == "/"
1057 # assert "/".simplify_path == "/"
1058 # assert "../".simplify_path == ".."
1059 # assert "./".simplify_path == "."
1060 # assert "././././././".simplify_path == "."
1061 # assert "./../dir".simplify_path == "../dir"
1062 # assert "./dir".simplify_path == "dir"
1063 # ~~~
1064 #
1065 # On Windows, '\' are replaced by '/':
1066 #
1067 # ~~~nitish
1068 # assert "C:\\some\\.\\complex\\../../path/to/a_file.ext".simplify_path == "C:/path/to/a_file.ext"
1069 # assert "C:\\".simplify_path == "C:"
1070 # ~~~
1071 fun simplify_path: String
1072 do
1073 var s = self
1074 if is_windows then s = s.replace("\\", "/")
1075 var a = s.split_with("/")
1076 var a2 = new Array[String]
1077 for x in a do
1078 if x == "." and not a2.is_empty then continue # skip `././`
1079 if x == "" and not a2.is_empty then continue # skip `//`
1080 if x == ".." and not a2.is_empty and a2.last != ".." then
1081 if a2.last == "." then # do not skip `./../`
1082 a2.pop # reduce `./../` in `../`
1083 else # reduce `dir/../` in `/`
1084 a2.pop
1085 continue
1086 end
1087 else if not a2.is_empty and a2.last == "." then
1088 a2.pop # reduce `./dir` in `dir`
1089 end
1090 a2.push(x)
1091 end
1092 if a2.is_empty then return "."
1093 if a2.length == 1 and a2.first == "" then return "/"
1094 return a2.join("/")
1095 end
1096
1097 # Correctly join two path using the directory separator.
1098 #
1099 # Using a standard "{self}/{path}" does not work in the following cases:
1100 #
1101 # * `self` is empty.
1102 # * `path` starts with `'/'`.
1103 #
1104 # This method ensures that the join is valid.
1105 #
1106 # assert "hello".join_path("world") == "hello/world"
1107 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
1108 # assert "".join_path("world") == "world"
1109 # assert "hello".join_path("/world") == "/world"
1110 # assert "hello/".join_path("world") == "hello/world"
1111 # assert "hello/".join_path("/world") == "/world"
1112 #
1113 # Note: You may want to use `simplify_path` on the result.
1114 #
1115 # Note: This method works only with POSIX paths.
1116 fun join_path(path: Text): String
1117 do
1118 if path.is_empty then return self.to_s
1119 if self.is_empty then return path.to_s
1120 if path.chars[0] == '/' then return path.to_s
1121 if self.last == '/' then return "{self}{path}"
1122 return "{self}/{path}"
1123 end
1124
1125 # Convert the path (`self`) to a program name.
1126 #
1127 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
1128 # used as a program name. In order to do that, prepend `./` if needed.
1129 #
1130 # assert "foo".to_program_name == "./foo"
1131 # assert "/foo".to_program_name == "/foo"
1132 # assert "".to_program_name == "./" # At least, your shell will detect the error.
1133 fun to_program_name: String do
1134 if self.has_prefix("/") then
1135 return self.to_s
1136 else
1137 return "./{self}"
1138 end
1139 end
1140
1141 # Alias for `join_path`
1142 #
1143 # assert "hello" / "world" == "hello/world"
1144 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
1145 # assert "" / "world" == "world"
1146 # assert "/hello" / "/world" == "/world"
1147 #
1148 # This operator is quite useful for chaining changes of path.
1149 # The next one being relative to the previous one.
1150 #
1151 # var a = "foo"
1152 # var b = "/bar"
1153 # var c = "baz/foobar"
1154 # assert a/b/c == "/bar/baz/foobar"
1155 fun /(path: Text): String do return join_path(path)
1156
1157 # Returns the relative path needed to go from `self` to `dest`.
1158 #
1159 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
1160 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
1161 #
1162 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
1163 #
1164 # In some cases, the result is still independent of the current directory:
1165 #
1166 # assert "foo/bar".relpath("..") == "../../.."
1167 #
1168 # In other cases, parts of the current directory may be exhibited:
1169 #
1170 # var p = "../foo/bar".relpath("baz")
1171 # var c = getcwd.basename
1172 # assert p == "../../{c}/baz"
1173 #
1174 # For path resolution independent of the current directory (eg. for paths in URL),
1175 # or to use an other starting directory than the current directory,
1176 # just force absolute paths:
1177 #
1178 # var start = "/a/b/c/d"
1179 # var p2 = (start/"../foo/bar").relpath(start/"baz")
1180 # assert p2 == "../../d/baz"
1181 #
1182 #
1183 # Neither `self` or `dest` has to be real paths or to exist in directories since
1184 # the resolution is only done with string manipulations and without any access to
1185 # the underlying file system.
1186 #
1187 # If `self` and `dest` are the same directory, the empty string is returned:
1188 #
1189 # assert "foo".relpath("foo") == ""
1190 # assert "foo/../bar".relpath("bar") == ""
1191 #
1192 # The empty string and "." designate both the current directory:
1193 #
1194 # assert "".relpath("foo/bar") == "foo/bar"
1195 # assert ".".relpath("foo/bar") == "foo/bar"
1196 # assert "foo/bar".relpath("") == "../.."
1197 # assert "/" + "/".relpath(".") == getcwd
1198 fun relpath(dest: String): String
1199 do
1200 # TODO windows support
1201 var cwd = getcwd
1202 var from = (cwd/self).simplify_path.split("/")
1203 if from.last.is_empty then from.pop # case for the root directory
1204 var to = (cwd/dest).simplify_path.split("/")
1205 if to.last.is_empty then to.pop # case for the root directory
1206
1207 # Remove common prefixes
1208 while not from.is_empty and not to.is_empty and from.first == to.first do
1209 from.shift
1210 to.shift
1211 end
1212
1213 # Result is going up in `from` with ".." then going down following `to`
1214 var from_len = from.length
1215 if from_len == 0 then return to.join("/")
1216 var up = "../"*(from_len-1) + ".."
1217 if to.is_empty then return up
1218 var res = up + "/" + to.join("/")
1219 return res
1220 end
1221
1222 # Create a directory (and all intermediate directories if needed)
1223 #
1224 # The optional `mode` parameter specifies the permissions of the directory,
1225 # the default value is `0o777`.
1226 #
1227 # Return an error object in case of error.
1228 #
1229 # assert "/etc/".mkdir != null
1230 fun mkdir(mode: nullable Int): nullable Error
1231 do
1232 mode = mode or else 0o777
1233 var s = self
1234 if is_windows then s = s.replace("\\", "/")
1235
1236 var dirs = s.split_with("/")
1237 var path = new FlatBuffer
1238 if dirs.is_empty then return null
1239 if dirs[0].is_empty then
1240 # it was a starting /
1241 path.add('/')
1242 end
1243 var error: nullable Error = null
1244 for i in [0 .. dirs.length - 1[ do
1245 var d = dirs[i]
1246 if d.is_empty then continue
1247 path.append(d)
1248 path.add('/')
1249 if path.file_exists then continue
1250 var res = path.to_cstring.file_mkdir(mode)
1251 if not res and error == null then
1252 error = new IOError("Cannot create directory `{path}`: {sys.errno.strerror}")
1253 end
1254 end
1255 var res = s.to_cstring.file_mkdir(mode)
1256 if not res and error == null then
1257 error = new IOError("Cannot create directory `{path}`: {sys.errno.strerror}")
1258 end
1259 return error
1260 end
1261
1262 # Delete a directory and all of its content, return `true` on success
1263 #
1264 # Does not go through symbolic links and may get stuck in a cycle if there
1265 # is a cycle in the filesystem.
1266 #
1267 # Return an error object in case of error.
1268 #
1269 # assert "/fail/does not/exist".rmdir != null
1270 fun rmdir: nullable Error
1271 do
1272 var p = to_path
1273 p.rmdir
1274 return p.last_error
1275 end
1276
1277 # Change the current working directory
1278 #
1279 # "/etc".chdir
1280 # assert getcwd == "/etc"
1281 # "..".chdir
1282 # assert getcwd == "/"
1283 #
1284 # Return an error object in case of error.
1285 #
1286 # assert "/etc".chdir == null
1287 # assert "/fail/does no/exist".chdir != null
1288 # assert getcwd == "/etc" # unchanger
1289 fun chdir: nullable Error
1290 do
1291 var res = to_cstring.file_chdir
1292 if res then return null
1293 var error = new IOError("Cannot change directory to `{self}`: {sys.errno.strerror}")
1294 return error
1295 end
1296
1297 # Return right-most extension (without the dot)
1298 #
1299 # Only the last extension is returned.
1300 # There is no special case for combined extensions.
1301 #
1302 # assert "file.txt".file_extension == "txt"
1303 # assert "file.tar.gz".file_extension == "gz"
1304 #
1305 # For file without extension, `null` is returned.
1306 # Hoever, for trailing dot, `""` is returned.
1307 #
1308 # assert "file".file_extension == null
1309 # assert "file.".file_extension == ""
1310 #
1311 # The starting dot of hidden files is never considered.
1312 #
1313 # assert ".file.txt".file_extension == "txt"
1314 # assert ".file".file_extension == null
1315 fun file_extension: nullable String
1316 do
1317 var last_slash = chars.last_index_of('.')
1318 if last_slash > 0 then
1319 return substring( last_slash+1, length ).to_s
1320 else
1321 return null
1322 end
1323 end
1324
1325 # Returns entries contained within the directory represented by self.
1326 #
1327 # var files = "/etc".files
1328 # assert files.has("issue")
1329 #
1330 # Returns an empty array in case of error
1331 #
1332 # files = "/etc/issue".files
1333 # assert files.is_empty
1334 #
1335 # TODO find a better way to handle errors and to give them back to the user.
1336 fun files: Array[String]
1337 do
1338 var res = new Array[String]
1339 var d = new NativeDir.opendir(to_cstring)
1340 if d.address_is_null then return res
1341
1342 loop
1343 var de = d.readdir
1344 if de.address_is_null then break
1345 var name = de.to_s
1346 if name == "." or name == ".." then continue
1347 res.add name
1348 end
1349 d.closedir
1350
1351 return res
1352 end
1353 end
1354
1355 redef class FlatString
1356 redef fun write_native_to(s)
1357 do
1358 s.write_native(items, first_byte, byte_length)
1359 end
1360
1361 redef fun file_extension do
1362 var its = _items
1363 var p = last_byte
1364 var c = its[p]
1365 var st = _first_byte
1366 while p >= st and c != '.'.ascii do
1367 p -= 1
1368 c = its[p]
1369 end
1370 if p <= st then return null
1371 var ls = last_byte
1372 return new FlatString.with_infos(its, ls - p, p + 1)
1373 end
1374
1375 redef fun basename(extension) do
1376 var s = self
1377 if is_windows then s = s.replace("\\", "/").as(FlatString)
1378
1379 var bname
1380 var l = s.last_byte
1381 var its = s._items
1382 var min = s._first_byte
1383 var sl = '/'.ascii
1384 while l > min and its[l] == sl do l -= 1
1385 if l == min then return "/"
1386 var ns = l
1387 while ns >= min and its[ns] != sl do ns -= 1
1388 bname = new FlatString.with_infos(its, l - ns, ns + 1)
1389
1390 return if extension != null then bname.strip_extension(extension) else bname
1391 end
1392 end
1393
1394 redef class CString
1395 private fun file_exists: Bool `{
1396 #ifdef _WIN32
1397 DWORD attribs = GetFileAttributesA(self);
1398 return attribs != INVALID_FILE_ATTRIBUTES;
1399 #else
1400 FILE *hdl = fopen(self,"r");
1401 if(hdl != NULL){
1402 fclose(hdl);
1403 }
1404 return hdl != NULL;
1405 #endif
1406 `}
1407
1408 private fun file_stat: NativeFileStat `{
1409 struct stat buff;
1410 if(stat(self, &buff) != -1) {
1411 struct stat* stat_element;
1412 stat_element = malloc(sizeof(struct stat));
1413 return memcpy(stat_element, &buff, sizeof(struct stat));
1414 }
1415 return 0;
1416 `}
1417
1418 private fun file_lstat: NativeFileStat `{
1419 #ifdef _WIN32
1420 // FIXME use a higher level abstraction to support WIN32
1421 return NULL;
1422 #else
1423 struct stat* stat_element;
1424 int res;
1425 stat_element = malloc(sizeof(struct stat));
1426 res = lstat(self, stat_element);
1427 if (res == -1) return NULL;
1428 return stat_element;
1429 #endif
1430 `}
1431
1432 private fun file_mkdir(mode: Int): Bool `{
1433 #ifdef _WIN32
1434 return !mkdir(self);
1435 #else
1436 return !mkdir(self, mode);
1437 #endif
1438 `}
1439
1440 private fun rmdir: Bool `{ return !rmdir(self); `}
1441
1442 private fun file_delete: Bool `{
1443 return remove(self) == 0;
1444 `}
1445
1446 private fun file_chdir: Bool `{ return !chdir(self); `}
1447
1448 private fun file_realpath: CString `{
1449 #ifdef _WIN32
1450 DWORD len = GetFullPathName(self, 0, NULL, NULL);
1451 char *buf = malloc(len+1); // FIXME don't leak memory
1452 len = GetFullPathName(self, len+1, buf, NULL);
1453 return buf;
1454 #else
1455 return realpath(self, NULL);
1456 #endif
1457 `}
1458 end
1459
1460 # This class is system dependent ... must reify the vfs
1461 private extern class NativeFileStat `{ struct stat * `}
1462
1463 # Returns the permission bits of file
1464 fun mode: Int `{ return self->st_mode; `}
1465
1466 # Returns the last access time
1467 fun atime: Int `{ return self->st_atime; `}
1468
1469 # Returns the last status change time
1470 fun ctime: Int `{ return self->st_ctime; `}
1471
1472 # Returns the last modification time
1473 fun mtime: Int `{ return self->st_mtime; `}
1474
1475 # Returns the size
1476 fun size: Int `{ return self->st_size; `}
1477
1478 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
1479 fun is_reg: Bool `{ return S_ISREG(self->st_mode); `}
1480
1481 # Returns true if it is a directory
1482 fun is_dir: Bool `{ return S_ISDIR(self->st_mode); `}
1483
1484 # Returns true if it is a character device
1485 fun is_chr: Bool `{ return S_ISCHR(self->st_mode); `}
1486
1487 # Returns true if it is a block device
1488 fun is_blk: Bool `{ return S_ISBLK(self->st_mode); `}
1489
1490 # Returns true if the type is fifo
1491 fun is_fifo: Bool `{ return S_ISFIFO(self->st_mode); `}
1492
1493 # Returns true if the type is a link
1494 fun is_lnk: Bool `{
1495 #ifdef _WIN32
1496 return 0;
1497 #else
1498 return S_ISLNK(self->st_mode);
1499 #endif
1500 `}
1501
1502 # Returns true if the type is a socket
1503 fun is_sock: Bool `{
1504 #ifdef _WIN32
1505 return 0;
1506 #else
1507 return S_ISSOCK(self->st_mode);
1508 #endif
1509 `}
1510 end
1511
1512 # Instance of this class are standard FILE * pointers
1513 private extern class NativeFile `{ FILE* `}
1514 fun io_read(buf: CString, len: Int): Int `{
1515 return fread(buf, 1, len, self);
1516 `}
1517
1518 fun io_write(buf: CString, from, len: Int): Int `{
1519 size_t res = fwrite(buf+from, 1, len, self);
1520 #ifdef _WIN32
1521 // Force flushing buffer because end of line does not trigger a flush
1522 fflush(self);
1523 #endif
1524 return (long)res;
1525 `}
1526
1527 fun write_byte(value: Byte): Int `{
1528 unsigned char b = (unsigned char)value;
1529 return fwrite(&b, 1, 1, self);
1530 `}
1531
1532 fun io_close: Int `{ return fclose(self); `}
1533
1534 fun file_stat: NativeFileStat `{
1535 struct stat buff;
1536 if(fstat(fileno(self), &buff) != -1) {
1537 struct stat* stat_element;
1538 stat_element = malloc(sizeof(struct stat));
1539 return memcpy(stat_element, &buff, sizeof(struct stat));
1540 }
1541 return 0;
1542 `}
1543
1544 fun ferror: Bool `{ return ferror(self); `}
1545
1546 fun fileno: Int `{ return fileno(self); `}
1547
1548 # Flushes the buffer, forcing the write operation
1549 fun flush: Int `{ return fflush(self); `}
1550
1551 # Used to specify how the buffering will be handled for the current stream.
1552 fun set_buffering_type(buf_length, mode: Int): Int `{
1553 return setvbuf(self, NULL, (int)mode, buf_length);
1554 `}
1555
1556 new io_open_read(path: CString) `{ return fopen(path, "r"); `}
1557
1558 new io_open_write(path: CString) `{ return fopen(path, "w"); `}
1559
1560 new native_stdin `{ return stdin; `}
1561
1562 new native_stdout `{ return stdout; `}
1563
1564 new native_stderr `{ return stderr; `}
1565 end
1566
1567 # Standard `DIR*` pointer
1568 private extern class NativeDir `{ DIR* `}
1569
1570 # Open a directory
1571 new opendir(path: CString) `{ return opendir(path); `}
1572
1573 # Close a directory
1574 fun closedir `{ closedir(self); `}
1575
1576 # Read the next directory entry
1577 fun readdir: CString `{
1578 struct dirent *de;
1579 de = readdir(self);
1580 if (!de) return NULL;
1581 return de->d_name;
1582 `}
1583 end
1584
1585 redef class Sys
1586
1587 # Standard input
1588 var stdin: PollableReader = new Stdin is protected writable, lazy
1589
1590 # Standard output
1591 var stdout: Writer = new Stdout is protected writable, lazy
1592
1593 # Standard output for errors
1594 var stderr: Writer = new Stderr is protected writable, lazy
1595
1596 # Enumeration for buffer mode full (flushes when buffer is full)
1597 fun buffer_mode_full: Int `{ return _IOFBF; `}
1598
1599 # Enumeration for buffer mode line (flushes when a `\n` is encountered)
1600 fun buffer_mode_line: Int `{ return _IONBF; `}
1601
1602 # Enumeration for buffer mode none (flushes ASAP when something is written)
1603 fun buffer_mode_none: Int `{ return _IOLBF; `}
1604
1605 # returns first available stream to read or write to
1606 # return null on interruption (possibly a signal)
1607 protected fun poll( streams : Sequence[FileStream] ) : nullable FileStream
1608 do
1609 var in_fds = new Array[Int]
1610 var out_fds = new Array[Int]
1611 var fd_to_stream = new HashMap[Int,FileStream]
1612 for s in streams do
1613 var fd = s.fd
1614 if s isa FileReader then in_fds.add( fd )
1615 if s isa FileWriter then out_fds.add( fd )
1616
1617 fd_to_stream[fd] = s
1618 end
1619
1620 var polled_fd = intern_poll( in_fds, out_fds )
1621
1622 if polled_fd == null then
1623 return null
1624 else
1625 return fd_to_stream[polled_fd]
1626 end
1627 end
1628
1629 private fun intern_poll(in_fds: Array[Int], out_fds: Array[Int]): nullable Int
1630 import Array[Int].length, Array[Int].[], Int.as(nullable Int) `{
1631 #ifndef _WIN32
1632 // FIXME use a higher level abstraction to support WIN32
1633
1634 int in_len, out_len, total_len;
1635 struct pollfd *c_fds;
1636 int i;
1637 int first_polled_fd = -1;
1638 int result;
1639
1640 in_len = (int)Array_of_Int_length( in_fds );
1641 out_len = (int)Array_of_Int_length( out_fds );
1642 total_len = in_len + out_len;
1643 c_fds = malloc( sizeof(struct pollfd) * total_len );
1644
1645 /* input streams */
1646 for ( i=0; i<in_len; i ++ ) {
1647 int fd = (int)Array_of_Int__index( in_fds, i );
1648
1649 c_fds[i].fd = fd;
1650 c_fds[i].events = POLLIN;
1651 }
1652
1653 /* output streams */
1654 for ( i=0; i<out_len; i ++ ) {
1655 int fd = (int)Array_of_Int__index( out_fds, i );
1656
1657 c_fds[i].fd = fd;
1658 c_fds[i].events = POLLOUT;
1659 }
1660
1661 /* poll all fds, unlimited timeout */
1662 result = poll( c_fds, total_len, -1 );
1663
1664 if ( result > 0 ) {
1665 /* analyse results */
1666 for ( i=0; i<total_len; i++ )
1667 if ( c_fds[i].revents & c_fds[i].events || /* awaited event */
1668 c_fds[i].revents & POLLHUP ) /* closed */
1669 {
1670 first_polled_fd = c_fds[i].fd;
1671 break;
1672 }
1673
1674 return Int_as_nullable( first_polled_fd );
1675 }
1676 else if ( result < 0 )
1677 fprintf( stderr, "Error in Stream:poll: %s\n", strerror( errno ) );
1678 #endif
1679
1680 return null_Int();
1681 `}
1682
1683 end
1684
1685 # Print `objects` on the standard output (`stdout`).
1686 fun printn(objects: Object...)
1687 do
1688 sys.stdout.write(objects.plain_to_s)
1689 end
1690
1691 # Print an `object` on the standard output (`stdout`) and add a newline.
1692 fun print(object: Object)
1693 do
1694 sys.stdout.write(object.to_s)
1695 sys.stdout.write("\n")
1696 end
1697
1698 # Print `object` on the error output (`stderr` or a log system)
1699 fun print_error(object: Object)
1700 do
1701 sys.stderr.write object.to_s
1702 sys.stderr.write "\n"
1703 end
1704
1705 # Read a character from the standard input (`stdin`).
1706 fun getc: Char
1707 do
1708 var c = sys.stdin.read_char
1709 if c == null then return '\1'
1710 return c
1711 end
1712
1713 # Read a line from the standard input (`stdin`).
1714 fun gets: String
1715 do
1716 return sys.stdin.read_line
1717 end
1718
1719 # Return the working (current) directory
1720 fun getcwd: String do return native_getcwd.to_s
1721
1722 private fun native_getcwd: CString `{ return getcwd(NULL, 0); `}