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