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