Skip to main content

std/sys/fs/
common.rs

1#![allow(dead_code)] // not used on all platforms
2
3use crate::fs::{remove_file, rename};
4use crate::io::{self, Error, ErrorKind};
5use crate::path::{Path, PathBuf};
6use crate::sys::IntoInner;
7use crate::sys::fs::{File, FileAttr, OpenOptions};
8use crate::sys::helpers::ignore_notfound;
9use crate::{fmt, fs};
10
11pub(crate) const NOT_FILE_ERROR: Error = io::const_error!(
12    ErrorKind::InvalidInput,
13    "the source path is neither a regular file nor a symlink to a regular file",
14);
15
16pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
17    let mut reader = fs::File::open(from)?;
18    let metadata = reader.metadata()?;
19
20    if !metadata.is_file() {
21        return Err(NOT_FILE_ERROR);
22    }
23
24    let mut writer = fs::File::create(to)?;
25    let perm = metadata.permissions();
26
27    let ret = io::copy(&mut reader, &mut writer)?;
28    writer.set_permissions(perm)?;
29    Ok(ret)
30}
31
32pub fn remove_dir_all(path: &Path) -> io::Result<()> {
33    let filetype = fs::symlink_metadata(path)?.file_type();
34    if filetype.is_symlink() { fs::remove_file(path) } else { remove_dir_all_recursive(path) }
35}
36
37fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
38    for child in fs::read_dir(path)? {
39        let result: io::Result<()> = try {
40            let child = child?;
41            if child.file_type()?.is_dir() {
42                remove_dir_all_recursive(&child.path())?;
43            } else {
44                fs::remove_file(&child.path())?;
45            }
46        };
47        // ignore internal NotFound errors to prevent race conditions
48        if let Err(err) = &result
49            && err.kind() != io::ErrorKind::NotFound
50        {
51            return result;
52        }
53    }
54    ignore_notfound(fs::remove_dir(path))
55}
56
57pub fn exists(path: &Path) -> io::Result<bool> {
58    match fs::metadata(path) {
59        Ok(_) => Ok(true),
60        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
61        Err(error) => Err(error),
62    }
63}
64
65pub struct Dir {
66    path: PathBuf,
67}
68
69impl Dir {
70    pub fn open(path: &Path, _opts: &OpenOptions) -> io::Result<Self> {
71        path.canonicalize().map(|path| Self { path })
72    }
73
74    pub fn open_file(&self, path: &Path, opts: &OpenOptions) -> io::Result<File> {
75        File::open(&self.path.join(path), &opts)
76    }
77
78    pub fn metadata(&self) -> io::Result<FileAttr> {
79        self.path.metadata().map(|m| m.into_inner())
80    }
81
82    pub fn remove_file(&self, path: &Path) -> io::Result<()> {
83        remove_file(self.path.join(path))
84    }
85
86    pub fn rename(&self, from: &Path, to_dir: &Self, to: &Path) -> io::Result<()> {
87        rename(self.path.join(from), to_dir.path.join(to))
88    }
89}
90
91impl fmt::Debug for Dir {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        f.debug_struct("Dir").field("path", &self.path).finish()
94    }
95}