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