]> git.lizzy.rs Git - rust.git/blob - src/libstd/fs.rs
Auto merge of #30130 - tbu-:pr_array_clone, r=alexcrichton
[rust.git] / src / libstd / fs.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 #![stable(feature = "rust1", since = "1.0.0")]
19
20 use fmt;
21 use ffi::OsString;
22 use io::{self, SeekFrom, Seek, Read, Write};
23 use path::{Path, PathBuf};
24 use sys::fs as fs_imp;
25 use sys_common::io::read_to_end_uninitialized;
26 use sys_common::{AsInnerMut, FromInner, AsInner, IntoInner};
27 use vec::Vec;
28
29 /// A reference to an open file on the filesystem.
30 ///
31 /// An instance of a `File` can be read and/or written depending on what options
32 /// it was opened with. Files also implement `Seek` to alter the logical cursor
33 /// that the file contains internally.
34 ///
35 /// # Examples
36 ///
37 /// ```no_run
38 /// use std::io::prelude::*;
39 /// use std::fs::File;
40 ///
41 /// # fn foo() -> std::io::Result<()> {
42 /// let mut f = try!(File::create("foo.txt"));
43 /// try!(f.write_all(b"Hello, world!"));
44 ///
45 /// let mut f = try!(File::open("foo.txt"));
46 /// let mut s = String::new();
47 /// try!(f.read_to_string(&mut s));
48 /// assert_eq!(s, "Hello, world!");
49 /// # Ok(())
50 /// # }
51 /// ```
52 #[stable(feature = "rust1", since = "1.0.0")]
53 pub struct File {
54     inner: fs_imp::File,
55 }
56
57 /// Metadata information about a file.
58 ///
59 /// This structure is returned from the `metadata` function or method and
60 /// represents known metadata about a file such as its permissions, size,
61 /// modification times, etc.
62 #[stable(feature = "rust1", since = "1.0.0")]
63 #[derive(Clone)]
64 pub struct Metadata(fs_imp::FileAttr);
65
66 /// Iterator over the entries in a directory.
67 ///
68 /// This iterator is returned from the `read_dir` function of this module and
69 /// will yield instances of `io::Result<DirEntry>`. Through a `DirEntry`
70 /// information like the entry's path and possibly other metadata can be
71 /// learned.
72 ///
73 /// # Failure
74 ///
75 /// This `io::Result` will be an `Err` if there's some sort of intermittent
76 /// IO error during iteration.
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub struct ReadDir(fs_imp::ReadDir);
79
80 /// Entries returned by the `ReadDir` iterator.
81 ///
82 /// An instance of `DirEntry` represents an entry inside of a directory on the
83 /// filesystem. Each entry can be inspected via methods to learn about the full
84 /// path or possibly other metadata through per-platform extension traits.
85 #[stable(feature = "rust1", since = "1.0.0")]
86 pub struct DirEntry(fs_imp::DirEntry);
87
88 /// An iterator that recursively walks over the contents of a directory.
89 #[unstable(feature = "fs_walk",
90            reason = "the precise semantics and defaults for a recursive walk \
91                      may change and this may end up accounting for files such \
92                      as symlinks differently",
93            issue = "27707")]
94 pub struct WalkDir {
95     cur: Option<ReadDir>,
96     stack: Vec<io::Result<ReadDir>>,
97 }
98
99 /// Options and flags which can be used to configure how a file is opened.
100 ///
101 /// This builder exposes the ability to configure how a `File` is opened and
102 /// what operations are permitted on the open file. The `File::open` and
103 /// `File::create` methods are aliases for commonly used options using this
104 /// builder.
105 ///
106 /// Generally speaking, when using `OpenOptions`, you'll first call `new()`,
107 /// then chain calls to methods to set each option, then call `open()`, passing
108 /// the path of the file you're trying to open. This will give you a
109 /// [`io::Result`][result] with a [`File`][file] inside that you can further
110 /// operate on.
111 ///
112 /// [result]: ../io/type.Result.html
113 /// [file]: struct.File.html
114 ///
115 /// # Examples
116 ///
117 /// Opening a file to read:
118 ///
119 /// ```no_run
120 /// use std::fs::OpenOptions;
121 ///
122 /// let file = OpenOptions::new().read(true).open("foo.txt");
123 /// ```
124 ///
125 /// Opening a file for both reading and writing, as well as creating it if it
126 /// doesn't exist:
127 ///
128 /// ```no_run
129 /// use std::fs::OpenOptions;
130 ///
131 /// let file = OpenOptions::new()
132 ///             .read(true)
133 ///             .write(true)
134 ///             .create(true)
135 ///             .open("foo.txt");
136 /// ```
137 #[derive(Clone)]
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub struct OpenOptions(fs_imp::OpenOptions);
140
141 /// Representation of the various permissions on a file.
142 ///
143 /// This module only currently provides one bit of information, `readonly`,
144 /// which is exposed on all currently supported platforms. Unix-specific
145 /// functionality, such as mode bits, is available through the
146 /// `os::unix::PermissionsExt` trait.
147 #[derive(Clone, PartialEq, Eq, Debug)]
148 #[stable(feature = "rust1", since = "1.0.0")]
149 pub struct Permissions(fs_imp::FilePermissions);
150
151 /// An structure representing a type of file with accessors for each file type.
152 #[stable(feature = "file_type", since = "1.1.0")]
153 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
154 pub struct FileType(fs_imp::FileType);
155
156 /// A builder used to create directories in various manners.
157 ///
158 /// This builder also supports platform-specific options.
159 #[unstable(feature = "dir_builder", reason = "recently added API",
160            issue = "27710")]
161 pub struct DirBuilder {
162     inner: fs_imp::DirBuilder,
163     recursive: bool,
164 }
165
166 impl File {
167     /// Attempts to open a file in read-only mode.
168     ///
169     /// See the `OpenOptions::open` method for more details.
170     ///
171     /// # Errors
172     ///
173     /// This function will return an error if `path` does not already exist.
174     /// Other errors may also be returned according to `OpenOptions::open`.
175     ///
176     /// # Examples
177     ///
178     /// ```no_run
179     /// use std::fs::File;
180     ///
181     /// # fn foo() -> std::io::Result<()> {
182     /// let mut f = try!(File::open("foo.txt"));
183     /// # Ok(())
184     /// # }
185     /// ```
186     #[stable(feature = "rust1", since = "1.0.0")]
187     pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
188         OpenOptions::new().read(true).open(path.as_ref())
189     }
190
191     /// Opens a file in write-only mode.
192     ///
193     /// This function will create a file if it does not exist,
194     /// and will truncate it if it does.
195     ///
196     /// See the `OpenOptions::open` function for more details.
197     ///
198     /// # Examples
199     ///
200     /// ```no_run
201     /// use std::fs::File;
202     ///
203     /// # fn foo() -> std::io::Result<()> {
204     /// let mut f = try!(File::create("foo.txt"));
205     /// # Ok(())
206     /// # }
207     /// ```
208     #[stable(feature = "rust1", since = "1.0.0")]
209     pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
210         OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
211     }
212
213     /// Attempts to sync all OS-internal metadata to disk.
214     ///
215     /// This function will attempt to ensure that all in-core data reaches the
216     /// filesystem before returning.
217     ///
218     /// # Examples
219     ///
220     /// ```no_run
221     /// use std::fs::File;
222     /// use std::io::prelude::*;
223     ///
224     /// # fn foo() -> std::io::Result<()> {
225     /// let mut f = try!(File::create("foo.txt"));
226     /// try!(f.write_all(b"Hello, world!"));
227     ///
228     /// try!(f.sync_all());
229     /// # Ok(())
230     /// # }
231     /// ```
232     #[stable(feature = "rust1", since = "1.0.0")]
233     pub fn sync_all(&self) -> io::Result<()> {
234         self.inner.fsync()
235     }
236
237     /// This function is similar to `sync_all`, except that it may not
238     /// synchronize file metadata to the filesystem.
239     ///
240     /// This is intended for use cases that must synchronize content, but don't
241     /// need the metadata on disk. The goal of this method is to reduce disk
242     /// operations.
243     ///
244     /// Note that some platforms may simply implement this in terms of
245     /// `sync_all`.
246     ///
247     /// # Examples
248     ///
249     /// ```no_run
250     /// use std::fs::File;
251     /// use std::io::prelude::*;
252     ///
253     /// # fn foo() -> std::io::Result<()> {
254     /// let mut f = try!(File::create("foo.txt"));
255     /// try!(f.write_all(b"Hello, world!"));
256     ///
257     /// try!(f.sync_data());
258     /// # Ok(())
259     /// # }
260     /// ```
261     #[stable(feature = "rust1", since = "1.0.0")]
262     pub fn sync_data(&self) -> io::Result<()> {
263         self.inner.datasync()
264     }
265
266     /// Truncates or extends the underlying file, updating the size of
267     /// this file to become `size`.
268     ///
269     /// If the `size` is less than the current file's size, then the file will
270     /// be shrunk. If it is greater than the current file's size, then the file
271     /// will be extended to `size` and have all of the intermediate data filled
272     /// in with 0s.
273     ///
274     /// # Errors
275     ///
276     /// This function will return an error if the file is not opened for writing.
277     ///
278     /// # Examples
279     ///
280     /// ```no_run
281     /// use std::fs::File;
282     ///
283     /// # fn foo() -> std::io::Result<()> {
284     /// let mut f = try!(File::create("foo.txt"));
285     /// try!(f.set_len(10));
286     /// # Ok(())
287     /// # }
288     /// ```
289     #[stable(feature = "rust1", since = "1.0.0")]
290     pub fn set_len(&self, size: u64) -> io::Result<()> {
291         self.inner.truncate(size)
292     }
293
294     /// Queries metadata about the underlying file.
295     ///
296     /// # Examples
297     ///
298     /// ```no_run
299     /// use std::fs::File;
300     ///
301     /// # fn foo() -> std::io::Result<()> {
302     /// let mut f = try!(File::open("foo.txt"));
303     /// let metadata = try!(f.metadata());
304     /// # Ok(())
305     /// # }
306     /// ```
307     #[stable(feature = "rust1", since = "1.0.0")]
308     pub fn metadata(&self) -> io::Result<Metadata> {
309         self.inner.file_attr().map(Metadata)
310     }
311 }
312
313 impl AsInner<fs_imp::File> for File {
314     fn as_inner(&self) -> &fs_imp::File { &self.inner }
315 }
316 impl FromInner<fs_imp::File> for File {
317     fn from_inner(f: fs_imp::File) -> File {
318         File { inner: f }
319     }
320 }
321 impl IntoInner<fs_imp::File> for File {
322     fn into_inner(self) -> fs_imp::File {
323         self.inner
324     }
325 }
326
327 #[stable(feature = "rust1", since = "1.0.0")]
328 impl fmt::Debug for File {
329     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
330         self.inner.fmt(f)
331     }
332 }
333
334 #[stable(feature = "rust1", since = "1.0.0")]
335 impl Read for File {
336     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
337         self.inner.read(buf)
338     }
339     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
340         unsafe { read_to_end_uninitialized(self, buf) }
341     }
342 }
343 #[stable(feature = "rust1", since = "1.0.0")]
344 impl Write for File {
345     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
346         self.inner.write(buf)
347     }
348     fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
349 }
350 #[stable(feature = "rust1", since = "1.0.0")]
351 impl Seek for File {
352     fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
353         self.inner.seek(pos)
354     }
355 }
356 #[stable(feature = "rust1", since = "1.0.0")]
357 impl<'a> Read for &'a File {
358     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
359         self.inner.read(buf)
360     }
361 }
362 #[stable(feature = "rust1", since = "1.0.0")]
363 impl<'a> Write for &'a File {
364     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
365         self.inner.write(buf)
366     }
367     fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
368 }
369 #[stable(feature = "rust1", since = "1.0.0")]
370 impl<'a> Seek for &'a File {
371     fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
372         self.inner.seek(pos)
373     }
374 }
375
376 impl OpenOptions {
377     /// Creates a blank net set of options ready for configuration.
378     ///
379     /// All options are initially set to `false`.
380     ///
381     /// # Examples
382     ///
383     /// ```no_run
384     /// use std::fs::OpenOptions;
385     ///
386     /// let file = OpenOptions::new().open("foo.txt");
387     /// ```
388     #[stable(feature = "rust1", since = "1.0.0")]
389     pub fn new() -> OpenOptions {
390         OpenOptions(fs_imp::OpenOptions::new())
391     }
392
393     /// Sets the option for read access.
394     ///
395     /// This option, when true, will indicate that the file should be
396     /// `read`-able if opened.
397     ///
398     /// # Examples
399     ///
400     /// ```no_run
401     /// use std::fs::OpenOptions;
402     ///
403     /// let file = OpenOptions::new().read(true).open("foo.txt");
404     /// ```
405     #[stable(feature = "rust1", since = "1.0.0")]
406     pub fn read(&mut self, read: bool) -> &mut OpenOptions {
407         self.0.read(read); self
408     }
409
410     /// Sets the option for write access.
411     ///
412     /// This option, when true, will indicate that the file should be
413     /// `write`-able if opened.
414     ///
415     /// # Examples
416     ///
417     /// ```no_run
418     /// use std::fs::OpenOptions;
419     ///
420     /// let file = OpenOptions::new().write(true).open("foo.txt");
421     /// ```
422     #[stable(feature = "rust1", since = "1.0.0")]
423     pub fn write(&mut self, write: bool) -> &mut OpenOptions {
424         self.0.write(write); self
425     }
426
427     /// Sets the option for the append mode.
428     ///
429     /// This option, when true, means that writes will append to a file instead
430     /// of overwriting previous contents.
431     ///
432     /// # Examples
433     ///
434     /// ```no_run
435     /// use std::fs::OpenOptions;
436     ///
437     /// let file = OpenOptions::new().write(true).append(true).open("foo.txt");
438     /// ```
439     #[stable(feature = "rust1", since = "1.0.0")]
440     pub fn append(&mut self, append: bool) -> &mut OpenOptions {
441         self.0.append(append); self
442     }
443
444     /// Sets the option for truncating a previous file.
445     ///
446     /// If a file is successfully opened with this option set it will truncate
447     /// the file to 0 length if it already exists.
448     ///
449     /// # Examples
450     ///
451     /// ```no_run
452     /// use std::fs::OpenOptions;
453     ///
454     /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
455     /// ```
456     #[stable(feature = "rust1", since = "1.0.0")]
457     pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
458         self.0.truncate(truncate); self
459     }
460
461     /// Sets the option for creating a new file.
462     ///
463     /// This option indicates whether a new file will be created if the file
464     /// does not yet already exist.
465     ///
466     /// # Examples
467     ///
468     /// ```no_run
469     /// use std::fs::OpenOptions;
470     ///
471     /// let file = OpenOptions::new().create(true).open("foo.txt");
472     /// ```
473     #[stable(feature = "rust1", since = "1.0.0")]
474     pub fn create(&mut self, create: bool) -> &mut OpenOptions {
475         self.0.create(create); self
476     }
477
478     /// Opens a file at `path` with the options specified by `self`.
479     ///
480     /// # Errors
481     ///
482     /// This function will return an error under a number of different
483     /// circumstances, to include but not limited to:
484     ///
485     /// * Opening a file that does not exist with read access.
486     /// * Attempting to open a file with access that the user lacks
487     ///   permissions for
488     /// * Filesystem-level errors (full disk, etc)
489     ///
490     /// # Examples
491     ///
492     /// ```no_run
493     /// use std::fs::OpenOptions;
494     ///
495     /// let file = OpenOptions::new().open("foo.txt");
496     /// ```
497     #[stable(feature = "rust1", since = "1.0.0")]
498     pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
499         self._open(path.as_ref())
500     }
501
502     fn _open(&self, path: &Path) -> io::Result<File> {
503         let inner = try!(fs_imp::File::open(path, &self.0));
504         Ok(File { inner: inner })
505     }
506 }
507
508 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
509     fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
510 }
511
512 impl Metadata {
513     /// Returns the file type for this metadata.
514     #[stable(feature = "file_type", since = "1.1.0")]
515     pub fn file_type(&self) -> FileType {
516         FileType(self.0.file_type())
517     }
518
519     /// Returns whether this metadata is for a directory.
520     ///
521     /// # Examples
522     ///
523     /// ```
524     /// # fn foo() -> std::io::Result<()> {
525     /// use std::fs;
526     ///
527     /// let metadata = try!(fs::metadata("foo.txt"));
528     ///
529     /// assert!(!metadata.is_dir());
530     /// # Ok(())
531     /// # }
532     /// ```
533     #[stable(feature = "rust1", since = "1.0.0")]
534     pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
535
536     /// Returns whether this metadata is for a regular file.
537     ///
538     /// # Examples
539     ///
540     /// ```
541     /// # fn foo() -> std::io::Result<()> {
542     /// use std::fs;
543     ///
544     /// let metadata = try!(fs::metadata("foo.txt"));
545     ///
546     /// assert!(metadata.is_file());
547     /// # Ok(())
548     /// # }
549     /// ```
550     #[stable(feature = "rust1", since = "1.0.0")]
551     pub fn is_file(&self) -> bool { self.file_type().is_file() }
552
553     /// Returns the size of the file, in bytes, this metadata is for.
554     ///
555     /// # Examples
556     ///
557     /// ```
558     /// # fn foo() -> std::io::Result<()> {
559     /// use std::fs;
560     ///
561     /// let metadata = try!(fs::metadata("foo.txt"));
562     ///
563     /// assert_eq!(0, metadata.len());
564     /// # Ok(())
565     /// # }
566     /// ```
567     #[stable(feature = "rust1", since = "1.0.0")]
568     pub fn len(&self) -> u64 { self.0.size() }
569
570     /// Returns the permissions of the file this metadata is for.
571     ///
572     /// # Examples
573     ///
574     /// ```
575     /// # fn foo() -> std::io::Result<()> {
576     /// use std::fs;
577     ///
578     /// let metadata = try!(fs::metadata("foo.txt"));
579     ///
580     /// assert!(!metadata.permissions().readonly());
581     /// # Ok(())
582     /// # }
583     /// ```
584     #[stable(feature = "rust1", since = "1.0.0")]
585     pub fn permissions(&self) -> Permissions {
586         Permissions(self.0.perm())
587     }
588 }
589
590 impl AsInner<fs_imp::FileAttr> for Metadata {
591     fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
592 }
593
594 impl Permissions {
595     /// Returns whether these permissions describe a readonly file.
596     ///
597     /// # Examples
598     ///
599     /// ```
600     /// use std::fs::File;
601     ///
602     /// # fn foo() -> std::io::Result<()> {
603     /// let mut f = try!(File::create("foo.txt"));
604     /// let metadata = try!(f.metadata());
605     ///
606     /// assert_eq!(false, metadata.permissions().readonly());
607     /// # Ok(())
608     /// # }
609     /// ```
610     #[stable(feature = "rust1", since = "1.0.0")]
611     pub fn readonly(&self) -> bool { self.0.readonly() }
612
613     /// Modifies the readonly flag for this set of permissions.
614     ///
615     /// This operation does **not** modify the filesystem. To modify the
616     /// filesystem use the `fs::set_permissions` function.
617     ///
618     /// # Examples
619     ///
620     /// ```
621     /// use std::fs::File;
622     ///
623     /// # fn foo() -> std::io::Result<()> {
624     /// let f = try!(File::create("foo.txt"));
625     /// let metadata = try!(f.metadata());
626     /// let mut permissions = metadata.permissions();
627     ///
628     /// permissions.set_readonly(true);
629     ///
630     /// // filesystem doesn't change
631     /// assert_eq!(false, metadata.permissions().readonly());
632     ///
633     /// // just this particular `permissions`.
634     /// assert_eq!(true, permissions.readonly());
635     /// # Ok(())
636     /// # }
637     /// ```
638     #[stable(feature = "rust1", since = "1.0.0")]
639     pub fn set_readonly(&mut self, readonly: bool) {
640         self.0.set_readonly(readonly)
641     }
642 }
643
644 impl FileType {
645     /// Test whether this file type represents a directory.
646     #[stable(feature = "file_type", since = "1.1.0")]
647     pub fn is_dir(&self) -> bool { self.0.is_dir() }
648
649     /// Test whether this file type represents a regular file.
650     #[stable(feature = "file_type", since = "1.1.0")]
651     pub fn is_file(&self) -> bool { self.0.is_file() }
652
653     /// Test whether this file type represents a symbolic link.
654     #[stable(feature = "file_type", since = "1.1.0")]
655     pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
656 }
657
658 impl AsInner<fs_imp::FileType> for FileType {
659     fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
660 }
661
662 impl FromInner<fs_imp::FilePermissions> for Permissions {
663     fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
664         Permissions(f)
665     }
666 }
667
668 impl AsInner<fs_imp::FilePermissions> for Permissions {
669     fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
670 }
671
672 #[stable(feature = "rust1", since = "1.0.0")]
673 impl Iterator for ReadDir {
674     type Item = io::Result<DirEntry>;
675
676     fn next(&mut self) -> Option<io::Result<DirEntry>> {
677         self.0.next().map(|entry| entry.map(DirEntry))
678     }
679 }
680
681 impl DirEntry {
682     /// Returns the full path to the file that this entry represents.
683     ///
684     /// The full path is created by joining the original path to `read_dir` or
685     /// `walk_dir` with the filename of this entry.
686     ///
687     /// # Examples
688     ///
689     /// ```
690     /// use std::fs;
691     /// # fn foo() -> std::io::Result<()> {
692     /// for entry in try!(fs::read_dir(".")) {
693     ///     let dir = try!(entry);
694     ///     println!("{:?}", dir.path());
695     /// }
696     /// # Ok(())
697     /// # }
698     /// ```
699     ///
700     /// This prints output like:
701     ///
702     /// ```text
703     /// "./whatever.txt"
704     /// "./foo.html"
705     /// "./hello_world.rs"
706     /// ```
707     ///
708     /// The exact text, of course, depends on what files you have in `.`.
709     #[stable(feature = "rust1", since = "1.0.0")]
710     pub fn path(&self) -> PathBuf { self.0.path() }
711
712     /// Return the metadata for the file that this entry points at.
713     ///
714     /// This function will not traverse symlinks if this entry points at a
715     /// symlink.
716     ///
717     /// # Platform behavior
718     ///
719     /// On Windows this function is cheap to call (no extra system calls
720     /// needed), but on Unix platforms this function is the equivalent of
721     /// calling `symlink_metadata` on the path.
722     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
723     pub fn metadata(&self) -> io::Result<Metadata> {
724         self.0.metadata().map(Metadata)
725     }
726
727     /// Return the file type for the file that this entry points at.
728     ///
729     /// This function will not traverse symlinks if this entry points at a
730     /// symlink.
731     ///
732     /// # Platform behavior
733     ///
734     /// On Windows and most Unix platforms this function is free (no extra
735     /// system calls needed), but some Unix platforms may require the equivalent
736     /// call to `symlink_metadata` to learn about the target file type.
737     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
738     pub fn file_type(&self) -> io::Result<FileType> {
739         self.0.file_type().map(FileType)
740     }
741
742     /// Returns the bare file name of this directory entry without any other
743     /// leading path component.
744     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
745     pub fn file_name(&self) -> OsString {
746         self.0.file_name()
747     }
748 }
749
750 impl AsInner<fs_imp::DirEntry> for DirEntry {
751     fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
752 }
753
754 /// Removes a file from the filesystem.
755 ///
756 /// Note that there is no
757 /// guarantee that the file is immediately deleted (e.g. depending on
758 /// platform, other open file descriptors may prevent immediate removal).
759 ///
760 /// # Errors
761 ///
762 /// This function will return an error if `path` points to a directory, if the
763 /// user lacks permissions to remove the file, or if some other filesystem-level
764 /// error occurs.
765 ///
766 /// # Examples
767 ///
768 /// ```
769 /// use std::fs;
770 ///
771 /// # fn foo() -> std::io::Result<()> {
772 /// try!(fs::remove_file("a.txt"));
773 /// # Ok(())
774 /// # }
775 /// ```
776 #[stable(feature = "rust1", since = "1.0.0")]
777 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
778     fs_imp::unlink(path.as_ref())
779 }
780
781 /// Given a path, query the file system to get information about a file,
782 /// directory, etc.
783 ///
784 /// This function will traverse symbolic links to query information about the
785 /// destination file.
786 ///
787 /// # Examples
788 ///
789 /// ```rust
790 /// # fn foo() -> std::io::Result<()> {
791 /// use std::fs;
792 ///
793 /// let attr = try!(fs::metadata("/some/file/path.txt"));
794 /// // inspect attr ...
795 /// # Ok(())
796 /// # }
797 /// ```
798 ///
799 /// # Errors
800 ///
801 /// This function will return an error if the user lacks the requisite
802 /// permissions to perform a `metadata` call on the given `path` or if there
803 /// is no entry in the filesystem at the provided path.
804 #[stable(feature = "rust1", since = "1.0.0")]
805 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
806     fs_imp::stat(path.as_ref()).map(Metadata)
807 }
808
809 /// Query the metadata about a file without following symlinks.
810 ///
811 /// # Examples
812 ///
813 /// ```rust
814 /// # fn foo() -> std::io::Result<()> {
815 /// use std::fs;
816 ///
817 /// let attr = try!(fs::symlink_metadata("/some/file/path.txt"));
818 /// // inspect attr ...
819 /// # Ok(())
820 /// # }
821 /// ```
822 #[stable(feature = "symlink_metadata", since = "1.1.0")]
823 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
824     fs_imp::lstat(path.as_ref()).map(Metadata)
825 }
826
827 /// Rename a file or directory to a new name.
828 ///
829 /// This will not work if the new name is on a different mount point.
830 ///
831 /// # Errors
832 ///
833 /// This function will return an error if the provided `from` doesn't exist, if
834 /// the process lacks permissions to view the contents, if `from` and `to`
835 /// reside on separate filesystems, or if some other intermittent I/O error
836 /// occurs.
837 ///
838 /// # Examples
839 ///
840 /// ```
841 /// use std::fs;
842 ///
843 /// # fn foo() -> std::io::Result<()> {
844 /// try!(fs::rename("a.txt", "b.txt"));
845 /// # Ok(())
846 /// # }
847 /// ```
848 #[stable(feature = "rust1", since = "1.0.0")]
849 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
850     fs_imp::rename(from.as_ref(), to.as_ref())
851 }
852
853 /// Copies the contents of one file to another. This function will also
854 /// copy the permission bits of the original file to the destination file.
855 ///
856 /// This function will **overwrite** the contents of `to`.
857 ///
858 /// Note that if `from` and `to` both point to the same file, then the file
859 /// will likely get truncated by this operation.
860 ///
861 /// On success, the total number of bytes copied is returned.
862 ///
863 /// # Errors
864 ///
865 /// This function will return an error in the following situations, but is not
866 /// limited to just these cases:
867 ///
868 /// * The `from` path is not a file
869 /// * The `from` file does not exist
870 /// * The current process does not have the permission rights to access
871 ///   `from` or write `to`
872 ///
873 /// # Examples
874 ///
875 /// ```no_run
876 /// use std::fs;
877 ///
878 /// # fn foo() -> std::io::Result<()> {
879 /// try!(fs::copy("foo.txt", "bar.txt"));
880 /// # Ok(()) }
881 /// ```
882 #[stable(feature = "rust1", since = "1.0.0")]
883 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
884     fs_imp::copy(from.as_ref(), to.as_ref())
885 }
886
887 /// Creates a new hard link on the filesystem.
888 ///
889 /// The `dst` path will be a link pointing to the `src` path. Note that systems
890 /// often require these two paths to both be located on the same filesystem.
891 ///
892 /// # Examples
893 ///
894 /// ```
895 /// use std::fs;
896 ///
897 /// # fn foo() -> std::io::Result<()> {
898 /// try!(fs::hard_link("a.txt", "b.txt"));
899 /// # Ok(())
900 /// # }
901 /// ```
902 #[stable(feature = "rust1", since = "1.0.0")]
903 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
904     fs_imp::link(src.as_ref(), dst.as_ref())
905 }
906
907 /// Creates a new symbolic link on the filesystem.
908 ///
909 /// The `dst` path will be a symbolic link pointing to the `src` path.
910 /// On Windows, this will be a file symlink, not a directory symlink;
911 /// for this reason, the platform-specific `std::os::unix::fs::symlink`
912 /// and `std::os::windows::fs::{symlink_file, symlink_dir}` should be
913 /// used instead to make the intent explicit.
914 ///
915 /// # Examples
916 ///
917 /// ```
918 /// use std::fs;
919 ///
920 /// # fn foo() -> std::io::Result<()> {
921 /// try!(fs::soft_link("a.txt", "b.txt"));
922 /// # Ok(())
923 /// # }
924 /// ```
925 #[rustc_deprecated(since = "1.1.0",
926              reason = "replaced with std::os::unix::fs::symlink and \
927                        std::os::windows::fs::{symlink_file, symlink_dir}")]
928 #[stable(feature = "rust1", since = "1.0.0")]
929 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
930     fs_imp::symlink(src.as_ref(), dst.as_ref())
931 }
932
933 /// Reads a symbolic link, returning the file that the link points to.
934 ///
935 /// # Errors
936 ///
937 /// This function will return an error on failure. Failure conditions include
938 /// reading a file that does not exist or reading a file that is not a symbolic
939 /// link.
940 ///
941 /// # Examples
942 ///
943 /// ```
944 /// use std::fs;
945 ///
946 /// # fn foo() -> std::io::Result<()> {
947 /// let path = try!(fs::read_link("a.txt"));
948 /// # Ok(())
949 /// # }
950 /// ```
951 #[stable(feature = "rust1", since = "1.0.0")]
952 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
953     fs_imp::readlink(path.as_ref())
954 }
955
956 /// Returns the canonical form of a path with all intermediate components
957 /// normalized and symbolic links resolved.
958 ///
959 /// This function may return an error in situations like where the path does not
960 /// exist, a component in the path is not a directory, or an I/O error happens.
961 ///
962 /// # Examples
963 ///
964 /// ```
965 /// use std::fs;
966 ///
967 /// # fn foo() -> std::io::Result<()> {
968 /// let path = try!(fs::canonicalize("../a/../foo.txt"));
969 /// # Ok(())
970 /// # }
971 /// ```
972 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
973 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
974     fs_imp::canonicalize(path.as_ref())
975 }
976
977 /// Creates a new, empty directory at the provided path
978 ///
979 /// # Errors
980 ///
981 /// This function will return an error if the user lacks permissions to make a
982 /// new directory at the provided `path`, or if the directory already exists.
983 ///
984 /// # Examples
985 ///
986 /// ```
987 /// use std::fs;
988 ///
989 /// # fn foo() -> std::io::Result<()> {
990 /// try!(fs::create_dir("/some/dir"));
991 /// # Ok(())
992 /// # }
993 /// ```
994 #[stable(feature = "rust1", since = "1.0.0")]
995 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
996     DirBuilder::new().create(path.as_ref())
997 }
998
999 /// Recursively create a directory and all of its parent components if they
1000 /// are missing.
1001 ///
1002 /// # Errors
1003 ///
1004 /// This function will fail if any directory in the path specified by `path`
1005 /// does not already exist and it could not be created otherwise. The specific
1006 /// error conditions for when a directory is being created (after it is
1007 /// determined to not exist) are outlined by `fs::create_dir`.
1008 ///
1009 /// # Examples
1010 ///
1011 /// ```
1012 /// use std::fs;
1013 ///
1014 /// # fn foo() -> std::io::Result<()> {
1015 /// try!(fs::create_dir_all("/some/dir"));
1016 /// # Ok(())
1017 /// # }
1018 /// ```
1019 #[stable(feature = "rust1", since = "1.0.0")]
1020 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1021     DirBuilder::new().recursive(true).create(path.as_ref())
1022 }
1023
1024 /// Removes an existing, empty directory.
1025 ///
1026 /// # Errors
1027 ///
1028 /// This function will return an error if the user lacks permissions to remove
1029 /// the directory at the provided `path`, or if the directory isn't empty.
1030 ///
1031 /// # Examples
1032 ///
1033 /// ```
1034 /// use std::fs;
1035 ///
1036 /// # fn foo() -> std::io::Result<()> {
1037 /// try!(fs::remove_dir("/some/dir"));
1038 /// # Ok(())
1039 /// # }
1040 /// ```
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1043     fs_imp::rmdir(path.as_ref())
1044 }
1045
1046 /// Removes a directory at this path, after removing all its contents. Use
1047 /// carefully!
1048 ///
1049 /// This function does **not** follow symbolic links and it will simply remove the
1050 /// symbolic link itself.
1051 ///
1052 /// # Errors
1053 ///
1054 /// See `file::remove_file` and `fs::remove_dir`.
1055 ///
1056 /// # Examples
1057 ///
1058 /// ```
1059 /// use std::fs;
1060 ///
1061 /// # fn foo() -> std::io::Result<()> {
1062 /// try!(fs::remove_dir_all("/some/dir"));
1063 /// # Ok(())
1064 /// # }
1065 /// ```
1066 #[stable(feature = "rust1", since = "1.0.0")]
1067 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1068     _remove_dir_all(path.as_ref())
1069 }
1070
1071 fn _remove_dir_all(path: &Path) -> io::Result<()> {
1072     for child in try!(read_dir(path)) {
1073         let child = try!(child).path();
1074         let stat = try!(symlink_metadata(&*child));
1075         if stat.is_dir() {
1076             try!(remove_dir_all(&*child));
1077         } else {
1078             try!(remove_file(&*child));
1079         }
1080     }
1081     remove_dir(path)
1082 }
1083
1084 /// Returns an iterator over the entries within a directory.
1085 ///
1086 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1087 /// be encountered after an iterator is initially constructed.
1088 ///
1089 /// # Examples
1090 ///
1091 /// ```
1092 /// use std::io;
1093 /// use std::fs::{self, DirEntry};
1094 /// use std::path::Path;
1095 ///
1096 /// // one possible implementation of fs::walk_dir only visiting files
1097 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1098 ///     if try!(fs::metadata(dir)).is_dir() {
1099 ///         for entry in try!(fs::read_dir(dir)) {
1100 ///             let entry = try!(entry);
1101 ///             if try!(fs::metadata(entry.path())).is_dir() {
1102 ///                 try!(visit_dirs(&entry.path(), cb));
1103 ///             } else {
1104 ///                 cb(&entry);
1105 ///             }
1106 ///         }
1107 ///     }
1108 ///     Ok(())
1109 /// }
1110 /// ```
1111 ///
1112 /// # Errors
1113 ///
1114 /// This function will return an error if the provided `path` doesn't exist, if
1115 /// the process lacks permissions to view the contents or if the `path` points
1116 /// at a non-directory file
1117 #[stable(feature = "rust1", since = "1.0.0")]
1118 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1119     fs_imp::readdir(path.as_ref()).map(ReadDir)
1120 }
1121
1122 /// Returns an iterator that will recursively walk the directory structure
1123 /// rooted at `path`.
1124 ///
1125 /// The path given will not be iterated over, and this will perform iteration in
1126 /// some top-down order.  The contents of unreadable subdirectories are ignored.
1127 ///
1128 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1129 /// be encountered after an iterator is initially constructed.
1130 #[unstable(feature = "fs_walk",
1131            reason = "the precise semantics and defaults for a recursive walk \
1132                      may change and this may end up accounting for files such \
1133                      as symlinks differently",
1134            issue = "27707")]
1135 pub fn walk_dir<P: AsRef<Path>>(path: P) -> io::Result<WalkDir> {
1136     _walk_dir(path.as_ref())
1137 }
1138
1139 fn _walk_dir(path: &Path) -> io::Result<WalkDir> {
1140     let start = try!(read_dir(path));
1141     Ok(WalkDir { cur: Some(start), stack: Vec::new() })
1142 }
1143
1144 #[unstable(feature = "fs_walk", issue = "27707")]
1145 impl Iterator for WalkDir {
1146     type Item = io::Result<DirEntry>;
1147
1148     fn next(&mut self) -> Option<io::Result<DirEntry>> {
1149         loop {
1150             if let Some(ref mut cur) = self.cur {
1151                 match cur.next() {
1152                     Some(Err(e)) => return Some(Err(e)),
1153                     Some(Ok(next)) => {
1154                         let path = next.path();
1155                         if path.is_dir() {
1156                             self.stack.push(read_dir(&*path));
1157                         }
1158                         return Some(Ok(next))
1159                     }
1160                     None => {}
1161                 }
1162             }
1163             self.cur = None;
1164             match self.stack.pop() {
1165                 Some(Err(e)) => return Some(Err(e)),
1166                 Some(Ok(next)) => self.cur = Some(next),
1167                 None => return None,
1168             }
1169         }
1170     }
1171 }
1172
1173 /// Utility methods for paths.
1174 #[unstable(feature = "path_ext_deprecated",
1175            reason = "The precise set of methods exposed on this trait may \
1176                      change and some methods may be removed.  For stable code, \
1177                      see the std::fs::metadata function.",
1178            issue = "27725")]
1179 #[rustc_deprecated(since = "1.5.0", reason = "replaced with inherent methods")]
1180 pub trait PathExt {
1181     /// Gets information on the file, directory, etc at this path.
1182     ///
1183     /// Consult the `fs::metadata` documentation for more info.
1184     ///
1185     /// This call preserves identical runtime/error semantics with
1186     /// `fs::metadata`.
1187     fn metadata(&self) -> io::Result<Metadata>;
1188
1189     /// Gets information on the file, directory, etc at this path.
1190     ///
1191     /// Consult the `fs::symlink_metadata` documentation for more info.
1192     ///
1193     /// This call preserves identical runtime/error semantics with
1194     /// `fs::symlink_metadata`.
1195     fn symlink_metadata(&self) -> io::Result<Metadata>;
1196
1197     /// Returns the canonical form of a path, normalizing all components and
1198     /// eliminate all symlinks.
1199     ///
1200     /// This call preserves identical runtime/error semantics with
1201     /// `fs::canonicalize`.
1202     fn canonicalize(&self) -> io::Result<PathBuf>;
1203
1204     /// Reads the symlink at this path.
1205     ///
1206     /// For more information see `fs::read_link`.
1207     fn read_link(&self) -> io::Result<PathBuf>;
1208
1209     /// Reads the directory at this path.
1210     ///
1211     /// For more information see `fs::read_dir`.
1212     fn read_dir(&self) -> io::Result<ReadDir>;
1213
1214     /// Boolean value indicator whether the underlying file exists on the local
1215     /// filesystem. Returns false in exactly the cases where `fs::metadata`
1216     /// fails.
1217     fn exists(&self) -> bool;
1218
1219     /// Whether the underlying implementation (be it a file path, or something
1220     /// else) points at a "regular file" on the FS. Will return false for paths
1221     /// to non-existent locations or directories or other non-regular files
1222     /// (named pipes, etc). Follows links when making this determination.
1223     fn is_file(&self) -> bool;
1224
1225     /// Whether the underlying implementation (be it a file path, or something
1226     /// else) is pointing at a directory in the underlying FS. Will return
1227     /// false for paths to non-existent locations or if the item is not a
1228     /// directory (eg files, named pipes, etc). Follows links when making this
1229     /// determination.
1230     fn is_dir(&self) -> bool;
1231 }
1232
1233 #[allow(deprecated)]
1234 #[unstable(feature = "path_ext_deprecated", issue = "27725")]
1235 impl PathExt for Path {
1236     fn metadata(&self) -> io::Result<Metadata> { metadata(self) }
1237     fn symlink_metadata(&self) -> io::Result<Metadata> { symlink_metadata(self) }
1238     fn canonicalize(&self) -> io::Result<PathBuf> { canonicalize(self) }
1239     fn read_link(&self) -> io::Result<PathBuf> { read_link(self) }
1240     fn read_dir(&self) -> io::Result<ReadDir> { read_dir(self) }
1241     fn exists(&self) -> bool { metadata(self).is_ok() }
1242
1243     fn is_file(&self) -> bool {
1244         metadata(self).map(|s| s.is_file()).unwrap_or(false)
1245     }
1246
1247     fn is_dir(&self) -> bool {
1248         metadata(self).map(|s| s.is_dir()).unwrap_or(false)
1249     }
1250 }
1251
1252 /// Changes the permissions found on a file or a directory.
1253 ///
1254 /// # Examples
1255 ///
1256 /// ```
1257 /// # fn foo() -> std::io::Result<()> {
1258 /// use std::fs;
1259 ///
1260 /// let mut perms = try!(fs::metadata("foo.txt")).permissions();
1261 /// perms.set_readonly(true);
1262 /// try!(fs::set_permissions("foo.txt", perms));
1263 /// # Ok(())
1264 /// # }
1265 /// ```
1266 ///
1267 /// # Errors
1268 ///
1269 /// This function will return an error if the provided `path` doesn't exist, if
1270 /// the process lacks permissions to change the attributes of the file, or if
1271 /// some other I/O error is encountered.
1272 #[stable(feature = "set_permissions", since = "1.1.0")]
1273 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
1274                                        -> io::Result<()> {
1275     fs_imp::set_perm(path.as_ref(), perm.0)
1276 }
1277
1278 #[unstable(feature = "dir_builder", reason = "recently added API",
1279            issue = "27710")]
1280 impl DirBuilder {
1281     /// Creates a new set of options with default mode/security settings for all
1282     /// platforms and also non-recursive.
1283     pub fn new() -> DirBuilder {
1284         DirBuilder {
1285             inner: fs_imp::DirBuilder::new(),
1286             recursive: false,
1287         }
1288     }
1289
1290     /// Indicate that directories create should be created recursively, creating
1291     /// all parent directories if they do not exist with the same security and
1292     /// permissions settings.
1293     ///
1294     /// This option defaults to `false`
1295     pub fn recursive(&mut self, recursive: bool) -> &mut Self {
1296         self.recursive = recursive;
1297         self
1298     }
1299
1300     /// Create the specified directory with the options configured in this
1301     /// builder.
1302     ///
1303     /// # Examples
1304     ///
1305     /// ```no_run
1306     /// #![feature(dir_builder)]
1307     /// use std::fs::{self, DirBuilder};
1308     ///
1309     /// let path = "/tmp/foo/bar/baz";
1310     /// DirBuilder::new()
1311     ///     .recursive(true)
1312     ///     .create(path).unwrap();
1313     ///
1314     /// assert!(fs::metadata(path).unwrap().is_dir());
1315     /// ```
1316     pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1317         self._create(path.as_ref())
1318     }
1319
1320     fn _create(&self, path: &Path) -> io::Result<()> {
1321         if self.recursive {
1322             self.create_dir_all(path)
1323         } else {
1324             self.inner.mkdir(path)
1325         }
1326     }
1327
1328     fn create_dir_all(&self, path: &Path) -> io::Result<()> {
1329         if path == Path::new("") || path.is_dir() { return Ok(()) }
1330         if let Some(p) = path.parent() {
1331             try!(self.create_dir_all(p))
1332         }
1333         self.inner.mkdir(path)
1334     }
1335 }
1336
1337 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
1338     fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
1339         &mut self.inner
1340     }
1341 }
1342
1343 #[cfg(test)]
1344 mod tests {
1345     #![allow(deprecated)] //rand
1346
1347     use prelude::v1::*;
1348     use io::prelude::*;
1349
1350     use env;
1351     use fs::{self, File, OpenOptions};
1352     use io::{ErrorKind, SeekFrom};
1353     use path::PathBuf;
1354     use path::Path as Path2;
1355     use os;
1356     use rand::{self, StdRng, Rng};
1357     use str;
1358
1359     macro_rules! check { ($e:expr) => (
1360         match $e {
1361             Ok(t) => t,
1362             Err(e) => panic!("{} failed with: {}", stringify!($e), e),
1363         }
1364     ) }
1365
1366     macro_rules! error { ($e:expr, $s:expr) => (
1367         match $e {
1368             Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1369             Err(ref err) => assert!(err.to_string().contains($s),
1370                                     format!("`{}` did not contain `{}`", err, $s))
1371         }
1372     ) }
1373
1374     pub struct TempDir(PathBuf);
1375
1376     impl TempDir {
1377         fn join(&self, path: &str) -> PathBuf {
1378             let TempDir(ref p) = *self;
1379             p.join(path)
1380         }
1381
1382         fn path<'a>(&'a self) -> &'a Path2 {
1383             let TempDir(ref p) = *self;
1384             p
1385         }
1386     }
1387
1388     impl Drop for TempDir {
1389         fn drop(&mut self) {
1390             // Gee, seeing how we're testing the fs module I sure hope that we
1391             // at least implement this correctly!
1392             let TempDir(ref p) = *self;
1393             check!(fs::remove_dir_all(p));
1394         }
1395     }
1396
1397     pub fn tmpdir() -> TempDir {
1398         let p = env::temp_dir();
1399         let mut r = rand::thread_rng();
1400         let ret = p.join(&format!("rust-{}", r.next_u32()));
1401         check!(fs::create_dir(&ret));
1402         TempDir(ret)
1403     }
1404
1405     #[test]
1406     fn file_test_io_smoke_test() {
1407         let message = "it's alright. have a good time";
1408         let tmpdir = tmpdir();
1409         let filename = &tmpdir.join("file_rt_io_file_test.txt");
1410         {
1411             let mut write_stream = check!(File::create(filename));
1412             check!(write_stream.write(message.as_bytes()));
1413         }
1414         {
1415             let mut read_stream = check!(File::open(filename));
1416             let mut read_buf = [0; 1028];
1417             let read_str = match check!(read_stream.read(&mut read_buf)) {
1418                 0 => panic!("shouldn't happen"),
1419                 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
1420             };
1421             assert_eq!(read_str, message);
1422         }
1423         check!(fs::remove_file(filename));
1424     }
1425
1426     #[test]
1427     fn invalid_path_raises() {
1428         let tmpdir = tmpdir();
1429         let filename = &tmpdir.join("file_that_does_not_exist.txt");
1430         let result = File::open(filename);
1431
1432         if cfg!(unix) {
1433             error!(result, "o such file or directory");
1434         }
1435         // error!(result, "couldn't open path as file");
1436         // error!(result, format!("path={}; mode=open; access=read", filename.display()));
1437     }
1438
1439     #[test]
1440     fn file_test_iounlinking_invalid_path_should_raise_condition() {
1441         let tmpdir = tmpdir();
1442         let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1443
1444         let result = fs::remove_file(filename);
1445
1446         if cfg!(unix) {
1447             error!(result, "o such file or directory");
1448         }
1449         // error!(result, "couldn't unlink path");
1450         // error!(result, format!("path={}", filename.display()));
1451     }
1452
1453     #[test]
1454     fn file_test_io_non_positional_read() {
1455         let message: &str = "ten-four";
1456         let mut read_mem = [0; 8];
1457         let tmpdir = tmpdir();
1458         let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1459         {
1460             let mut rw_stream = check!(File::create(filename));
1461             check!(rw_stream.write(message.as_bytes()));
1462         }
1463         {
1464             let mut read_stream = check!(File::open(filename));
1465             {
1466                 let read_buf = &mut read_mem[0..4];
1467                 check!(read_stream.read(read_buf));
1468             }
1469             {
1470                 let read_buf = &mut read_mem[4..8];
1471                 check!(read_stream.read(read_buf));
1472             }
1473         }
1474         check!(fs::remove_file(filename));
1475         let read_str = str::from_utf8(&read_mem).unwrap();
1476         assert_eq!(read_str, message);
1477     }
1478
1479     #[test]
1480     fn file_test_io_seek_and_tell_smoke_test() {
1481         let message = "ten-four";
1482         let mut read_mem = [0; 4];
1483         let set_cursor = 4 as u64;
1484         let mut tell_pos_pre_read;
1485         let mut tell_pos_post_read;
1486         let tmpdir = tmpdir();
1487         let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
1488         {
1489             let mut rw_stream = check!(File::create(filename));
1490             check!(rw_stream.write(message.as_bytes()));
1491         }
1492         {
1493             let mut read_stream = check!(File::open(filename));
1494             check!(read_stream.seek(SeekFrom::Start(set_cursor)));
1495             tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
1496             check!(read_stream.read(&mut read_mem));
1497             tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
1498         }
1499         check!(fs::remove_file(filename));
1500         let read_str = str::from_utf8(&read_mem).unwrap();
1501         assert_eq!(read_str, &message[4..8]);
1502         assert_eq!(tell_pos_pre_read, set_cursor);
1503         assert_eq!(tell_pos_post_read, message.len() as u64);
1504     }
1505
1506     #[test]
1507     fn file_test_io_seek_and_write() {
1508         let initial_msg =   "food-is-yummy";
1509         let overwrite_msg =    "-the-bar!!";
1510         let final_msg =     "foo-the-bar!!";
1511         let seek_idx = 3;
1512         let mut read_mem = [0; 13];
1513         let tmpdir = tmpdir();
1514         let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
1515         {
1516             let mut rw_stream = check!(File::create(filename));
1517             check!(rw_stream.write(initial_msg.as_bytes()));
1518             check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
1519             check!(rw_stream.write(overwrite_msg.as_bytes()));
1520         }
1521         {
1522             let mut read_stream = check!(File::open(filename));
1523             check!(read_stream.read(&mut read_mem));
1524         }
1525         check!(fs::remove_file(filename));
1526         let read_str = str::from_utf8(&read_mem).unwrap();
1527         assert!(read_str == final_msg);
1528     }
1529
1530     #[test]
1531     fn file_test_io_seek_shakedown() {
1532         //                   01234567890123
1533         let initial_msg =   "qwer-asdf-zxcv";
1534         let chunk_one: &str = "qwer";
1535         let chunk_two: &str = "asdf";
1536         let chunk_three: &str = "zxcv";
1537         let mut read_mem = [0; 4];
1538         let tmpdir = tmpdir();
1539         let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
1540         {
1541             let mut rw_stream = check!(File::create(filename));
1542             check!(rw_stream.write(initial_msg.as_bytes()));
1543         }
1544         {
1545             let mut read_stream = check!(File::open(filename));
1546
1547             check!(read_stream.seek(SeekFrom::End(-4)));
1548             check!(read_stream.read(&mut read_mem));
1549             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
1550
1551             check!(read_stream.seek(SeekFrom::Current(-9)));
1552             check!(read_stream.read(&mut read_mem));
1553             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
1554
1555             check!(read_stream.seek(SeekFrom::Start(0)));
1556             check!(read_stream.read(&mut read_mem));
1557             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
1558         }
1559         check!(fs::remove_file(filename));
1560     }
1561
1562     #[test]
1563     fn file_test_stat_is_correct_on_is_file() {
1564         let tmpdir = tmpdir();
1565         let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
1566         {
1567             let mut opts = OpenOptions::new();
1568             let mut fs = check!(opts.read(true).write(true)
1569                                     .create(true).open(filename));
1570             let msg = "hw";
1571             fs.write(msg.as_bytes()).unwrap();
1572
1573             let fstat_res = check!(fs.metadata());
1574             assert!(fstat_res.is_file());
1575         }
1576         let stat_res_fn = check!(fs::metadata(filename));
1577         assert!(stat_res_fn.is_file());
1578         let stat_res_meth = check!(filename.metadata());
1579         assert!(stat_res_meth.is_file());
1580         check!(fs::remove_file(filename));
1581     }
1582
1583     #[test]
1584     fn file_test_stat_is_correct_on_is_dir() {
1585         let tmpdir = tmpdir();
1586         let filename = &tmpdir.join("file_stat_correct_on_is_dir");
1587         check!(fs::create_dir(filename));
1588         let stat_res_fn = check!(fs::metadata(filename));
1589         assert!(stat_res_fn.is_dir());
1590         let stat_res_meth = check!(filename.metadata());
1591         assert!(stat_res_meth.is_dir());
1592         check!(fs::remove_dir(filename));
1593     }
1594
1595     #[test]
1596     fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1597         let tmpdir = tmpdir();
1598         let dir = &tmpdir.join("fileinfo_false_on_dir");
1599         check!(fs::create_dir(dir));
1600         assert!(dir.is_file() == false);
1601         check!(fs::remove_dir(dir));
1602     }
1603
1604     #[test]
1605     fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1606         let tmpdir = tmpdir();
1607         let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1608         check!(check!(File::create(file)).write(b"foo"));
1609         assert!(file.exists());
1610         check!(fs::remove_file(file));
1611         assert!(!file.exists());
1612     }
1613
1614     #[test]
1615     fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1616         let tmpdir = tmpdir();
1617         let dir = &tmpdir.join("before_and_after_dir");
1618         assert!(!dir.exists());
1619         check!(fs::create_dir(dir));
1620         assert!(dir.exists());
1621         assert!(dir.is_dir());
1622         check!(fs::remove_dir(dir));
1623         assert!(!dir.exists());
1624     }
1625
1626     #[test]
1627     fn file_test_directoryinfo_readdir() {
1628         let tmpdir = tmpdir();
1629         let dir = &tmpdir.join("di_readdir");
1630         check!(fs::create_dir(dir));
1631         let prefix = "foo";
1632         for n in 0..3 {
1633             let f = dir.join(&format!("{}.txt", n));
1634             let mut w = check!(File::create(&f));
1635             let msg_str = format!("{}{}", prefix, n.to_string());
1636             let msg = msg_str.as_bytes();
1637             check!(w.write(msg));
1638         }
1639         let files = check!(fs::read_dir(dir));
1640         let mut mem = [0; 4];
1641         for f in files {
1642             let f = f.unwrap().path();
1643             {
1644                 let n = f.file_stem().unwrap();
1645                 check!(check!(File::open(&f)).read(&mut mem));
1646                 let read_str = str::from_utf8(&mem).unwrap();
1647                 let expected = format!("{}{}", prefix, n.to_str().unwrap());
1648                 assert_eq!(expected, read_str);
1649             }
1650             check!(fs::remove_file(&f));
1651         }
1652         check!(fs::remove_dir(dir));
1653     }
1654
1655     #[test]
1656     fn file_test_walk_dir() {
1657         let tmpdir = tmpdir();
1658         let dir = &tmpdir.join("walk_dir");
1659         check!(fs::create_dir(dir));
1660
1661         let dir1 = &dir.join("01/02/03");
1662         check!(fs::create_dir_all(dir1));
1663         check!(File::create(&dir1.join("04")));
1664
1665         let dir2 = &dir.join("11/12/13");
1666         check!(fs::create_dir_all(dir2));
1667         check!(File::create(&dir2.join("14")));
1668
1669         let files = check!(fs::walk_dir(dir));
1670         let mut cur = [0; 2];
1671         for f in files {
1672             let f = f.unwrap().path();
1673             let stem = f.file_stem().unwrap().to_str().unwrap();
1674             let root = stem.as_bytes()[0] - b'0';
1675             let name = stem.as_bytes()[1] - b'0';
1676             assert!(cur[root as usize] < name);
1677             cur[root as usize] = name;
1678         }
1679
1680         check!(fs::remove_dir_all(dir));
1681     }
1682
1683     #[test]
1684     fn mkdir_path_already_exists_error() {
1685         let tmpdir = tmpdir();
1686         let dir = &tmpdir.join("mkdir_error_twice");
1687         check!(fs::create_dir(dir));
1688         let e = fs::create_dir(dir).err().unwrap();
1689         assert_eq!(e.kind(), ErrorKind::AlreadyExists);
1690     }
1691
1692     #[test]
1693     fn recursive_mkdir() {
1694         let tmpdir = tmpdir();
1695         let dir = tmpdir.join("d1/d2");
1696         check!(fs::create_dir_all(&dir));
1697         assert!(dir.is_dir())
1698     }
1699
1700     #[test]
1701     fn recursive_mkdir_failure() {
1702         let tmpdir = tmpdir();
1703         let dir = tmpdir.join("d1");
1704         let file = dir.join("f1");
1705
1706         check!(fs::create_dir_all(&dir));
1707         check!(File::create(&file));
1708
1709         let result = fs::create_dir_all(&file);
1710
1711         assert!(result.is_err());
1712         // error!(result, "couldn't recursively mkdir");
1713         // error!(result, "couldn't create directory");
1714         // error!(result, "mode=0700");
1715         // error!(result, format!("path={}", file.display()));
1716     }
1717
1718     #[test]
1719     fn recursive_mkdir_slash() {
1720         check!(fs::create_dir_all(&Path2::new("/")));
1721     }
1722
1723     // FIXME(#12795) depends on lstat to work on windows
1724     #[cfg(not(windows))]
1725     #[test]
1726     fn recursive_rmdir() {
1727         let tmpdir = tmpdir();
1728         let d1 = tmpdir.join("d1");
1729         let dt = d1.join("t");
1730         let dtt = dt.join("t");
1731         let d2 = tmpdir.join("d2");
1732         let canary = d2.join("do_not_delete");
1733         check!(fs::create_dir_all(&dtt));
1734         check!(fs::create_dir_all(&d2));
1735         check!(check!(File::create(&canary)).write(b"foo"));
1736         check!(fs::soft_link(&d2, &dt.join("d2")));
1737         check!(fs::remove_dir_all(&d1));
1738
1739         assert!(!d1.is_dir());
1740         assert!(canary.exists());
1741     }
1742
1743     #[test]
1744     fn unicode_path_is_dir() {
1745         assert!(Path2::new(".").is_dir());
1746         assert!(!Path2::new("test/stdtest/fs.rs").is_dir());
1747
1748         let tmpdir = tmpdir();
1749
1750         let mut dirpath = tmpdir.path().to_path_buf();
1751         dirpath.push("test-가一ー你好");
1752         check!(fs::create_dir(&dirpath));
1753         assert!(dirpath.is_dir());
1754
1755         let mut filepath = dirpath;
1756         filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
1757         check!(File::create(&filepath)); // ignore return; touch only
1758         assert!(!filepath.is_dir());
1759         assert!(filepath.exists());
1760     }
1761
1762     #[test]
1763     fn unicode_path_exists() {
1764         assert!(Path2::new(".").exists());
1765         assert!(!Path2::new("test/nonexistent-bogus-path").exists());
1766
1767         let tmpdir = tmpdir();
1768         let unicode = tmpdir.path();
1769         let unicode = unicode.join(&format!("test-각丁ー再见"));
1770         check!(fs::create_dir(&unicode));
1771         assert!(unicode.exists());
1772         assert!(!Path2::new("test/unicode-bogus-path-각丁ー再见").exists());
1773     }
1774
1775     #[test]
1776     fn copy_file_does_not_exist() {
1777         let from = Path2::new("test/nonexistent-bogus-path");
1778         let to = Path2::new("test/other-bogus-path");
1779
1780         match fs::copy(&from, &to) {
1781             Ok(..) => panic!(),
1782             Err(..) => {
1783                 assert!(!from.exists());
1784                 assert!(!to.exists());
1785             }
1786         }
1787     }
1788
1789     #[test]
1790     fn copy_src_does_not_exist() {
1791         let tmpdir = tmpdir();
1792         let from = Path2::new("test/nonexistent-bogus-path");
1793         let to = tmpdir.join("out.txt");
1794         check!(check!(File::create(&to)).write(b"hello"));
1795         assert!(fs::copy(&from, &to).is_err());
1796         assert!(!from.exists());
1797         let mut v = Vec::new();
1798         check!(check!(File::open(&to)).read_to_end(&mut v));
1799         assert_eq!(v, b"hello");
1800     }
1801
1802     #[test]
1803     fn copy_file_ok() {
1804         let tmpdir = tmpdir();
1805         let input = tmpdir.join("in.txt");
1806         let out = tmpdir.join("out.txt");
1807
1808         check!(check!(File::create(&input)).write(b"hello"));
1809         check!(fs::copy(&input, &out));
1810         let mut v = Vec::new();
1811         check!(check!(File::open(&out)).read_to_end(&mut v));
1812         assert_eq!(v, b"hello");
1813
1814         assert_eq!(check!(input.metadata()).permissions(),
1815                    check!(out.metadata()).permissions());
1816     }
1817
1818     #[test]
1819     fn copy_file_dst_dir() {
1820         let tmpdir = tmpdir();
1821         let out = tmpdir.join("out");
1822
1823         check!(File::create(&out));
1824         match fs::copy(&*out, tmpdir.path()) {
1825             Ok(..) => panic!(), Err(..) => {}
1826         }
1827     }
1828
1829     #[test]
1830     fn copy_file_dst_exists() {
1831         let tmpdir = tmpdir();
1832         let input = tmpdir.join("in");
1833         let output = tmpdir.join("out");
1834
1835         check!(check!(File::create(&input)).write("foo".as_bytes()));
1836         check!(check!(File::create(&output)).write("bar".as_bytes()));
1837         check!(fs::copy(&input, &output));
1838
1839         let mut v = Vec::new();
1840         check!(check!(File::open(&output)).read_to_end(&mut v));
1841         assert_eq!(v, b"foo".to_vec());
1842     }
1843
1844     #[test]
1845     fn copy_file_src_dir() {
1846         let tmpdir = tmpdir();
1847         let out = tmpdir.join("out");
1848
1849         match fs::copy(tmpdir.path(), &out) {
1850             Ok(..) => panic!(), Err(..) => {}
1851         }
1852         assert!(!out.exists());
1853     }
1854
1855     #[test]
1856     fn copy_file_preserves_perm_bits() {
1857         let tmpdir = tmpdir();
1858         let input = tmpdir.join("in.txt");
1859         let out = tmpdir.join("out.txt");
1860
1861         let attr = check!(check!(File::create(&input)).metadata());
1862         let mut p = attr.permissions();
1863         p.set_readonly(true);
1864         check!(fs::set_permissions(&input, p));
1865         check!(fs::copy(&input, &out));
1866         assert!(check!(out.metadata()).permissions().readonly());
1867         check!(fs::set_permissions(&input, attr.permissions()));
1868         check!(fs::set_permissions(&out, attr.permissions()));
1869     }
1870
1871     #[cfg(windows)]
1872     #[test]
1873     fn copy_file_preserves_streams() {
1874         let tmp = tmpdir();
1875         check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
1876         assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 6);
1877         assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
1878         let mut v = Vec::new();
1879         check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
1880         assert_eq!(v, b"carrot".to_vec());
1881     }
1882
1883     #[cfg(not(windows))] // FIXME(#10264) operation not permitted?
1884     #[test]
1885     fn symlinks_work() {
1886         let tmpdir = tmpdir();
1887         let input = tmpdir.join("in.txt");
1888         let out = tmpdir.join("out.txt");
1889
1890         check!(check!(File::create(&input)).write("foobar".as_bytes()));
1891         check!(fs::soft_link(&input, &out));
1892         // if cfg!(not(windows)) {
1893         //     assert_eq!(check!(lstat(&out)).kind, FileType::Symlink);
1894         //     assert_eq!(check!(out.lstat()).kind, FileType::Symlink);
1895         // }
1896         assert_eq!(check!(fs::metadata(&out)).len(),
1897                    check!(fs::metadata(&input)).len());
1898         let mut v = Vec::new();
1899         check!(check!(File::open(&out)).read_to_end(&mut v));
1900         assert_eq!(v, b"foobar".to_vec());
1901     }
1902
1903     #[cfg(not(windows))] // apparently windows doesn't like symlinks
1904     #[test]
1905     fn symlink_noexist() {
1906         let tmpdir = tmpdir();
1907         // symlinks can point to things that don't exist
1908         check!(fs::soft_link(&tmpdir.join("foo"), &tmpdir.join("bar")));
1909         assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))),
1910                    tmpdir.join("foo"));
1911     }
1912
1913     #[test]
1914     fn readlink_not_symlink() {
1915         let tmpdir = tmpdir();
1916         match fs::read_link(tmpdir.path()) {
1917             Ok(..) => panic!("wanted a failure"),
1918             Err(..) => {}
1919         }
1920     }
1921
1922     #[test]
1923     fn links_work() {
1924         let tmpdir = tmpdir();
1925         let input = tmpdir.join("in.txt");
1926         let out = tmpdir.join("out.txt");
1927
1928         check!(check!(File::create(&input)).write("foobar".as_bytes()));
1929         check!(fs::hard_link(&input, &out));
1930         assert_eq!(check!(fs::metadata(&out)).len(),
1931                    check!(fs::metadata(&input)).len());
1932         assert_eq!(check!(fs::metadata(&out)).len(),
1933                    check!(input.metadata()).len());
1934         let mut v = Vec::new();
1935         check!(check!(File::open(&out)).read_to_end(&mut v));
1936         assert_eq!(v, b"foobar".to_vec());
1937
1938         // can't link to yourself
1939         match fs::hard_link(&input, &input) {
1940             Ok(..) => panic!("wanted a failure"),
1941             Err(..) => {}
1942         }
1943         // can't link to something that doesn't exist
1944         match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
1945             Ok(..) => panic!("wanted a failure"),
1946             Err(..) => {}
1947         }
1948     }
1949
1950     #[test]
1951     fn chmod_works() {
1952         let tmpdir = tmpdir();
1953         let file = tmpdir.join("in.txt");
1954
1955         check!(File::create(&file));
1956         let attr = check!(fs::metadata(&file));
1957         assert!(!attr.permissions().readonly());
1958         let mut p = attr.permissions();
1959         p.set_readonly(true);
1960         check!(fs::set_permissions(&file, p.clone()));
1961         let attr = check!(fs::metadata(&file));
1962         assert!(attr.permissions().readonly());
1963
1964         match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
1965             Ok(..) => panic!("wanted an error"),
1966             Err(..) => {}
1967         }
1968
1969         p.set_readonly(false);
1970         check!(fs::set_permissions(&file, p));
1971     }
1972
1973     #[test]
1974     fn sync_doesnt_kill_anything() {
1975         let tmpdir = tmpdir();
1976         let path = tmpdir.join("in.txt");
1977
1978         let mut file = check!(File::create(&path));
1979         check!(file.sync_all());
1980         check!(file.sync_data());
1981         check!(file.write(b"foo"));
1982         check!(file.sync_all());
1983         check!(file.sync_data());
1984     }
1985
1986     #[test]
1987     fn truncate_works() {
1988         let tmpdir = tmpdir();
1989         let path = tmpdir.join("in.txt");
1990
1991         let mut file = check!(File::create(&path));
1992         check!(file.write(b"foo"));
1993         check!(file.sync_all());
1994
1995         // Do some simple things with truncation
1996         assert_eq!(check!(file.metadata()).len(), 3);
1997         check!(file.set_len(10));
1998         assert_eq!(check!(file.metadata()).len(), 10);
1999         check!(file.write(b"bar"));
2000         check!(file.sync_all());
2001         assert_eq!(check!(file.metadata()).len(), 10);
2002
2003         let mut v = Vec::new();
2004         check!(check!(File::open(&path)).read_to_end(&mut v));
2005         assert_eq!(v, b"foobar\0\0\0\0".to_vec());
2006
2007         // Truncate to a smaller length, don't seek, and then write something.
2008         // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
2009         // past the end of the file).
2010         check!(file.set_len(2));
2011         assert_eq!(check!(file.metadata()).len(), 2);
2012         check!(file.write(b"wut"));
2013         check!(file.sync_all());
2014         assert_eq!(check!(file.metadata()).len(), 9);
2015         let mut v = Vec::new();
2016         check!(check!(File::open(&path)).read_to_end(&mut v));
2017         assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
2018     }
2019
2020     #[test]
2021     fn open_flavors() {
2022         use fs::OpenOptions as OO;
2023         fn c<T: Clone>(t: &T) -> T { t.clone() }
2024
2025         let tmpdir = tmpdir();
2026
2027         let mut r = OO::new(); r.read(true);
2028         let mut w = OO::new(); w.write(true);
2029         let mut rw = OO::new(); rw.write(true).read(true);
2030
2031         match r.open(&tmpdir.join("a")) {
2032             Ok(..) => panic!(), Err(..) => {}
2033         }
2034
2035         // Perform each one twice to make sure that it succeeds the second time
2036         // (where the file exists)
2037         check!(c(&w).create(true).open(&tmpdir.join("b")));
2038         assert!(tmpdir.join("b").exists());
2039         check!(c(&w).create(true).open(&tmpdir.join("b")));
2040         check!(w.open(&tmpdir.join("b")));
2041
2042         check!(c(&rw).create(true).open(&tmpdir.join("c")));
2043         assert!(tmpdir.join("c").exists());
2044         check!(c(&rw).create(true).open(&tmpdir.join("c")));
2045         check!(rw.open(&tmpdir.join("c")));
2046
2047         check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
2048         assert!(tmpdir.join("d").exists());
2049         check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
2050         check!(c(&w).append(true).open(&tmpdir.join("d")));
2051
2052         check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
2053         assert!(tmpdir.join("e").exists());
2054         check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
2055         check!(c(&rw).append(true).open(&tmpdir.join("e")));
2056
2057         check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
2058         assert!(tmpdir.join("f").exists());
2059         check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
2060         check!(c(&w).truncate(true).open(&tmpdir.join("f")));
2061
2062         check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
2063         assert!(tmpdir.join("g").exists());
2064         check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
2065         check!(c(&rw).truncate(true).open(&tmpdir.join("g")));
2066
2067         check!(check!(File::create(&tmpdir.join("h"))).write("foo".as_bytes()));
2068         check!(r.open(&tmpdir.join("h")));
2069         {
2070             let mut f = check!(r.open(&tmpdir.join("h")));
2071             assert!(f.write("wut".as_bytes()).is_err());
2072         }
2073         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2074         {
2075             let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
2076             check!(f.write("bar".as_bytes()));
2077         }
2078         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
2079         {
2080             let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
2081             check!(f.write("bar".as_bytes()));
2082         }
2083         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2084     }
2085
2086     #[test]
2087     fn binary_file() {
2088         let mut bytes = [0; 1024];
2089         StdRng::new().unwrap().fill_bytes(&mut bytes);
2090
2091         let tmpdir = tmpdir();
2092
2093         check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
2094         let mut v = Vec::new();
2095         check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
2096         assert!(v == &bytes[..]);
2097     }
2098
2099     #[test]
2100     #[cfg(not(windows))]
2101     fn unlink_readonly() {
2102         let tmpdir = tmpdir();
2103         let path = tmpdir.join("file");
2104         check!(File::create(&path));
2105         let mut perm = check!(fs::metadata(&path)).permissions();
2106         perm.set_readonly(true);
2107         check!(fs::set_permissions(&path, perm));
2108         check!(fs::remove_file(&path));
2109     }
2110
2111     #[test]
2112     fn mkdir_trailing_slash() {
2113         let tmpdir = tmpdir();
2114         let path = tmpdir.join("file");
2115         check!(fs::create_dir_all(&path.join("a/")));
2116     }
2117
2118     #[test]
2119     fn canonicalize_works_simple() {
2120         let tmpdir = tmpdir();
2121         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2122         let file = tmpdir.join("test");
2123         File::create(&file).unwrap();
2124         assert_eq!(fs::canonicalize(&file).unwrap(), file);
2125     }
2126
2127     #[test]
2128     #[cfg(not(windows))]
2129     fn realpath_works() {
2130         let tmpdir = tmpdir();
2131         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2132         let file = tmpdir.join("test");
2133         let dir = tmpdir.join("test2");
2134         let link = dir.join("link");
2135         let linkdir = tmpdir.join("test3");
2136
2137         File::create(&file).unwrap();
2138         fs::create_dir(&dir).unwrap();
2139         fs::soft_link(&file, &link).unwrap();
2140         fs::soft_link(&dir, &linkdir).unwrap();
2141
2142         assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
2143
2144         assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
2145         assert_eq!(fs::canonicalize(&file).unwrap(), file);
2146         assert_eq!(fs::canonicalize(&link).unwrap(), file);
2147         assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
2148         assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
2149     }
2150
2151     #[test]
2152     #[cfg(not(windows))]
2153     fn realpath_works_tricky() {
2154         let tmpdir = tmpdir();
2155         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2156
2157         let a = tmpdir.join("a");
2158         let b = a.join("b");
2159         let c = b.join("c");
2160         let d = a.join("d");
2161         let e = d.join("e");
2162         let f = a.join("f");
2163
2164         fs::create_dir_all(&b).unwrap();
2165         fs::create_dir_all(&d).unwrap();
2166         File::create(&f).unwrap();
2167         fs::soft_link("../d/e", &c).unwrap();
2168         fs::soft_link("../f", &e).unwrap();
2169
2170         assert_eq!(fs::canonicalize(&c).unwrap(), f);
2171         assert_eq!(fs::canonicalize(&e).unwrap(), f);
2172     }
2173
2174     #[test]
2175     fn dir_entry_methods() {
2176         let tmpdir = tmpdir();
2177
2178         fs::create_dir_all(&tmpdir.join("a")).unwrap();
2179         File::create(&tmpdir.join("b")).unwrap();
2180
2181         for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
2182             let fname = file.file_name();
2183             match fname.to_str() {
2184                 Some("a") => {
2185                     assert!(file.file_type().unwrap().is_dir());
2186                     assert!(file.metadata().unwrap().is_dir());
2187                 }
2188                 Some("b") => {
2189                     assert!(file.file_type().unwrap().is_file());
2190                     assert!(file.metadata().unwrap().is_file());
2191                 }
2192                 f => panic!("unknown file name: {:?}", f),
2193             }
2194         }
2195     }
2196
2197     #[test]
2198     fn read_dir_not_found() {
2199         let res = fs::read_dir("/path/that/does/not/exist");
2200         assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
2201     }
2202 }