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: File = fs::File::open(path:from)?; |
14 | let metadata: Metadata = reader.metadata()?; |
15 | |
16 | if !metadata.is_file() { |
17 | return Err(NOT_FILE_ERROR); |
18 | } |
19 | |
20 | let mut writer: File = fs::File::create(path:to)?; |
21 | let perm: Permissions = metadata.permissions(); |
22 | |
23 | let ret: u64 = 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: 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: Result in fs::read_dir(path)? { |
35 | let child: DirEntry = 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: Error) if error.kind() == io::ErrorKind::NotFound => Ok(false), |
49 | Err(error: Error) => Err(error), |
50 | } |
51 | } |
52 | |