]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/fs.rs
afd88ee0ed91b05d93369480c508eb5e1ae7a08d
[rust.git] / src / libstd / io / fs.rs
1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 //
11 // ignore-lexer-test FIXME #15679
12
13 /*! Synchronous File I/O
14
15 This module provides a set of functions and traits for working
16 with regular files & directories on a filesystem.
17
18 At the top-level of the module are a set of freestanding functions, associated
19 with various filesystem operations. They all operate on `Path` objects.
20
21 All operations in this module, including those as part of `File` et al
22 block the task during execution. In the event of failure, all functions/methods
23 will return an `IoResult` type with an `Err` value.
24
25 Also included in this module is an implementation block on the `Path` object
26 defined in `std::path::Path`. The impl adds useful methods about inspecting the
27 metadata of a file. This includes getting the `stat` information, reading off
28 particular bits of it, etc.
29
30 # Example
31
32 ```rust
33 # #![allow(unused_must_use)]
34 use std::io::{File, fs};
35
36 let path = Path::new("foo.txt");
37
38 // create the file, whether it exists or not
39 let mut file = File::create(&path);
40 file.write(b"foobar");
41 # drop(file);
42
43 // open the file in read-only mode
44 let mut file = File::open(&path);
45 file.read_to_end();
46
47 println!("{}", path.stat().unwrap().size);
48 # drop(file);
49 fs::unlink(&path);
50 ```
51
52 */
53
54 use c_str::ToCStr;
55 use clone::Clone;
56 use collections::Collection;
57 use io::standard_error;
58 use io::{FilePermission, Write, UnstableFileStat, Open, FileAccess, FileMode};
59 use io::{IoResult, IoError, FileStat, SeekStyle, Seek, Writer, Reader};
60 use io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append};
61 use io::UpdateIoError;
62 use io;
63 use iter::Iterator;
64 use kinds::Send;
65 use libc;
66 use option::{Some, None, Option};
67 use boxed::Box;
68 use path::{Path, GenericPath};
69 use path;
70 use result::{Err, Ok};
71 use rt::rtio::LocalIo;
72 use rt::rtio;
73 use slice::ImmutableVector;
74 use string::String;
75 use vec::Vec;
76
77 /// Unconstrained file access type that exposes read and write operations
78 ///
79 /// Can be constructed via `File::open()`, `File::create()`, and
80 /// `File::open_mode()`.
81 ///
82 /// # Error
83 ///
84 /// This type will return errors as an `IoResult<T>` if operations are
85 /// attempted against it for which its underlying file descriptor was not
86 /// configured at creation time, via the `FileAccess` parameter to
87 /// `File::open_mode()`.
88 pub struct File {
89     fd: Box<rtio::RtioFileStream + Send>,
90     path: Path,
91     last_nread: int,
92 }
93
94 impl File {
95     /// Open a file at `path` in the mode specified by the `mode` and `access`
96     /// arguments
97     ///
98     /// # Example
99     ///
100     /// ```rust,should_fail
101     /// use std::io::{File, Open, ReadWrite};
102     ///
103     /// let p = Path::new("/some/file/path.txt");
104     ///
105     /// let file = match File::open_mode(&p, Open, ReadWrite) {
106     ///     Ok(f) => f,
107     ///     Err(e) => fail!("file error: {}", e),
108     /// };
109     /// // do some stuff with that file
110     ///
111     /// // the file will be closed at the end of this block
112     /// ```
113     ///
114     /// `FileMode` and `FileAccess` provide information about the permissions
115     /// context in which a given stream is created. More information about them
116     /// can be found in `std::io`'s docs. If a file is opened with `Write`
117     /// or `ReadWrite` access, then it will be created it does not already
118     /// exist.
119     ///
120     /// Note that, with this function, a `File` is returned regardless of the
121     /// access-limitations indicated by `FileAccess` (e.g. calling `write` on a
122     /// `File` opened as `Read` will return an error at runtime).
123     ///
124     /// # Error
125     ///
126     /// This function will return an error under a number of different
127     /// circumstances, to include but not limited to:
128     ///
129     /// * Opening a file that does not exist with `Read` access.
130     /// * Attempting to open a file with a `FileAccess` that the user lacks
131     ///   permissions for
132     /// * Filesystem-level errors (full disk, etc)
133     pub fn open_mode(path: &Path,
134                      mode: FileMode,
135                      access: FileAccess) -> IoResult<File> {
136         let rtio_mode = match mode {
137             Open => rtio::Open,
138             Append => rtio::Append,
139             Truncate => rtio::Truncate,
140         };
141         let rtio_access = match access {
142             Read => rtio::Read,
143             Write => rtio::Write,
144             ReadWrite => rtio::ReadWrite,
145         };
146         let err = LocalIo::maybe_raise(|io| {
147             io.fs_open(&path.to_c_str(), rtio_mode, rtio_access).map(|fd| {
148                 File {
149                     path: path.clone(),
150                     fd: fd,
151                     last_nread: -1
152                 }
153             })
154         }).map_err(IoError::from_rtio_error);
155         err.update_err("couldn't open file", |e| {
156             format!("{}; path={}; mode={}; access={}", e, path.display(),
157                 mode_string(mode), access_string(access))
158         })
159     }
160
161     /// Attempts to open a file in read-only mode. This function is equivalent to
162     /// `File::open_mode(path, Open, Read)`, and will raise all of the same
163     /// errors that `File::open_mode` does.
164     ///
165     /// For more information, see the `File::open_mode` function.
166     ///
167     /// # Example
168     ///
169     /// ```rust
170     /// use std::io::File;
171     ///
172     /// let contents = File::open(&Path::new("foo.txt")).read_to_end();
173     /// ```
174     pub fn open(path: &Path) -> IoResult<File> {
175         File::open_mode(path, Open, Read)
176     }
177
178     /// Attempts to create a file in write-only mode. This function is
179     /// equivalent to `File::open_mode(path, Truncate, Write)`, and will
180     /// raise all of the same errors that `File::open_mode` does.
181     ///
182     /// For more information, see the `File::open_mode` function.
183     ///
184     /// # Example
185     ///
186     /// ```rust
187     /// # #![allow(unused_must_use)]
188     /// use std::io::File;
189     ///
190     /// let mut f = File::create(&Path::new("foo.txt"));
191     /// f.write(b"This is a sample file");
192     /// # drop(f);
193     /// # ::std::io::fs::unlink(&Path::new("foo.txt"));
194     /// ```
195     pub fn create(path: &Path) -> IoResult<File> {
196         File::open_mode(path, Truncate, Write)
197             .update_desc("couldn't create file")
198     }
199
200     /// Returns the original path which was used to open this file.
201     pub fn path<'a>(&'a self) -> &'a Path {
202         &self.path
203     }
204
205     /// Synchronizes all modifications to this file to its permanent storage
206     /// device. This will flush any internal buffers necessary to perform this
207     /// operation.
208     pub fn fsync(&mut self) -> IoResult<()> {
209         let err = self.fd.fsync().map_err(IoError::from_rtio_error);
210         err.update_err("couldn't fsync file",
211                        |e| format!("{}; path={}", e, self.path.display()))
212     }
213
214     /// This function is similar to `fsync`, except that it may not synchronize
215     /// file metadata to the filesystem. This is intended for use case which
216     /// must synchronize content, but don't need the metadata on disk. The goal
217     /// of this method is to reduce disk operations.
218     pub fn datasync(&mut self) -> IoResult<()> {
219         let err = self.fd.datasync().map_err(IoError::from_rtio_error);
220         err.update_err("couldn't datasync file",
221                        |e| format!("{}; path={}", e, self.path.display()))
222     }
223
224     /// Either truncates or extends the underlying file, updating the size of
225     /// this file to become `size`. This is equivalent to unix's `truncate`
226     /// function.
227     ///
228     /// If the `size` is less than the current file's size, then the file will
229     /// be shrunk. If it is greater than the current file's size, then the file
230     /// will be extended to `size` and have all of the intermediate data filled
231     /// in with 0s.
232     pub fn truncate(&mut self, size: i64) -> IoResult<()> {
233         let err = self.fd.truncate(size).map_err(IoError::from_rtio_error);
234         err.update_err("couldn't truncate file", |e| {
235             format!("{}; path={}; size={}", e, self.path.display(), size)
236         })
237     }
238
239     /// Tests whether this stream has reached EOF.
240     ///
241     /// If true, then this file will no longer continue to return data via
242     /// `read`.
243     pub fn eof(&self) -> bool {
244         self.last_nread == 0
245     }
246
247     /// Queries information about the underlying file.
248     pub fn stat(&mut self) -> IoResult<FileStat> {
249         let err = match self.fd.fstat() {
250             Ok(s) => Ok(from_rtio(s)),
251             Err(e) => Err(IoError::from_rtio_error(e)),
252         };
253         err.update_err("couldn't fstat file",
254                        |e| format!("{}; path={}", e, self.path.display()))
255     }
256 }
257
258 /// Unlink a file from the underlying filesystem.
259 ///
260 /// # Example
261 ///
262 /// ```rust
263 /// # #![allow(unused_must_use)]
264 /// use std::io::fs;
265 ///
266 /// let p = Path::new("/some/file/path.txt");
267 /// fs::unlink(&p);
268 /// ```
269 ///
270 /// Note that, just because an unlink call was successful, it is not
271 /// guaranteed that a file is immediately deleted (e.g. depending on
272 /// platform, other open file descriptors may prevent immediate removal)
273 ///
274 /// # Error
275 ///
276 /// This function will return an error if the path points to a directory, the
277 /// user lacks permissions to remove the file, or if some other filesystem-level
278 /// error occurs.
279 pub fn unlink(path: &Path) -> IoResult<()> {
280     return match do_unlink(path) {
281         Ok(()) => Ok(()),
282         Err(e) => {
283             // On unix, a readonly file can be successfully removed. On windows,
284             // however, it cannot. To keep the two platforms in line with
285             // respect to their behavior, catch this case on windows, attempt to
286             // change it to read-write, and then remove the file.
287             if cfg!(windows) && e.kind == io::PermissionDenied {
288                 let stat = match stat(path) {
289                     Ok(stat) => stat,
290                     Err(..) => return Err(e),
291                 };
292                 if stat.perm.intersects(io::UserWrite) { return Err(e) }
293
294                 match chmod(path, stat.perm | io::UserWrite) {
295                     Ok(()) => do_unlink(path),
296                     Err(..) => {
297                         // Try to put it back as we found it
298                         let _ = chmod(path, stat.perm);
299                         Err(e)
300                     }
301                 }
302             } else {
303                 Err(e)
304             }
305         }
306     };
307
308     fn do_unlink(path: &Path) -> IoResult<()> {
309         let err = LocalIo::maybe_raise(|io| {
310             io.fs_unlink(&path.to_c_str())
311         }).map_err(IoError::from_rtio_error);
312         err.update_err("couldn't unlink path",
313                        |e| format!("{}; path={}", e, path.display()))
314     }
315 }
316
317 /// Given a path, query the file system to get information about a file,
318 /// directory, etc. This function will traverse symlinks to query
319 /// information about the destination file.
320 ///
321 /// # Example
322 ///
323 /// ```rust
324 /// use std::io::fs;
325 ///
326 /// let p = Path::new("/some/file/path.txt");
327 /// match fs::stat(&p) {
328 ///     Ok(stat) => { /* ... */ }
329 ///     Err(e) => { /* handle error */ }
330 /// }
331 /// ```
332 ///
333 /// # Error
334 ///
335 /// This call will return an error if the user lacks the requisite permissions
336 /// to perform a `stat` call on the given path or if there is no entry in the
337 /// filesystem at the provided path.
338 pub fn stat(path: &Path) -> IoResult<FileStat> {
339     let err = match LocalIo::maybe_raise(|io| io.fs_stat(&path.to_c_str())) {
340         Ok(s) => Ok(from_rtio(s)),
341         Err(e) => Err(IoError::from_rtio_error(e)),
342     };
343     err.update_err("couldn't stat path",
344                    |e| format!("{}; path={}", e, path.display()))
345 }
346
347 /// Perform the same operation as the `stat` function, except that this
348 /// function does not traverse through symlinks. This will return
349 /// information about the symlink file instead of the file that it points
350 /// to.
351 ///
352 /// # Error
353 ///
354 /// See `stat`
355 pub fn lstat(path: &Path) -> IoResult<FileStat> {
356     let err = match LocalIo::maybe_raise(|io| io.fs_lstat(&path.to_c_str())) {
357         Ok(s) => Ok(from_rtio(s)),
358         Err(e) => Err(IoError::from_rtio_error(e)),
359     };
360     err.update_err("couldn't lstat path",
361                    |e| format!("{}; path={}", e, path.display()))
362 }
363
364 fn from_rtio(s: rtio::FileStat) -> FileStat {
365     #[cfg(windows)]
366     type Mode = libc::c_int;
367     #[cfg(unix)]
368     type Mode = libc::mode_t;
369
370     let rtio::FileStat {
371         size, kind, perm, created, modified,
372         accessed, device, inode, rdev,
373         nlink, uid, gid, blksize, blocks, flags, gen
374     } = s;
375
376     FileStat {
377         size: size,
378         kind: match (kind as Mode) & libc::S_IFMT {
379             libc::S_IFREG => io::TypeFile,
380             libc::S_IFDIR => io::TypeDirectory,
381             libc::S_IFIFO => io::TypeNamedPipe,
382             libc::S_IFBLK => io::TypeBlockSpecial,
383             libc::S_IFLNK => io::TypeSymlink,
384             _ => io::TypeUnknown,
385         },
386         perm: FilePermission::from_bits_truncate(perm as u32),
387         created: created,
388         modified: modified,
389         accessed: accessed,
390         unstable: UnstableFileStat {
391             device: device,
392             inode: inode,
393             rdev: rdev,
394             nlink: nlink,
395             uid: uid,
396             gid: gid,
397             blksize: blksize,
398             blocks: blocks,
399             flags: flags,
400             gen: gen,
401         },
402     }
403 }
404
405 /// Rename a file or directory to a new name.
406 ///
407 /// # Example
408 ///
409 /// ```rust
410 /// # #![allow(unused_must_use)]
411 /// use std::io::fs;
412 ///
413 /// fs::rename(&Path::new("foo"), &Path::new("bar"));
414 /// ```
415 ///
416 /// # Error
417 ///
418 /// Will return an error if the provided `path` doesn't exist, the process lacks
419 /// permissions to view the contents, or if some other intermittent I/O error
420 /// occurs.
421 pub fn rename(from: &Path, to: &Path) -> IoResult<()> {
422     let err = LocalIo::maybe_raise(|io| {
423         io.fs_rename(&from.to_c_str(), &to.to_c_str())
424     }).map_err(IoError::from_rtio_error);
425     err.update_err("couldn't rename path", |e| {
426         format!("{}; from={}; to={}", e, from.display(), to.display())
427     })
428 }
429
430 /// Copies the contents of one file to another. This function will also
431 /// copy the permission bits of the original file to the destination file.
432 ///
433 /// Note that if `from` and `to` both point to the same file, then the file
434 /// will likely get truncated by this operation.
435 ///
436 /// # Example
437 ///
438 /// ```rust
439 /// # #![allow(unused_must_use)]
440 /// use std::io::fs;
441 ///
442 /// fs::copy(&Path::new("foo.txt"), &Path::new("bar.txt"));
443 /// ```
444 ///
445 /// # Error
446 ///
447 /// Will return an error in the following situations, but is not limited to
448 /// just these cases:
449 ///
450 /// * The `from` path is not a file
451 /// * The `from` file does not exist
452 /// * The current process does not have the permission rights to access
453 ///   `from` or write `to`
454 ///
455 /// Note that this copy is not atomic in that once the destination is
456 /// ensured to not exist, there is nothing preventing the destination from
457 /// being created and then destroyed by this operation.
458 pub fn copy(from: &Path, to: &Path) -> IoResult<()> {
459     fn update_err<T>(result: IoResult<T>, from: &Path, to: &Path) -> IoResult<T> {
460         result.update_err("couldn't copy path",
461             |e| format!("{}; from={}; to={}", e, from.display(), to.display()))
462     }
463
464     if !from.is_file() {
465         return update_err(Err(IoError {
466             kind: io::MismatchedFileTypeForOperation,
467             desc: "the source path is not an existing file",
468             detail: None
469         }), from, to)
470     }
471
472     let mut reader = try!(File::open(from));
473     let mut writer = try!(File::create(to));
474     let mut buf = [0, ..io::DEFAULT_BUF_SIZE];
475
476     loop {
477         let amt = match reader.read(buf) {
478             Ok(n) => n,
479             Err(ref e) if e.kind == io::EndOfFile => { break }
480             Err(e) => return update_err(Err(e), from, to)
481         };
482         try!(writer.write(buf.slice_to(amt)));
483     }
484
485     chmod(to, try!(update_err(from.stat(), from, to)).perm)
486 }
487
488 /// Changes the permission mode bits found on a file or a directory. This
489 /// function takes a mask from the `io` module
490 ///
491 /// # Example
492 ///
493 /// ```rust
494 /// # #![allow(unused_must_use)]
495 /// use std::io;
496 /// use std::io::fs;
497 ///
498 /// fs::chmod(&Path::new("file.txt"), io::UserFile);
499 /// fs::chmod(&Path::new("file.txt"), io::UserRead | io::UserWrite);
500 /// fs::chmod(&Path::new("dir"),      io::UserDir);
501 /// fs::chmod(&Path::new("file.exe"), io::UserExec);
502 /// ```
503 ///
504 /// # Error
505 ///
506 /// If this function encounters an I/O error, it will return an `Err` value.
507 /// Some possible error situations are not having the permission to
508 /// change the attributes of a file or the file not existing.
509 pub fn chmod(path: &Path, mode: io::FilePermission) -> IoResult<()> {
510     let err = LocalIo::maybe_raise(|io| {
511         io.fs_chmod(&path.to_c_str(), mode.bits() as uint)
512     }).map_err(IoError::from_rtio_error);
513     err.update_err("couldn't chmod path", |e| {
514         format!("{}; path={}; mode={}", e, path.display(), mode)
515     })
516 }
517
518 /// Change the user and group owners of a file at the specified path.
519 pub fn chown(path: &Path, uid: int, gid: int) -> IoResult<()> {
520     let err = LocalIo::maybe_raise(|io| {
521         io.fs_chown(&path.to_c_str(), uid, gid)
522     }).map_err(IoError::from_rtio_error);
523     err.update_err("couldn't chown path", |e| {
524         format!("{}; path={}; uid={}; gid={}", e, path.display(), uid, gid)
525     })
526 }
527
528 /// Creates a new hard link on the filesystem. The `dst` path will be a
529 /// link pointing to the `src` path. Note that systems often require these
530 /// two paths to both be located on the same filesystem.
531 pub fn link(src: &Path, dst: &Path) -> IoResult<()> {
532     let err = LocalIo::maybe_raise(|io| {
533         io.fs_link(&src.to_c_str(), &dst.to_c_str())
534     }).map_err(IoError::from_rtio_error);
535     err.update_err("couldn't link path", |e| {
536         format!("{}; src={}; dest={}", e, src.display(), dst.display())
537     })
538 }
539
540 /// Creates a new symbolic link on the filesystem. The `dst` path will be a
541 /// symlink pointing to the `src` path.
542 pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> {
543     let err = LocalIo::maybe_raise(|io| {
544         io.fs_symlink(&src.to_c_str(), &dst.to_c_str())
545     }).map_err(IoError::from_rtio_error);
546     err.update_err("couldn't symlink path", |e| {
547         format!("{}; src={}; dest={}", e, src.display(), dst.display())
548     })
549 }
550
551 /// Reads a symlink, returning the file that the symlink points to.
552 ///
553 /// # Error
554 ///
555 /// This function will return an error on failure. Failure conditions include
556 /// reading a file that does not exist or reading a file which is not a symlink.
557 pub fn readlink(path: &Path) -> IoResult<Path> {
558     let err = LocalIo::maybe_raise(|io| {
559         Ok(Path::new(try!(io.fs_readlink(&path.to_c_str()))))
560     }).map_err(IoError::from_rtio_error);
561     err.update_err("couldn't resolve symlink for path",
562                    |e| format!("{}; path={}", e, path.display()))
563 }
564
565 /// Create a new, empty directory at the provided path
566 ///
567 /// # Example
568 ///
569 /// ```rust
570 /// # #![allow(unused_must_use)]
571 /// use std::io;
572 /// use std::io::fs;
573 ///
574 /// let p = Path::new("/some/dir");
575 /// fs::mkdir(&p, io::UserRWX);
576 /// ```
577 ///
578 /// # Error
579 ///
580 /// This call will return an error if the user lacks permissions to make a new
581 /// directory at the provided path, or if the directory already exists.
582 pub fn mkdir(path: &Path, mode: FilePermission) -> IoResult<()> {
583     let err = LocalIo::maybe_raise(|io| {
584         io.fs_mkdir(&path.to_c_str(), mode.bits() as uint)
585     }).map_err(IoError::from_rtio_error);
586     err.update_err("couldn't create directory", |e| {
587         format!("{}; path={}; mode={}", e, path.display(), mode)
588     })
589 }
590
591 /// Remove an existing, empty directory
592 ///
593 /// # Example
594 ///
595 /// ```rust
596 /// # #![allow(unused_must_use)]
597 /// use std::io::fs;
598 ///
599 /// let p = Path::new("/some/dir");
600 /// fs::rmdir(&p);
601 /// ```
602 ///
603 /// # Error
604 ///
605 /// This call will return an error if the user lacks permissions to remove the
606 /// directory at the provided path, or if the directory isn't empty.
607 pub fn rmdir(path: &Path) -> IoResult<()> {
608     let err = LocalIo::maybe_raise(|io| {
609         io.fs_rmdir(&path.to_c_str())
610     }).map_err(IoError::from_rtio_error);
611     err.update_err("couldn't remove directory",
612                    |e| format!("{}; path={}", e, path.display()))
613 }
614
615 /// Retrieve a vector containing all entries within a provided directory
616 ///
617 /// # Example
618 ///
619 /// ```rust
620 /// use std::io;
621 /// use std::io::fs;
622 ///
623 /// // one possible implementation of fs::walk_dir only visiting files
624 /// fn visit_dirs(dir: &Path, cb: |&Path|) -> io::IoResult<()> {
625 ///     if dir.is_dir() {
626 ///         let contents = try!(fs::readdir(dir));
627 ///         for entry in contents.iter() {
628 ///             if entry.is_dir() {
629 ///                 try!(visit_dirs(entry, |p| cb(p)));
630 ///             } else {
631 ///                 cb(entry);
632 ///             }
633 ///         }
634 ///         Ok(())
635 ///     } else {
636 ///         Err(io::standard_error(io::InvalidInput))
637 ///     }
638 /// }
639 /// ```
640 ///
641 /// # Error
642 ///
643 /// Will return an error if the provided `from` doesn't exist, the process lacks
644 /// permissions to view the contents or if the `path` points at a non-directory
645 /// file
646 pub fn readdir(path: &Path) -> IoResult<Vec<Path>> {
647     let err = LocalIo::maybe_raise(|io| {
648         Ok(try!(io.fs_readdir(&path.to_c_str(), 0)).move_iter().map(|a| {
649             Path::new(a)
650         }).collect())
651     }).map_err(IoError::from_rtio_error);
652     err.update_err("couldn't read directory",
653                    |e| format!("{}; path={}", e, path.display()))
654 }
655
656 /// Returns an iterator which will recursively walk the directory structure
657 /// rooted at `path`. The path given will not be iterated over, and this will
658 /// perform iteration in some top-down order.  The contents of unreadable
659 /// subdirectories are ignored.
660 pub fn walk_dir(path: &Path) -> IoResult<Directories> {
661     Ok(Directories {
662         stack: try!(readdir(path).update_err("couldn't walk directory",
663                                              |e| format!("{}; path={}",
664                                                          e, path.display())))
665     })
666 }
667
668 /// An iterator which walks over a directory
669 pub struct Directories {
670     stack: Vec<Path>,
671 }
672
673 impl Iterator<Path> for Directories {
674     fn next(&mut self) -> Option<Path> {
675         match self.stack.pop() {
676             Some(path) => {
677                 if path.is_dir() {
678                     let result = readdir(&path)
679                         .update_err("couldn't advance Directories iterator",
680                                     |e| format!("{}; path={}",
681                                                 e, path.display()));
682
683                     match result {
684                         Ok(dirs) => { self.stack.push_all_move(dirs); }
685                         Err(..) => {}
686                     }
687                 }
688                 Some(path)
689             }
690             None => None
691         }
692     }
693 }
694
695 /// Recursively create a directory and all of its parent components if they
696 /// are missing.
697 ///
698 /// # Error
699 ///
700 /// This function will return an `Err` value if an error happens, see
701 /// `fs::mkdir` for more information about error conditions and performance.
702 pub fn mkdir_recursive(path: &Path, mode: FilePermission) -> IoResult<()> {
703     // tjc: if directory exists but with different permissions,
704     // should we return false?
705     if path.is_dir() {
706         return Ok(())
707     }
708
709     let mut comps = path.components();
710     let mut curpath = path.root_path().unwrap_or(Path::new("."));
711
712     for c in comps {
713         curpath.push(c);
714
715         let result = mkdir(&curpath, mode)
716             .update_err("couldn't recursively mkdir",
717                         |e| format!("{}; path={}", e, path.display()));
718
719         match result {
720             Err(mkdir_err) => {
721                 // already exists ?
722                 if try!(stat(&curpath)).kind != io::TypeDirectory {
723                     return Err(mkdir_err);
724                 }
725             }
726             Ok(()) => ()
727         }
728     }
729
730     Ok(())
731 }
732
733 /// Removes a directory at this path, after removing all its contents. Use
734 /// carefully!
735 ///
736 /// # Error
737 ///
738 /// This function will return an `Err` value if an error happens. See
739 /// `file::unlink` and `fs::readdir` for possible error conditions.
740 pub fn rmdir_recursive(path: &Path) -> IoResult<()> {
741     let mut rm_stack = Vec::new();
742     rm_stack.push(path.clone());
743
744     fn rmdir_failed(err: &IoError, path: &Path) -> String {
745         format!("rmdir_recursive failed; path={}; cause={}",
746                 path.display(), err)
747     }
748
749     fn update_err<T>(err: IoResult<T>, path: &Path) -> IoResult<T> {
750         err.update_err("couldn't recursively rmdir",
751                        |e| rmdir_failed(e, path))
752     }
753
754     while !rm_stack.is_empty() {
755         let children = try!(readdir(rm_stack.last().unwrap())
756             .update_detail(|e| rmdir_failed(e, path)));
757
758         let mut has_child_dir = false;
759
760         // delete all regular files in the way and push subdirs
761         // on the stack
762         for child in children.move_iter() {
763             // FIXME(#12795) we should use lstat in all cases
764             let child_type = match cfg!(windows) {
765                 true => try!(update_err(stat(&child), path)),
766                 false => try!(update_err(lstat(&child), path))
767             };
768
769             if child_type.kind == io::TypeDirectory {
770                 rm_stack.push(child);
771                 has_child_dir = true;
772             } else {
773                 // we can carry on safely if the file is already gone
774                 // (eg: deleted by someone else since readdir)
775                 match update_err(unlink(&child), path) {
776                     Ok(()) => (),
777                     Err(ref e) if e.kind == io::FileNotFound => (),
778                     Err(e) => return Err(e)
779                 }
780             }
781         }
782
783         // if no subdir was found, let's pop and delete
784         if !has_child_dir {
785             let result = update_err(rmdir(&rm_stack.pop().unwrap()), path);
786             match result {
787                 Ok(()) => (),
788                 Err(ref e) if e.kind == io::FileNotFound => (),
789                 Err(e) => return Err(e)
790             }
791         }
792     }
793
794     Ok(())
795 }
796
797 /// Changes the timestamps for a file's last modification and access time.
798 /// The file at the path specified will have its last access time set to
799 /// `atime` and its modification time set to `mtime`. The times specified should
800 /// be in milliseconds.
801 // FIXME(#10301) these arguments should not be u64
802 pub fn change_file_times(path: &Path, atime: u64, mtime: u64) -> IoResult<()> {
803     let err = LocalIo::maybe_raise(|io| {
804         io.fs_utime(&path.to_c_str(), atime, mtime)
805     }).map_err(IoError::from_rtio_error);
806     err.update_err("couldn't change_file_times",
807                    |e| format!("{}; path={}", e, path.display()))
808 }
809
810 impl Reader for File {
811     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
812         fn update_err<T>(result: IoResult<T>, file: &File) -> IoResult<T> {
813             result.update_err("couldn't read file",
814                               |e| format!("{}; path={}",
815                                           e, file.path.display()))
816         }
817
818         let result = update_err(self.fd.read(buf)
819                                     .map_err(IoError::from_rtio_error), self);
820
821         match result {
822             Ok(read) => {
823                 self.last_nread = read;
824                 match read {
825                     0 => update_err(Err(standard_error(io::EndOfFile)), self),
826                     _ => Ok(read as uint)
827                 }
828             },
829             Err(e) => Err(e)
830         }
831     }
832 }
833
834 impl Writer for File {
835     fn write(&mut self, buf: &[u8]) -> IoResult<()> {
836         let err = self.fd.write(buf).map_err(IoError::from_rtio_error);
837         err.update_err("couldn't write to file",
838                        |e| format!("{}; path={}", e, self.path.display()))
839     }
840 }
841
842 impl Seek for File {
843     fn tell(&self) -> IoResult<u64> {
844         let err = self.fd.tell().map_err(IoError::from_rtio_error);
845         err.update_err("couldn't retrieve file cursor (`tell`)",
846                        |e| format!("{}; path={}", e, self.path.display()))
847     }
848
849     fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()> {
850         let style = match style {
851             SeekSet => rtio::SeekSet,
852             SeekCur => rtio::SeekCur,
853             SeekEnd => rtio::SeekEnd,
854         };
855         let err = match self.fd.seek(pos, style) {
856             Ok(_) => {
857                 // successful seek resets EOF indicator
858                 self.last_nread = -1;
859                 Ok(())
860             }
861             Err(e) => Err(IoError::from_rtio_error(e)),
862         };
863         err.update_err("couldn't seek in file",
864                        |e| format!("{}; path={}", e, self.path.display()))
865     }
866 }
867
868 impl path::Path {
869     /// Get information on the file, directory, etc at this path.
870     ///
871     /// Consult the `fs::stat` documentation for more info.
872     ///
873     /// This call preserves identical runtime/error semantics with `file::stat`.
874     pub fn stat(&self) -> IoResult<FileStat> { stat(self) }
875
876     /// Get information on the file, directory, etc at this path, not following
877     /// symlinks.
878     ///
879     /// Consult the `fs::lstat` documentation for more info.
880     ///
881     /// This call preserves identical runtime/error semantics with `file::lstat`.
882     pub fn lstat(&self) -> IoResult<FileStat> { lstat(self) }
883
884     /// Boolean value indicator whether the underlying file exists on the local
885     /// filesystem. Returns false in exactly the cases where `fs::stat` fails.
886     pub fn exists(&self) -> bool {
887         self.stat().is_ok()
888     }
889
890     /// Whether the underlying implementation (be it a file path, or something
891     /// else) points at a "regular file" on the FS. Will return false for paths
892     /// to non-existent locations or directories or other non-regular files
893     /// (named pipes, etc). Follows links when making this determination.
894     pub fn is_file(&self) -> bool {
895         match self.stat() {
896             Ok(s) => s.kind == io::TypeFile,
897             Err(..) => false
898         }
899     }
900
901     /// Whether the underlying implementation (be it a file path, or something
902     /// else) is pointing at a directory in the underlying FS. Will return
903     /// false for paths to non-existent locations or if the item is not a
904     /// directory (eg files, named pipes, etc). Follows links when making this
905     /// determination.
906     pub fn is_dir(&self) -> bool {
907         match self.stat() {
908             Ok(s) => s.kind == io::TypeDirectory,
909             Err(..) => false
910         }
911     }
912 }
913
914 fn mode_string(mode: FileMode) -> &'static str {
915     match mode {
916         super::Open => "open",
917         super::Append => "append",
918         super::Truncate => "truncate"
919     }
920 }
921
922 fn access_string(access: FileAccess) -> &'static str {
923     match access {
924         super::Read => "read",
925         super::Write => "write",
926         super::ReadWrite => "readwrite"
927     }
928 }
929
930 #[cfg(test)]
931 #[allow(unused_imports)]
932 mod test {
933     use prelude::*;
934     use io::{SeekSet, SeekCur, SeekEnd, Read, Open, ReadWrite};
935     use io;
936     use str;
937     use io::fs::{File, rmdir, mkdir, readdir, rmdir_recursive,
938                  mkdir_recursive, copy, unlink, stat, symlink, link,
939                  readlink, chmod, lstat, change_file_times};
940     use path::Path;
941     use io;
942     use ops::Drop;
943     use str::StrSlice;
944
945     macro_rules! check( ($e:expr) => (
946         match $e {
947             Ok(t) => t,
948             Err(e) => fail!("{} failed with: {}", stringify!($e), e),
949         }
950     ) )
951
952     macro_rules! error( ($e:expr, $s:expr) => (
953         match $e {
954             Ok(val) => fail!("Should have been an error, was {:?}", val),
955             Err(ref err) => assert!(err.to_string().as_slice().contains($s.as_slice()),
956                                     format!("`{}` did not contain `{}`", err, $s))
957         }
958     ) )
959
960     struct TempDir(Path);
961
962     impl TempDir {
963         fn join(&self, path: &str) -> Path {
964             let TempDir(ref p) = *self;
965             p.join(path)
966         }
967
968         fn path<'a>(&'a self) -> &'a Path {
969             let TempDir(ref p) = *self;
970             p
971         }
972     }
973
974     impl Drop for TempDir {
975         fn drop(&mut self) {
976             // Gee, seeing how we're testing the fs module I sure hope that we
977             // at least implement this correctly!
978             let TempDir(ref p) = *self;
979             check!(io::fs::rmdir_recursive(p));
980         }
981     }
982
983     pub fn tmpdir() -> TempDir {
984         use os;
985         use rand;
986         let ret = os::tmpdir().join(format!("rust-{}", rand::random::<u32>()));
987         check!(io::fs::mkdir(&ret, io::UserRWX));
988         TempDir(ret)
989     }
990
991     iotest!(fn file_test_io_smoke_test() {
992         let message = "it's alright. have a good time";
993         let tmpdir = tmpdir();
994         let filename = &tmpdir.join("file_rt_io_file_test.txt");
995         {
996             let mut write_stream = File::open_mode(filename, Open, ReadWrite);
997             check!(write_stream.write(message.as_bytes()));
998         }
999         {
1000             let mut read_stream = File::open_mode(filename, Open, Read);
1001             let mut read_buf = [0, .. 1028];
1002             let read_str = match check!(read_stream.read(read_buf)) {
1003                 -1|0 => fail!("shouldn't happen"),
1004                 n => str::from_utf8(read_buf.slice_to(n)).unwrap().to_string()
1005             };
1006             assert_eq!(read_str.as_slice(), message);
1007         }
1008         check!(unlink(filename));
1009     })
1010
1011     iotest!(fn invalid_path_raises() {
1012         let tmpdir = tmpdir();
1013         let filename = &tmpdir.join("file_that_does_not_exist.txt");
1014         let result = File::open_mode(filename, Open, Read);
1015
1016         error!(result, "couldn't open file");
1017         if cfg!(unix) {
1018             error!(result, "no such file or directory");
1019         }
1020         error!(result, format!("path={}; mode=open; access=read", filename.display()));
1021     })
1022
1023     iotest!(fn file_test_iounlinking_invalid_path_should_raise_condition() {
1024         let tmpdir = tmpdir();
1025         let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1026
1027         let result = unlink(filename);
1028
1029         error!(result, "couldn't unlink path");
1030         if cfg!(unix) {
1031             error!(result, "no such file or directory");
1032         }
1033         error!(result, format!("path={}", filename.display()));
1034     })
1035
1036     iotest!(fn file_test_io_non_positional_read() {
1037         let message: &str = "ten-four";
1038         let mut read_mem = [0, .. 8];
1039         let tmpdir = tmpdir();
1040         let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1041         {
1042             let mut rw_stream = File::open_mode(filename, Open, ReadWrite);
1043             check!(rw_stream.write(message.as_bytes()));
1044         }
1045         {
1046             let mut read_stream = File::open_mode(filename, Open, Read);
1047             {
1048                 let read_buf = read_mem.mut_slice(0, 4);
1049                 check!(read_stream.read(read_buf));
1050             }
1051             {
1052                 let read_buf = read_mem.mut_slice(4, 8);
1053                 check!(read_stream.read(read_buf));
1054             }
1055         }
1056         check!(unlink(filename));
1057         let read_str = str::from_utf8(read_mem).unwrap();
1058         assert_eq!(read_str, message);
1059     })
1060
1061     iotest!(fn file_test_io_seek_and_tell_smoke_test() {
1062         let message = "ten-four";
1063         let mut read_mem = [0, .. 4];
1064         let set_cursor = 4 as u64;
1065         let mut tell_pos_pre_read;
1066         let mut tell_pos_post_read;
1067         let tmpdir = tmpdir();
1068         let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
1069         {
1070             let mut rw_stream = File::open_mode(filename, Open, ReadWrite);
1071             check!(rw_stream.write(message.as_bytes()));
1072         }
1073         {
1074             let mut read_stream = File::open_mode(filename, Open, Read);
1075             check!(read_stream.seek(set_cursor as i64, SeekSet));
1076             tell_pos_pre_read = check!(read_stream.tell());
1077             check!(read_stream.read(read_mem));
1078             tell_pos_post_read = check!(read_stream.tell());
1079         }
1080         check!(unlink(filename));
1081         let read_str = str::from_utf8(read_mem).unwrap();
1082         assert_eq!(read_str, message.slice(4, 8));
1083         assert_eq!(tell_pos_pre_read, set_cursor);
1084         assert_eq!(tell_pos_post_read, message.len() as u64);
1085     })
1086
1087     iotest!(fn file_test_io_seek_and_write() {
1088         let initial_msg =   "food-is-yummy";
1089         let overwrite_msg =    "-the-bar!!";
1090         let final_msg =     "foo-the-bar!!";
1091         let seek_idx = 3i;
1092         let mut read_mem = [0, .. 13];
1093         let tmpdir = tmpdir();
1094         let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
1095         {
1096             let mut rw_stream = File::open_mode(filename, Open, ReadWrite);
1097             check!(rw_stream.write(initial_msg.as_bytes()));
1098             check!(rw_stream.seek(seek_idx as i64, SeekSet));
1099             check!(rw_stream.write(overwrite_msg.as_bytes()));
1100         }
1101         {
1102             let mut read_stream = File::open_mode(filename, Open, Read);
1103             check!(read_stream.read(read_mem));
1104         }
1105         check!(unlink(filename));
1106         let read_str = str::from_utf8(read_mem).unwrap();
1107         assert!(read_str.as_slice() == final_msg.as_slice());
1108     })
1109
1110     iotest!(fn file_test_io_seek_shakedown() {
1111         use str;          // 01234567890123
1112         let initial_msg =   "qwer-asdf-zxcv";
1113         let chunk_one: &str = "qwer";
1114         let chunk_two: &str = "asdf";
1115         let chunk_three: &str = "zxcv";
1116         let mut read_mem = [0, .. 4];
1117         let tmpdir = tmpdir();
1118         let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
1119         {
1120             let mut rw_stream = File::open_mode(filename, Open, ReadWrite);
1121             check!(rw_stream.write(initial_msg.as_bytes()));
1122         }
1123         {
1124             let mut read_stream = File::open_mode(filename, Open, Read);
1125
1126             check!(read_stream.seek(-4, SeekEnd));
1127             check!(read_stream.read(read_mem));
1128             assert_eq!(str::from_utf8(read_mem).unwrap(), chunk_three);
1129
1130             check!(read_stream.seek(-9, SeekCur));
1131             check!(read_stream.read(read_mem));
1132             assert_eq!(str::from_utf8(read_mem).unwrap(), chunk_two);
1133
1134             check!(read_stream.seek(0, SeekSet));
1135             check!(read_stream.read(read_mem));
1136             assert_eq!(str::from_utf8(read_mem).unwrap(), chunk_one);
1137         }
1138         check!(unlink(filename));
1139     })
1140
1141     iotest!(fn file_test_stat_is_correct_on_is_file() {
1142         let tmpdir = tmpdir();
1143         let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
1144         {
1145             let mut fs = check!(File::open_mode(filename, Open, ReadWrite));
1146             let msg = "hw";
1147             fs.write(msg.as_bytes()).unwrap();
1148
1149             let fstat_res = check!(fs.stat());
1150             assert_eq!(fstat_res.kind, io::TypeFile);
1151         }
1152         let stat_res_fn = check!(stat(filename));
1153         assert_eq!(stat_res_fn.kind, io::TypeFile);
1154         let stat_res_meth = check!(filename.stat());
1155         assert_eq!(stat_res_meth.kind, io::TypeFile);
1156         check!(unlink(filename));
1157     })
1158
1159     iotest!(fn file_test_stat_is_correct_on_is_dir() {
1160         let tmpdir = tmpdir();
1161         let filename = &tmpdir.join("file_stat_correct_on_is_dir");
1162         check!(mkdir(filename, io::UserRWX));
1163         let stat_res_fn = check!(stat(filename));
1164         assert!(stat_res_fn.kind == io::TypeDirectory);
1165         let stat_res_meth = check!(filename.stat());
1166         assert!(stat_res_meth.kind == io::TypeDirectory);
1167         check!(rmdir(filename));
1168     })
1169
1170     iotest!(fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1171         let tmpdir = tmpdir();
1172         let dir = &tmpdir.join("fileinfo_false_on_dir");
1173         check!(mkdir(dir, io::UserRWX));
1174         assert!(dir.is_file() == false);
1175         check!(rmdir(dir));
1176     })
1177
1178     iotest!(fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1179         let tmpdir = tmpdir();
1180         let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1181         check!(File::create(file).write(b"foo"));
1182         assert!(file.exists());
1183         check!(unlink(file));
1184         assert!(!file.exists());
1185     })
1186
1187     iotest!(fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1188         let tmpdir = tmpdir();
1189         let dir = &tmpdir.join("before_and_after_dir");
1190         assert!(!dir.exists());
1191         check!(mkdir(dir, io::UserRWX));
1192         assert!(dir.exists());
1193         assert!(dir.is_dir());
1194         check!(rmdir(dir));
1195         assert!(!dir.exists());
1196     })
1197
1198     iotest!(fn file_test_directoryinfo_readdir() {
1199         use str;
1200         let tmpdir = tmpdir();
1201         let dir = &tmpdir.join("di_readdir");
1202         check!(mkdir(dir, io::UserRWX));
1203         let prefix = "foo";
1204         for n in range(0i,3) {
1205             let f = dir.join(format!("{}.txt", n));
1206             let mut w = check!(File::create(&f));
1207             let msg_str = format!("{}{}", prefix, n.to_string());
1208             let msg = msg_str.as_slice().as_bytes();
1209             check!(w.write(msg));
1210         }
1211         let files = check!(readdir(dir));
1212         let mut mem = [0u8, .. 4];
1213         for f in files.iter() {
1214             {
1215                 let n = f.filestem_str();
1216                 check!(File::open(f).read(mem));
1217                 let read_str = str::from_utf8(mem).unwrap();
1218                 let expected = match n {
1219                     None|Some("") => fail!("really shouldn't happen.."),
1220                     Some(n) => format!("{}{}", prefix, n),
1221                 };
1222                 assert_eq!(expected.as_slice(), read_str);
1223             }
1224             check!(unlink(f));
1225         }
1226         check!(rmdir(dir));
1227     })
1228
1229     iotest!(fn file_test_walk_dir() {
1230         let tmpdir = tmpdir();
1231         let dir = &tmpdir.join("walk_dir");
1232         check!(mkdir(dir, io::UserRWX));
1233
1234         let dir1 = &dir.join("01/02/03");
1235         check!(mkdir_recursive(dir1, io::UserRWX));
1236         check!(File::create(&dir1.join("04")));
1237
1238         let dir2 = &dir.join("11/12/13");
1239         check!(mkdir_recursive(dir2, io::UserRWX));
1240         check!(File::create(&dir2.join("14")));
1241
1242         let mut files = check!(walk_dir(dir));
1243         let mut cur = [0u8, .. 2];
1244         for f in files {
1245             let stem = f.filestem_str().unwrap();
1246             let root = stem.as_bytes()[0] - ('0' as u8);
1247             let name = stem.as_bytes()[1] - ('0' as u8);
1248             assert!(cur[root as uint] < name);
1249             cur[root as uint] = name;
1250         }
1251
1252         check!(rmdir_recursive(dir));
1253     })
1254
1255     iotest!(fn recursive_mkdir() {
1256         let tmpdir = tmpdir();
1257         let dir = tmpdir.join("d1/d2");
1258         check!(mkdir_recursive(&dir, io::UserRWX));
1259         assert!(dir.is_dir())
1260     })
1261
1262     iotest!(fn recursive_mkdir_failure() {
1263         let tmpdir = tmpdir();
1264         let dir = tmpdir.join("d1");
1265         let file = dir.join("f1");
1266
1267         check!(mkdir_recursive(&dir, io::UserRWX));
1268         check!(File::create(&file));
1269
1270         let result = mkdir_recursive(&file, io::UserRWX);
1271
1272         error!(result, "couldn't recursively mkdir");
1273         error!(result, "couldn't create directory");
1274         error!(result, "mode=FilePermission { bits: 448 }");
1275         error!(result, format!("path={}", file.display()));
1276     })
1277
1278     iotest!(fn recursive_mkdir_slash() {
1279         check!(mkdir_recursive(&Path::new("/"), io::UserRWX));
1280     })
1281
1282     // FIXME(#12795) depends on lstat to work on windows
1283     #[cfg(not(windows))]
1284     iotest!(fn recursive_rmdir() {
1285         let tmpdir = tmpdir();
1286         let d1 = tmpdir.join("d1");
1287         let dt = d1.join("t");
1288         let dtt = dt.join("t");
1289         let d2 = tmpdir.join("d2");
1290         let canary = d2.join("do_not_delete");
1291         check!(mkdir_recursive(&dtt, io::UserRWX));
1292         check!(mkdir_recursive(&d2, io::UserRWX));
1293         check!(File::create(&canary).write(b"foo"));
1294         check!(symlink(&d2, &dt.join("d2")));
1295         check!(rmdir_recursive(&d1));
1296
1297         assert!(!d1.is_dir());
1298         assert!(canary.exists());
1299     })
1300
1301     iotest!(fn unicode_path_is_dir() {
1302         assert!(Path::new(".").is_dir());
1303         assert!(!Path::new("test/stdtest/fs.rs").is_dir());
1304
1305         let tmpdir = tmpdir();
1306
1307         let mut dirpath = tmpdir.path().clone();
1308         dirpath.push(format!("test-가一ー你好"));
1309         check!(mkdir(&dirpath, io::UserRWX));
1310         assert!(dirpath.is_dir());
1311
1312         let mut filepath = dirpath;
1313         filepath.push("unicode-file-\uac00\u4e00\u30fc\u4f60\u597d.rs");
1314         check!(File::create(&filepath)); // ignore return; touch only
1315         assert!(!filepath.is_dir());
1316         assert!(filepath.exists());
1317     })
1318
1319     iotest!(fn unicode_path_exists() {
1320         assert!(Path::new(".").exists());
1321         assert!(!Path::new("test/nonexistent-bogus-path").exists());
1322
1323         let tmpdir = tmpdir();
1324         let unicode = tmpdir.path();
1325         let unicode = unicode.join(format!("test-각丁ー再见"));
1326         check!(mkdir(&unicode, io::UserRWX));
1327         assert!(unicode.exists());
1328         assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
1329     })
1330
1331     iotest!(fn copy_file_does_not_exist() {
1332         let from = Path::new("test/nonexistent-bogus-path");
1333         let to = Path::new("test/other-bogus-path");
1334
1335         error!(copy(&from, &to),
1336             format!("couldn't copy path (the source path is not an \
1337                     existing file; from={}; to={})",
1338                     from.display(), to.display()));
1339
1340         match copy(&from, &to) {
1341             Ok(..) => fail!(),
1342             Err(..) => {
1343                 assert!(!from.exists());
1344                 assert!(!to.exists());
1345             }
1346         }
1347     })
1348
1349     iotest!(fn copy_file_ok() {
1350         let tmpdir = tmpdir();
1351         let input = tmpdir.join("in.txt");
1352         let out = tmpdir.join("out.txt");
1353
1354         check!(File::create(&input).write(b"hello"));
1355         check!(copy(&input, &out));
1356         let contents = check!(File::open(&out).read_to_end());
1357         assert_eq!(contents.as_slice(), b"hello");
1358
1359         assert_eq!(check!(input.stat()).perm, check!(out.stat()).perm);
1360     })
1361
1362     iotest!(fn copy_file_dst_dir() {
1363         let tmpdir = tmpdir();
1364         let out = tmpdir.join("out");
1365
1366         check!(File::create(&out));
1367         match copy(&out, tmpdir.path()) {
1368             Ok(..) => fail!(), Err(..) => {}
1369         }
1370     })
1371
1372     iotest!(fn copy_file_dst_exists() {
1373         let tmpdir = tmpdir();
1374         let input = tmpdir.join("in");
1375         let output = tmpdir.join("out");
1376
1377         check!(File::create(&input).write("foo".as_bytes()));
1378         check!(File::create(&output).write("bar".as_bytes()));
1379         check!(copy(&input, &output));
1380
1381         assert_eq!(check!(File::open(&output).read_to_end()),
1382                    (Vec::from_slice(b"foo")));
1383     })
1384
1385     iotest!(fn copy_file_src_dir() {
1386         let tmpdir = tmpdir();
1387         let out = tmpdir.join("out");
1388
1389         match copy(tmpdir.path(), &out) {
1390             Ok(..) => fail!(), Err(..) => {}
1391         }
1392         assert!(!out.exists());
1393     })
1394
1395     iotest!(fn copy_file_preserves_perm_bits() {
1396         let tmpdir = tmpdir();
1397         let input = tmpdir.join("in.txt");
1398         let out = tmpdir.join("out.txt");
1399
1400         check!(File::create(&input));
1401         check!(chmod(&input, io::UserRead));
1402         check!(copy(&input, &out));
1403         assert!(!check!(out.stat()).perm.intersects(io::UserWrite));
1404
1405         check!(chmod(&input, io::UserFile));
1406         check!(chmod(&out, io::UserFile));
1407     })
1408
1409     #[cfg(not(windows))] // FIXME(#10264) operation not permitted?
1410     iotest!(fn symlinks_work() {
1411         let tmpdir = tmpdir();
1412         let input = tmpdir.join("in.txt");
1413         let out = tmpdir.join("out.txt");
1414
1415         check!(File::create(&input).write("foobar".as_bytes()));
1416         check!(symlink(&input, &out));
1417         if cfg!(not(windows)) {
1418             assert_eq!(check!(lstat(&out)).kind, io::TypeSymlink);
1419             assert_eq!(check!(out.lstat()).kind, io::TypeSymlink);
1420         }
1421         assert_eq!(check!(stat(&out)).size, check!(stat(&input)).size);
1422         assert_eq!(check!(File::open(&out).read_to_end()),
1423                    (Vec::from_slice(b"foobar")));
1424     })
1425
1426     #[cfg(not(windows))] // apparently windows doesn't like symlinks
1427     iotest!(fn symlink_noexist() {
1428         let tmpdir = tmpdir();
1429         // symlinks can point to things that don't exist
1430         check!(symlink(&tmpdir.join("foo"), &tmpdir.join("bar")));
1431         assert!(check!(readlink(&tmpdir.join("bar"))) == tmpdir.join("foo"));
1432     })
1433
1434     iotest!(fn readlink_not_symlink() {
1435         let tmpdir = tmpdir();
1436         match readlink(tmpdir.path()) {
1437             Ok(..) => fail!("wanted a failure"),
1438             Err(..) => {}
1439         }
1440     })
1441
1442     iotest!(fn links_work() {
1443         let tmpdir = tmpdir();
1444         let input = tmpdir.join("in.txt");
1445         let out = tmpdir.join("out.txt");
1446
1447         check!(File::create(&input).write("foobar".as_bytes()));
1448         check!(link(&input, &out));
1449         if cfg!(not(windows)) {
1450             assert_eq!(check!(lstat(&out)).kind, io::TypeFile);
1451             assert_eq!(check!(out.lstat()).kind, io::TypeFile);
1452             assert_eq!(check!(stat(&out)).unstable.nlink, 2);
1453             assert_eq!(check!(out.stat()).unstable.nlink, 2);
1454         }
1455         assert_eq!(check!(stat(&out)).size, check!(stat(&input)).size);
1456         assert_eq!(check!(stat(&out)).size, check!(input.stat()).size);
1457         assert_eq!(check!(File::open(&out).read_to_end()),
1458                    (Vec::from_slice(b"foobar")));
1459
1460         // can't link to yourself
1461         match link(&input, &input) {
1462             Ok(..) => fail!("wanted a failure"),
1463             Err(..) => {}
1464         }
1465         // can't link to something that doesn't exist
1466         match link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
1467             Ok(..) => fail!("wanted a failure"),
1468             Err(..) => {}
1469         }
1470     })
1471
1472     iotest!(fn chmod_works() {
1473         let tmpdir = tmpdir();
1474         let file = tmpdir.join("in.txt");
1475
1476         check!(File::create(&file));
1477         assert!(check!(stat(&file)).perm.contains(io::UserWrite));
1478         check!(chmod(&file, io::UserRead));
1479         assert!(!check!(stat(&file)).perm.contains(io::UserWrite));
1480
1481         match chmod(&tmpdir.join("foo"), io::UserRWX) {
1482             Ok(..) => fail!("wanted a failure"),
1483             Err(..) => {}
1484         }
1485
1486         check!(chmod(&file, io::UserFile));
1487     })
1488
1489     iotest!(fn sync_doesnt_kill_anything() {
1490         let tmpdir = tmpdir();
1491         let path = tmpdir.join("in.txt");
1492
1493         let mut file = check!(File::open_mode(&path, io::Open, io::ReadWrite));
1494         check!(file.fsync());
1495         check!(file.datasync());
1496         check!(file.write(b"foo"));
1497         check!(file.fsync());
1498         check!(file.datasync());
1499         drop(file);
1500     })
1501
1502     iotest!(fn truncate_works() {
1503         let tmpdir = tmpdir();
1504         let path = tmpdir.join("in.txt");
1505
1506         let mut file = check!(File::open_mode(&path, io::Open, io::ReadWrite));
1507         check!(file.write(b"foo"));
1508         check!(file.fsync());
1509
1510         // Do some simple things with truncation
1511         assert_eq!(check!(file.stat()).size, 3);
1512         check!(file.truncate(10));
1513         assert_eq!(check!(file.stat()).size, 10);
1514         check!(file.write(b"bar"));
1515         check!(file.fsync());
1516         assert_eq!(check!(file.stat()).size, 10);
1517         assert_eq!(check!(File::open(&path).read_to_end()),
1518                    (Vec::from_slice(b"foobar\0\0\0\0")));
1519
1520         // Truncate to a smaller length, don't seek, and then write something.
1521         // Ensure that the intermediate zeroes are all filled in (we're seeked
1522         // past the end of the file).
1523         check!(file.truncate(2));
1524         assert_eq!(check!(file.stat()).size, 2);
1525         check!(file.write(b"wut"));
1526         check!(file.fsync());
1527         assert_eq!(check!(file.stat()).size, 9);
1528         assert_eq!(check!(File::open(&path).read_to_end()),
1529                    (Vec::from_slice(b"fo\0\0\0\0wut")));
1530         drop(file);
1531     })
1532
1533     iotest!(fn open_flavors() {
1534         let tmpdir = tmpdir();
1535
1536         match File::open_mode(&tmpdir.join("a"), io::Open, io::Read) {
1537             Ok(..) => fail!(), Err(..) => {}
1538         }
1539
1540         // Perform each one twice to make sure that it succeeds the second time
1541         // (where the file exists)
1542         check!(File::open_mode(&tmpdir.join("b"), io::Open, io::Write));
1543         assert!(tmpdir.join("b").exists());
1544         check!(File::open_mode(&tmpdir.join("b"), io::Open, io::Write));
1545
1546         check!(File::open_mode(&tmpdir.join("c"), io::Open, io::ReadWrite));
1547         assert!(tmpdir.join("c").exists());
1548         check!(File::open_mode(&tmpdir.join("c"), io::Open, io::ReadWrite));
1549
1550         check!(File::open_mode(&tmpdir.join("d"), io::Append, io::Write));
1551         assert!(tmpdir.join("d").exists());
1552         check!(File::open_mode(&tmpdir.join("d"), io::Append, io::Write));
1553
1554         check!(File::open_mode(&tmpdir.join("e"), io::Append, io::ReadWrite));
1555         assert!(tmpdir.join("e").exists());
1556         check!(File::open_mode(&tmpdir.join("e"), io::Append, io::ReadWrite));
1557
1558         check!(File::open_mode(&tmpdir.join("f"), io::Truncate, io::Write));
1559         assert!(tmpdir.join("f").exists());
1560         check!(File::open_mode(&tmpdir.join("f"), io::Truncate, io::Write));
1561
1562         check!(File::open_mode(&tmpdir.join("g"), io::Truncate, io::ReadWrite));
1563         assert!(tmpdir.join("g").exists());
1564         check!(File::open_mode(&tmpdir.join("g"), io::Truncate, io::ReadWrite));
1565
1566         check!(File::create(&tmpdir.join("h")).write("foo".as_bytes()));
1567         check!(File::open_mode(&tmpdir.join("h"), io::Open, io::Read));
1568         {
1569             let mut f = check!(File::open_mode(&tmpdir.join("h"), io::Open,
1570                                                io::Read));
1571             match f.write("wut".as_bytes()) {
1572                 Ok(..) => fail!(), Err(..) => {}
1573             }
1574         }
1575         assert!(check!(stat(&tmpdir.join("h"))).size == 3,
1576                 "write/stat failed");
1577         {
1578             let mut f = check!(File::open_mode(&tmpdir.join("h"), io::Append,
1579                                                io::Write));
1580             check!(f.write("bar".as_bytes()));
1581         }
1582         assert!(check!(stat(&tmpdir.join("h"))).size == 6,
1583                 "append didn't append");
1584         {
1585             let mut f = check!(File::open_mode(&tmpdir.join("h"), io::Truncate,
1586                                                io::Write));
1587             check!(f.write("bar".as_bytes()));
1588         }
1589         assert!(check!(stat(&tmpdir.join("h"))).size == 3,
1590                 "truncate didn't truncate");
1591     })
1592
1593     #[test]
1594     fn utime() {
1595         let tmpdir = tmpdir();
1596         let path = tmpdir.join("a");
1597         check!(File::create(&path));
1598
1599         check!(change_file_times(&path, 1000, 2000));
1600         assert_eq!(check!(path.stat()).accessed, 1000);
1601         assert_eq!(check!(path.stat()).modified, 2000);
1602     }
1603
1604     #[test]
1605     fn utime_noexist() {
1606         let tmpdir = tmpdir();
1607
1608         match change_file_times(&tmpdir.join("a"), 100, 200) {
1609             Ok(..) => fail!(),
1610             Err(..) => {}
1611         }
1612     }
1613
1614     iotest!(fn binary_file() {
1615         use rand::{StdRng, Rng};
1616
1617         let mut bytes = [0, ..1024];
1618         StdRng::new().ok().unwrap().fill_bytes(bytes);
1619
1620         let tmpdir = tmpdir();
1621
1622         check!(File::create(&tmpdir.join("test")).write(bytes));
1623         let actual = check!(File::open(&tmpdir.join("test")).read_to_end());
1624         assert!(actual.as_slice() == bytes);
1625     })
1626
1627     iotest!(fn unlink_readonly() {
1628         let tmpdir = tmpdir();
1629         let path = tmpdir.join("file");
1630         check!(File::create(&path));
1631         check!(chmod(&path, io::UserRead));
1632         check!(unlink(&path));
1633     })
1634 }