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