lib: update some modules of standard to new constructors
[nit.git] / lib / standard / file.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 # Copyright 2008 Floréal Morandat <morandat@lirmm.fr>
5 # Copyright 2008 Jean-Sébastien Gélinas <calestar@gmail.com>
6 #
7 # This file is free software, which comes along with NIT. This software is
8 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
10 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
11 # is kept unaltered, and a notification of the changes is added.
12 # You are allowed to redistribute it and sell it, alone or is a part of
13 # another product.
14
15 # File manipulations (create, read, write, etc.)
16 module file
17
18 intrude import stream
19 intrude import ropes
20 import string_search
21 import time
22
23 in "C Header" `{
24 #include <dirent.h>
25 #include <string.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <unistd.h>
29 #include <stdio.h>
30 `}
31
32 # File Abstract Stream
33 abstract class FStream
34 super IOS
35 # The path of the file.
36 var path: nullable String = null
37
38 # The FILE *.
39 private var file: nullable NativeFile = null
40
41 fun file_stat: FileStat do return _file.file_stat
42
43 # File descriptor of this file
44 fun fd: Int do return _file.fileno
45 end
46
47 # File input stream
48 class IFStream
49 super FStream
50 super BufferedIStream
51 super PollableIStream
52 # Misc
53
54 # Open the same file again.
55 # The original path is reused, therefore the reopened file can be a different file.
56 fun reopen
57 do
58 if not eof then close
59 _file = new NativeFile.io_open_read(path.to_cstring)
60 end_reached = false
61 _buffer_pos = 0
62 _buffer.clear
63 end
64
65 redef fun close
66 do
67 var i = _file.io_close
68 _buffer.clear
69 end_reached = true
70 end
71
72 redef fun fill_buffer
73 do
74 var nb = _file.io_read(_buffer.items, _buffer.capacity)
75 if nb <= 0 then
76 end_reached = true
77 nb = 0
78 end
79 _buffer.length = nb
80 _buffer_pos = 0
81 end
82
83 # End of file?
84 redef var end_reached: Bool = false
85
86 # Open the file at `path` for reading.
87 init open(path: String)
88 do
89 self.path = path
90 prepare_buffer(10)
91 _file = new NativeFile.io_open_read(path.to_cstring)
92 assert not _file.address_is_null else
93 print "Error: Opening file at '{path}' failed with '{sys.errno.strerror}'"
94 end
95 end
96
97 end
98
99 # File output stream
100 class OFStream
101 super FStream
102 super OStream
103
104 redef fun write(s)
105 do
106 assert _is_writable
107 if s isa FlatText then
108 write_native(s.to_cstring, s.length)
109 else
110 for i in s.substrings do write_native(i.to_cstring, i.length)
111 end
112 end
113
114 redef fun close
115 do
116 var i = _file.io_close
117 _is_writable = false
118 end
119
120 redef var is_writable = false
121
122 # Write `len` bytes from `native`.
123 private fun write_native(native: NativeString, len: Int)
124 do
125 assert _is_writable
126 var err = _file.io_write(native, len)
127 if err != len then
128 # Big problem
129 printn("Problem in writing : ", err, " ", len, "\n")
130 end
131 end
132
133 # Open the file at `path` for writing.
134 init open(path: String)
135 do
136 _file = new NativeFile.io_open_write(path.to_cstring)
137 assert not _file.address_is_null else
138 print "Error: Opening file at '{path}' failed with '{sys.errno.strerror}'"
139 end
140 self.path = path
141 _is_writable = true
142 end
143 end
144
145 ###############################################################################
146
147 class Stdin
148 super IFStream
149
150 init do
151 _file = new NativeFile.native_stdin
152 path = "/dev/stdin"
153 prepare_buffer(1)
154 end
155
156 redef fun poll_in: Bool is extern "file_stdin_poll_in"
157 end
158
159 class Stdout
160 super OFStream
161 init do
162 _file = new NativeFile.native_stdout
163 path = "/dev/stdout"
164 _is_writable = true
165 end
166 end
167
168 class Stderr
169 super OFStream
170 init do
171 _file = new NativeFile.native_stderr
172 path = "/dev/stderr"
173 _is_writable = true
174 end
175 end
176
177 ###############################################################################
178
179 redef class Streamable
180 # Like `write_to` but take care of creating the file
181 fun write_to_file(filepath: String)
182 do
183 var stream = new OFStream.open(filepath)
184 write_to(stream)
185 stream.close
186 end
187 end
188
189 redef class String
190 # return true if a file with this names exists
191 fun file_exists: Bool do return to_cstring.file_exists
192
193 # The status of a file. see POSIX stat(2).
194 fun file_stat: FileStat do return to_cstring.file_stat
195
196 # The status of a file or of a symlink. see POSIX lstat(2).
197 fun file_lstat: FileStat do return to_cstring.file_lstat
198
199 # Remove a file, return true if success
200 fun file_delete: Bool do return to_cstring.file_delete
201
202 # Copy content of file at `self` to `dest`
203 fun file_copy_to(dest: String)
204 do
205 var input = new IFStream.open(self)
206 var output = new OFStream.open(dest)
207
208 while not input.eof do
209 var buffer = input.read(1024)
210 output.write buffer
211 end
212
213 input.close
214 output.close
215 end
216
217 # Remove the trailing extension `ext`.
218 #
219 # `ext` usually starts with a dot but could be anything.
220 #
221 # assert "file.txt".strip_extension(".txt") == "file"
222 # assert "file.txt".strip_extension("le.txt") == "fi"
223 # assert "file.txt".strip_extension("xt") == "file.t"
224 #
225 # if `ext` is not present, `self` is returned unmodified.
226 #
227 # assert "file.txt".strip_extension(".tar.gz") == "file.txt"
228 fun strip_extension(ext: String): String
229 do
230 if has_suffix(ext) then
231 return substring(0, length - ext.length)
232 end
233 return self
234 end
235
236 # Extract the basename of a path and remove the extension
237 #
238 # assert "/path/to/a_file.ext".basename(".ext") == "a_file"
239 # assert "path/to/a_file.ext".basename(".ext") == "a_file"
240 # assert "path/to".basename(".ext") == "to"
241 # assert "path/to/".basename(".ext") == "to"
242 # assert "path".basename("") == "path"
243 # assert "/path".basename("") == "path"
244 # assert "/".basename("") == "/"
245 # assert "".basename("") == ""
246 fun basename(ext: String): String
247 do
248 var l = length - 1 # Index of the last char
249 while l > 0 and self.chars[l] == '/' do l -= 1 # remove all trailing `/`
250 if l == 0 then return "/"
251 var pos = chars.last_index_of_from('/', l)
252 var n = self
253 if pos >= 0 then
254 n = substring(pos+1, l-pos)
255 end
256 return n.strip_extension(ext)
257 end
258
259 # Extract the dirname of a path
260 #
261 # assert "/path/to/a_file.ext".dirname == "/path/to"
262 # assert "path/to/a_file.ext".dirname == "path/to"
263 # assert "path/to".dirname == "path"
264 # assert "path/to/".dirname == "path"
265 # assert "path".dirname == "."
266 # assert "/path".dirname == "/"
267 # assert "/".dirname == "/"
268 # assert "".dirname == "."
269 fun dirname: String
270 do
271 var l = length - 1 # Index of the last char
272 while l > 0 and self.chars[l] == '/' do l -= 1 # remove all trailing `/`
273 var pos = chars.last_index_of_from('/', l)
274 if pos > 0 then
275 return substring(0, pos)
276 else if pos == 0 then
277 return "/"
278 else
279 return "."
280 end
281 end
282
283 # Return the canonicalized absolute pathname (see POSIX function `realpath`)
284 fun realpath: String do
285 var cs = to_cstring.file_realpath
286 var res = cs.to_s_with_copy
287 # cs.free_malloc # FIXME memory leak
288 return res
289 end
290
291 # Simplify a file path by remove useless ".", removing "//", and resolving ".."
292 # ".." are not resolved if they start the path
293 # starting "/" is not removed
294 # trainling "/" is removed
295 #
296 # Note that the method only wonrk on the string:
297 # * no I/O access is performed
298 # * the validity of the path is not checked
299 #
300 # assert "some/./complex/../../path/from/../to/a////file//".simplify_path == "path/to/a/file"
301 # assert "../dir/file".simplify_path == "../dir/file"
302 # assert "dir/../../".simplify_path == ".."
303 # assert "dir/..".simplify_path == "."
304 # assert "//absolute//path/".simplify_path == "/absolute/path"
305 # assert "//absolute//../".simplify_path == "/"
306 fun simplify_path: String
307 do
308 var a = self.split_with("/")
309 var a2 = new Array[String]
310 for x in a do
311 if x == "." then continue
312 if x == "" and not a2.is_empty then continue
313 if x == ".." and not a2.is_empty and a2.last != ".." then
314 a2.pop
315 continue
316 end
317 a2.push(x)
318 end
319 if a2.is_empty then return "."
320 if a2.length == 1 and a2.first == "" then return "/"
321 return a2.join("/")
322 end
323
324 # Correctly join two path using the directory separator.
325 #
326 # Using a standard "{self}/{path}" does not work in the following cases:
327 #
328 # * `self` is empty.
329 # * `path` ends with `'/'`.
330 # * `path` starts with `'/'`.
331 #
332 # This method ensures that the join is valid.
333 #
334 # assert "hello".join_path("world") == "hello/world"
335 # assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
336 # assert "".join_path("world") == "world"
337 # assert "hello".join_path("/world") == "/world"
338 # assert "hello/".join_path("world") == "hello/world"
339 # assert "hello/".join_path("/world") == "/world"
340 #
341 # Note: You may want to use `simplify_path` on the result.
342 #
343 # Note: This method works only with POSIX paths.
344 fun join_path(path: String): String
345 do
346 if path.is_empty then return self
347 if self.is_empty then return path
348 if path.chars[0] == '/' then return path
349 if self.last == '/' then return "{self}{path}"
350 return "{self}/{path}"
351 end
352
353 # Convert the path (`self`) to a program name.
354 #
355 # Ensure the path (`self`) will be treated as-is by POSIX shells when it is
356 # used as a program name. In order to do that, prepend `./` if needed.
357 #
358 # assert "foo".to_program_name == "./foo"
359 # assert "/foo".to_program_name == "/foo"
360 # assert "".to_program_name == "./" # At least, your shell will detect the error.
361 fun to_program_name: String do
362 if self.has_prefix("/") then
363 return self
364 else
365 return "./{self}"
366 end
367 end
368
369 # Alias for `join_path`
370 #
371 # assert "hello" / "world" == "hello/world"
372 # assert "hel/lo" / "wor/ld" == "hel/lo/wor/ld"
373 # assert "" / "world" == "world"
374 # assert "/hello" / "/world" == "/world"
375 #
376 # This operator is quite useful for chaining changes of path.
377 # The next one being relative to the previous one.
378 #
379 # var a = "foo"
380 # var b = "/bar"
381 # var c = "baz/foobar"
382 # assert a/b/c == "/bar/baz/foobar"
383 fun /(path: String): String do return join_path(path)
384
385 # Returns the relative path needed to go from `self` to `dest`.
386 #
387 # assert "/foo/bar".relpath("/foo/baz") == "../baz"
388 # assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"
389 #
390 # If `self` or `dest` is relative, they are considered relatively to `getcwd`.
391 #
392 # In some cases, the result is still independent of the current directory:
393 #
394 # assert "foo/bar".relpath("..") == "../../.."
395 #
396 # In other cases, parts of the current directory may be exhibited:
397 #
398 # var p = "../foo/bar".relpath("baz")
399 # var c = getcwd.basename("")
400 # assert p == "../../{c}/baz"
401 #
402 # For path resolution independent of the current directory (eg. for paths in URL),
403 # or to use an other starting directory than the current directory,
404 # just force absolute paths:
405 #
406 # var start = "/a/b/c/d"
407 # var p2 = (start/"../foo/bar").relpath(start/"baz")
408 # assert p2 == "../../d/baz"
409 #
410 #
411 # Neither `self` or `dest` has to be real paths or to exist in directories since
412 # the resolution is only done with string manipulations and without any access to
413 # the underlying file system.
414 #
415 # If `self` and `dest` are the same directory, the empty string is returned:
416 #
417 # assert "foo".relpath("foo") == ""
418 # assert "foo/../bar".relpath("bar") == ""
419 #
420 # The empty string and "." designate both the current directory:
421 #
422 # assert "".relpath("foo/bar") == "foo/bar"
423 # assert ".".relpath("foo/bar") == "foo/bar"
424 # assert "foo/bar".relpath("") == "../.."
425 # assert "/" + "/".relpath(".") == getcwd
426 fun relpath(dest: String): String
427 do
428 var cwd = getcwd
429 var from = (cwd/self).simplify_path.split("/")
430 if from.last.is_empty then from.pop # case for the root directory
431 var to = (cwd/dest).simplify_path.split("/")
432 if to.last.is_empty then to.pop # case for the root directory
433
434 # Remove common prefixes
435 while not from.is_empty and not to.is_empty and from.first == to.first do
436 from.shift
437 to.shift
438 end
439
440 # Result is going up in `from` with ".." then going down following `to`
441 var from_len = from.length
442 if from_len == 0 then return to.join("/")
443 var up = "../"*(from_len-1) + ".."
444 if to.is_empty then return up
445 var res = up + "/" + to.join("/")
446 return res
447 end
448
449 # Create a directory (and all intermediate directories if needed)
450 fun mkdir
451 do
452 var dirs = self.split_with("/")
453 var path = new FlatBuffer
454 if dirs.is_empty then return
455 if dirs[0].is_empty then
456 # it was a starting /
457 path.add('/')
458 end
459 for d in dirs do
460 if d.is_empty then continue
461 path.append(d)
462 path.add('/')
463 path.to_s.to_cstring.file_mkdir
464 end
465 end
466
467 # Delete a directory and all of its content, return `true` on success
468 #
469 # Does not go through symbolic links and may get stuck in a cycle if there
470 # is a cycle in the filesystem.
471 fun rmdir: Bool
472 do
473 var ok = true
474 for file in self.files do
475 var file_path = self.join_path(file)
476 var stat = file_path.file_lstat
477 if stat.is_dir then
478 ok = file_path.rmdir and ok
479 else
480 ok = file_path.file_delete and ok
481 end
482 stat.free
483 end
484
485 # Delete the directory itself
486 if ok then to_cstring.rmdir
487
488 return ok
489 end
490
491 # Change the current working directory
492 #
493 # "/etc".chdir
494 # assert getcwd == "/etc"
495 # "..".chdir
496 # assert getcwd == "/"
497 #
498 # TODO: errno
499 fun chdir do to_cstring.file_chdir
500
501 # Return right-most extension (without the dot)
502 #
503 # Only the last extension is returned.
504 # There is no special case for combined extensions.
505 #
506 # assert "file.txt".file_extension == "txt"
507 # assert "file.tar.gz".file_extension == "gz"
508 #
509 # For file without extension, `null` is returned.
510 # Hoever, for trailing dot, `""` is returned.
511 #
512 # assert "file".file_extension == null
513 # assert "file.".file_extension == ""
514 #
515 # The starting dot of hidden files is never considered.
516 #
517 # assert ".file.txt".file_extension == "txt"
518 # assert ".file".file_extension == null
519 fun file_extension: nullable String
520 do
521 var last_slash = chars.last_index_of('.')
522 if last_slash > 0 then
523 return substring( last_slash+1, length )
524 else
525 return null
526 end
527 end
528
529 # returns files contained within the directory represented by self
530 fun files : Set[ String ] is extern import HashSet[String], HashSet[String].add, NativeString.to_s, String.to_cstring, HashSet[String].as(Set[String]) `{
531 char *dir_path;
532 DIR *dir;
533
534 dir_path = String_to_cstring( recv );
535 if ((dir = opendir(dir_path)) == NULL)
536 {
537 perror( dir_path );
538 exit( 1 );
539 }
540 else
541 {
542 HashSet_of_String results;
543 String file_name;
544 struct dirent *de;
545
546 results = new_HashSet_of_String();
547
548 while ( ( de = readdir( dir ) ) != NULL )
549 if ( strcmp( de->d_name, ".." ) != 0 &&
550 strcmp( de->d_name, "." ) != 0 )
551 {
552 file_name = NativeString_to_s( strdup( de->d_name ) );
553 HashSet_of_String_add( results, file_name );
554 }
555
556 closedir( dir );
557 return HashSet_of_String_as_Set_of_String( results );
558 }
559 `}
560 end
561
562 redef class NativeString
563 private fun file_exists: Bool is extern "string_NativeString_NativeString_file_exists_0"
564 private fun file_stat: FileStat is extern "string_NativeString_NativeString_file_stat_0"
565 private fun file_lstat: FileStat `{
566 struct stat* stat_element;
567 int res;
568 stat_element = malloc(sizeof(struct stat));
569 res = lstat(recv, stat_element);
570 if (res == -1) return NULL;
571 return stat_element;
572 `}
573 private fun file_mkdir: Bool is extern "string_NativeString_NativeString_file_mkdir_0"
574 private fun rmdir: Bool `{ return rmdir(recv); `}
575 private fun file_delete: Bool is extern "string_NativeString_NativeString_file_delete_0"
576 private fun file_chdir is extern "string_NativeString_NativeString_file_chdir_0"
577 private fun file_realpath: NativeString is extern "file_NativeString_realpath"
578 end
579
580 # This class is system dependent ... must reify the vfs
581 extern class FileStat `{ struct stat * `}
582 # Returns the permission bits of file
583 fun mode: Int is extern "file_FileStat_FileStat_mode_0"
584 # Returns the last access time
585 fun atime: Int is extern "file_FileStat_FileStat_atime_0"
586 # Returns the last status change time
587 fun ctime: Int is extern "file_FileStat_FileStat_ctime_0"
588 # Returns the last modification time
589 fun mtime: Int is extern "file_FileStat_FileStat_mtime_0"
590 # Returns the size
591 fun size: Int is extern "file_FileStat_FileStat_size_0"
592
593 # Returns true if it is a regular file (not a device file, pipe, sockect, ...)
594 fun is_reg: Bool `{ return S_ISREG(recv->st_mode); `}
595 # Returns true if it is a directory
596 fun is_dir: Bool `{ return S_ISDIR(recv->st_mode); `}
597 # Returns true if it is a character device
598 fun is_chr: Bool `{ return S_ISCHR(recv->st_mode); `}
599 # Returns true if it is a block device
600 fun is_blk: Bool `{ return S_ISBLK(recv->st_mode); `}
601 # Returns true if the type is fifo
602 fun is_fifo: Bool `{ return S_ISFIFO(recv->st_mode); `}
603 # Returns true if the type is a link
604 fun is_lnk: Bool `{ return S_ISLNK(recv->st_mode); `}
605 # Returns true if the type is a socket
606 fun is_sock: Bool `{ return S_ISSOCK(recv->st_mode); `}
607 end
608
609 # Instance of this class are standard FILE * pointers
610 private extern class NativeFile `{ FILE* `}
611 fun io_read(buf: NativeString, len: Int): Int is extern "file_NativeFile_NativeFile_io_read_2"
612 fun io_write(buf: NativeString, len: Int): Int is extern "file_NativeFile_NativeFile_io_write_2"
613 fun io_close: Int is extern "file_NativeFile_NativeFile_io_close_0"
614 fun file_stat: FileStat is extern "file_NativeFile_NativeFile_file_stat_0"
615 fun fileno: Int `{ return fileno(recv); `}
616
617 new io_open_read(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_read_1"
618 new io_open_write(path: NativeString) is extern "file_NativeFileCapable_NativeFileCapable_io_open_write_1"
619 new native_stdin is extern "file_NativeFileCapable_NativeFileCapable_native_stdin_0"
620 new native_stdout is extern "file_NativeFileCapable_NativeFileCapable_native_stdout_0"
621 new native_stderr is extern "file_NativeFileCapable_NativeFileCapable_native_stderr_0"
622 end
623
624 redef class Sys
625
626 # Standard input
627 var stdin: PollableIStream = new Stdin is protected writable
628
629 # Standard output
630 var stdout: OStream = new Stdout is protected writable
631
632 # Standard output for errors
633 var stderr: OStream = new Stderr is protected writable
634
635 end
636
637 # Print `objects` on the standard output (`stdout`).
638 protected fun printn(objects: Object...)
639 do
640 sys.stdout.write(objects.to_s)
641 end
642
643 # Print an `object` on the standard output (`stdout`) and add a newline.
644 protected fun print(object: Object)
645 do
646 sys.stdout.write(object.to_s)
647 sys.stdout.write("\n")
648 end
649
650 # Read a character from the standard input (`stdin`).
651 protected fun getc: Char
652 do
653 return sys.stdin.read_char.ascii
654 end
655
656 # Read a line from the standard input (`stdin`).
657 protected fun gets: String
658 do
659 return sys.stdin.read_line
660 end
661
662 # Return the working (current) directory
663 protected fun getcwd: String do return file_getcwd.to_s
664 private fun file_getcwd: NativeString is extern "string_NativeString_NativeString_file_getcwd_0"