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