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