| 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 | use crate::sys_common::ignore_notfound; |
| 7 | |
| 8 | pub(crate) const NOT_FILE_ERROR: Error = io::const_error!( |
| 9 | ErrorKind::InvalidInput, |
| 10 | "the source path is neither a regular file nor a symlink to a regular file", |
| 11 | ); |
| 12 | |
| 13 | pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { |
| 14 | let mut reader: File = fs::File::open(path:from)?; |
| 15 | let metadata: Metadata = reader.metadata()?; |
| 16 | |
| 17 | if !metadata.is_file() { |
| 18 | return Err(NOT_FILE_ERROR); |
| 19 | } |
| 20 | |
| 21 | let mut writer: File = fs::File::create(path:to)?; |
| 22 | let perm: Permissions = metadata.permissions(); |
| 23 | |
| 24 | let ret: u64 = io::copy(&mut reader, &mut writer)?; |
| 25 | writer.set_permissions(perm)?; |
| 26 | Ok(ret) |
| 27 | } |
| 28 | |
| 29 | pub fn remove_dir_all(path: &Path) -> io::Result<()> { |
| 30 | let filetype: FileType = fs::symlink_metadata(path)?.file_type(); |
| 31 | if filetype.is_symlink() { fs::remove_file(path) } else { remove_dir_all_recursive(path) } |
| 32 | } |
| 33 | |
| 34 | fn remove_dir_all_recursive(path: &Path) -> io::Result<()> { |
| 35 | for child: Result |
| 36 | let result: io::Result<()> = try { |
| 37 | let child: DirEntry = child?; |
| 38 | if child.file_type()?.is_dir() { |
| 39 | remove_dir_all_recursive(&child.path())?; |
| 40 | } else { |
| 41 | fs::remove_file(&child.path())?; |
| 42 | } |
| 43 | }; |
| 44 | // ignore internal NotFound errors to prevent race conditions |
| 45 | if let Err(err: &Error) = &result |
| 46 | && err.kind() != io::ErrorKind::NotFound |
| 47 | { |
| 48 | return result; |
| 49 | } |
| 50 | } |
| 51 | ignore_notfound(result:fs::remove_dir(path)) |
| 52 | } |
| 53 | |
| 54 | pub fn exists(path: &Path) -> io::Result<bool> { |
| 55 | match fs::metadata(path) { |
| 56 | Ok(_) => Ok(true), |
| 57 | Err(error: Error) if error.kind() == io::ErrorKind::NotFound => Ok(false), |
| 58 | Err(error: Error) => Err(error), |
| 59 | } |
| 60 | } |
| 61 |
