Skip to main content

std/sys/fs/
common.rs

1#![allow(dead_code)] // not used on all platforms
2
3use crate::fs::{create_dir, remove_dir, 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 = ::core::hint::must_use(::core::io::Error::from_static_message(const {
                &::core::io::SimpleMessage {
                        kind: ErrorKind::InvalidInput,
                        message: "the source path is neither a regular file nor a symlink to a regular file",
                    }
            }))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_for_traversal(path: &Path) -> io::Result<Self> {
75        let mut opts = OpenOptions::new();
76        opts.read(true);
77        Self::open(path, &opts)
78    }
79
80    pub fn open_file(&self, path: &Path, opts: &OpenOptions) -> io::Result<File> {
81        File::open(&self.path.join(path), opts)
82    }
83
84    pub fn metadata(&self) -> io::Result<FileAttr> {
85        self.path.metadata().map(|m| m.into_inner())
86    }
87
88    pub fn remove_file(&self, path: &Path) -> io::Result<()> {
89        remove_file(self.path.join(path))
90    }
91
92    pub fn rename(&self, from: &Path, to_dir: &Self, to: &Path) -> io::Result<()> {
93        rename(self.path.join(from), to_dir.path.join(to))
94    }
95
96    pub fn create_dir(&self, path: &Path) -> io::Result<()> {
97        create_dir(self.path.join(path))
98    }
99
100    pub fn open_dir(&self, path: &Path, opts: &OpenOptions) -> io::Result<Self> {
101        Self::open(&self.path.join(path), opts)
102    }
103
104    pub fn remove_dir(&self, path: &Path) -> io::Result<()> {
105        remove_dir(path)
106    }
107}
108
109impl fmt::Debug for Dir {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        f.debug_struct("Dir").field("path", &self.path).finish()
112    }
113}