]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys_common/fs.rs
Auto merge of #96210 - nnethercote:speed-up-TokenCursor, r=petrochenkov
[rust.git] / library / std / src / sys_common / fs.rs
1 #![allow(dead_code)] // not used on all platforms
2
3 use crate::fs;
4 use crate::io::{self, Error, ErrorKind};
5 use crate::path::Path;
6
7 pub(crate) const NOT_FILE_ERROR: Error = io::const_io_error!(
8     ErrorKind::InvalidInput,
9     "the source path is neither a regular file nor a symlink to a regular file",
10 );
11
12 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
13     let mut reader = fs::File::open(from)?;
14     let metadata = reader.metadata()?;
15
16     if !metadata.is_file() {
17         return Err(NOT_FILE_ERROR);
18     }
19
20     let mut writer = fs::File::create(to)?;
21     let perm = metadata.permissions();
22
23     let ret = io::copy(&mut reader, &mut writer)?;
24     writer.set_permissions(perm)?;
25     Ok(ret)
26 }
27
28 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
29     let filetype = fs::symlink_metadata(path)?.file_type();
30     if filetype.is_symlink() { fs::remove_file(path) } else { remove_dir_all_recursive(path) }
31 }
32
33 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
34     for child in fs::read_dir(path)? {
35         let child = child?;
36         if child.file_type()?.is_dir() {
37             remove_dir_all_recursive(&child.path())?;
38         } else {
39             fs::remove_file(&child.path())?;
40         }
41     }
42     fs::remove_dir(path)
43 }
44
45 pub fn try_exists(path: &Path) -> io::Result<bool> {
46     match fs::metadata(path) {
47         Ok(_) => Ok(true),
48         Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
49         Err(error) => Err(error),
50     }
51 }