1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
pub mod buffer;
pub mod dir;
pub mod file;
pub mod recover;
pub(crate) mod web;
pub use dir::DirectoryInfo;
pub use file::FileInfo;
use std::collections::VecDeque;
use crate::recover::RecoverError;
use std::env::current_dir;
use std::ffi::OsStr;
use std::fs;
use std::fs::{metadata, remove_dir_all, remove_file, Metadata, Permissions};
use std::io::{Error, ErrorKind, Result};
use std::path::{Path, PathBuf};
pub type RecoverResult<'a> = std::result::Result<(), RecoverError<'a>>;
pub trait FileAttr: Sized {
fn as_path(&self) -> &Path;
/// Returns None if the path is root directory
fn file_name(&self) -> Option<&OsStr> {
self.as_path().file_name()
}
fn metadata(&self) -> Result<Metadata> {
metadata(self.as_path())
}
fn size(&self) -> u64;
/// Return None if the path is a root directory
fn parent(&self) -> Option<DirectoryInfo> {
self.as_path().parent().and_then(|path| {
Some(DirectoryInfo {
path: path.to_path_buf(),
})
})
}
/// Rename a file or directory
///
/// # Examples
/// ```no_run
/// use fdir::{FileAttr, FileInfo};
/// let mut file = FileInfo::create("foo.txt").unwrap();
/// file.rename("bar").unwrap(); // or bar.txt
/// assert_eq!(file.file_name(), Some("bar.txt".as_ref()))
/// ```
///
fn rename<T: AsRef<OsStr>>(&mut self, name: T) -> Result<()>;
fn permissions(&self) -> Result<Permissions> {
self.metadata().and_then(|data| Ok(data.permissions()))
}
fn set_permissions(&self, perm: Permissions) -> Result<()> {
fs::set_permissions(self.as_path(), perm)
}
fn read_only(&self) -> Result<bool> {
self.metadata()
.and_then(|data| Ok(data.permissions().readonly()))
}
fn set_readonly(&self, readonly: bool) -> Result<()> {
let mut perm = self.metadata()?.permissions();
perm.set_readonly(readonly);
self.set_permissions(perm)
}
fn delete(self) -> Result<()> {
if self.read_only()? {
self.set_readonly(false)?;
}
if self.as_path().is_dir() {
remove_dir_all(self.as_path())
} else {
remove_file(self.as_path())
}
}
fn eq(&self, other: &Self) -> bool;
/// Copy a file or directory to a new directory
///
/// # Examples
///
/// ```no_run
/// use fdir::{FileInfo, FileAttr};
///
/// let f = FileInfo::create("foo.txt").unwrap();
/// f.copy_to("test").unwrap();
/// assert!(FileInfo::open("test/foo.txt").is_ok())
/// ```
///
/// # Repairable Error
///
/// If the destination path already exists, return an error that can be recovered
///
/// # Example
/// ```no_run
/// use fdir::{FileInfo, FileAttr};
///
/// FileInfo::create("test/foo.txt").unwrap();
/// let f = FileInfo::create("foo.txt").unwrap();
/// let res = f.copy_to("test");
/// assert!(res.is_err());
/// let res = f.copy_to("test").or_else(|e| e.try_recover());
/// assert!(res.is_ok())
/// ```
///
fn copy_to<P: AsRef<Path>>(&self, path: P) -> RecoverResult {
let path = complete_file_name(path, self.as_path().file_name())?;
self.copy_new(path)
}
/// Copy a file or directory to a new destination path
///
/// # Examples
/// ```no_run
/// use fdir::{FileInfo, FileAttr};
/// let f = FileInfo::create("foo.txt").unwrap();
/// f.copy_new("test/bar.txt").unwrap();
/// assert!(FileInfo::open("test/bar.txt").is_ok())
/// ```
///
/// # Repairable Error
///
/// If the destination path already exists, return an error that can be recovered
///
/// # Example
/// ```no_run
/// use fdir::{FileInfo, FileAttr};
/// FileInfo::create("test/foo.txt").unwrap();
/// let f = FileInfo::create("foo.txt").unwrap();
///
/// let res = f.copy_new("test/foo.txt");
/// assert!(res.is_err());
/// let res = f.copy_new("test/foo.txt").or_else(|e| e.try_recover());
/// assert!(res.is_ok())
/// ```
fn copy_new<P: AsRef<Path>>(&self, path: P) -> RecoverResult;
/// Move a file or directory to a new directory
///
/// # Examples
///
/// ```no_run
/// use std::env::current_dir;
/// use fdir::{FileInfo, FileAttr};
/// let mut f = FileInfo::create("foo.txt").unwrap();
/// f.move_to("test").unwrap();
/// let mut current_dir = current_dir().unwrap();
/// current_dir.push("test/foo.txt");
/// assert_eq!(f.as_path(), current_dir.as_path());
/// ```
///
/// # Repairable Error
///
/// If the destination path already exists, return an error that can be recovered
///
/// # Example
/// ```no_run
/// use fdir::{FileInfo, FileAttr};
/// FileInfo::create("test/foo.txt").unwrap();
/// let mut f = FileInfo::create("foo.txt").unwrap();
///
/// let res = f.move_to("test");
/// assert!(res.is_err());
/// let res = f.move_to("test").or_else(|e| e.try_recover());
/// assert!(res.is_ok())
/// ```
///
fn move_to<P: AsRef<Path>>(&mut self, path: P) -> RecoverResult {
let path = complete_file_name(path, self.as_path().file_name())?;
self.move_new(path)
}
/// Move a file or directory to a new destination path
///
/// # Examples
/// ```no_run
/// use std::env::current_dir;
/// use fdir::{FileInfo, FileAttr};
///
/// let mut f = FileInfo::create("foo.txt").unwrap();
/// f.move_new("test/bar.txt").unwrap();
/// let mut current_dir = current_dir().unwrap();
/// current_dir.push("test/bar.txt");
/// assert_eq!(f.as_path(), current_dir.as_path());
/// ```
///
/// # Repairable Error
///
/// If the destination path already exists, return an error that can be recovered
///
/// # Example
/// ```no_run
/// use fdir::{FileInfo, FileAttr};
/// FileInfo::create("test/foo.txt").unwrap();
/// let mut f = FileInfo::create("foo.txt").unwrap();
///
/// let res = f.move_new("test/foo.txt");
/// assert!(res.is_err());
/// let res = f.move_new("test/foo.txt").or_else(|e| e.try_recover());
/// assert!(res.is_ok())
/// ```
fn move_new<P: AsRef<Path>>(&mut self, path: P) -> RecoverResult;
}
fn complete_file_name<P: AsRef<Path>>(path: P, file_name: Option<&OsStr>) -> Result<PathBuf> {
let mut path = fix_path(path)?;
match file_name {
Some(name) => {
path.push(name);
Ok(path)
}
_ => Err(Error::new(
ErrorKind::PermissionDenied,
format!("Cannot get the file name in {} ", path.display()),
)),
}
}
#[inline]
pub(crate) fn fix_path(path: impl AsRef<Path>) -> Result<PathBuf> {
let path = path.as_ref().to_path_buf();
if path.is_relative() {
let mut fix_path = current_dir()?;
match path.to_str() {
Some(path) => match path.replace("\\", "/").as_str() {
"" | "." | "./" => (),
".." | "../" => {
fix_path.pop();
}
"/" => while fix_path.pop() {},
"~" => {
if let Some(home) = dirs::home_dir() {
fix_path = home
} else {
return Err(Error::new(
ErrorKind::Unsupported,
"Path '~' not supported!",
));
}
}
_ => {
fix_path.push(path);
}
},
_ => {
fix_path.push(path);
}
}
Ok(fix_path)
} else {
Ok(path)
}
}
fn _fix_path(_path: &str, _current_dir: PathBuf) -> PathBuf {
todo!()
}
#[inline]
pub(crate) fn is_exist(path: &Path) -> bool {
path.try_exists().unwrap_or_default()
}
#[inline]
pub(crate) fn replace(path: &Path, base: &Path, to: &Path) -> PathBuf {
let path_queue: VecDeque<_> = path.iter().map(|path| path).collect();
let base_queue: VecDeque<_> = base.iter().map(|path| path).collect();
let mut to = to.to_path_buf();
let mut i = 0;
while i < base_queue.len() && path_queue.get(i) == base_queue.get(i) {
i += 1;
}
for j in i..path_queue.len() {
to.push(path_queue[j])
}
to
}
#[inline]
pub(crate) fn is_same_root(path: &Path, to: &Path) -> bool {
let mut path = path.to_path_buf();
while path.pop() {
// empty
}
to.starts_with(path)
}
#[inline]
fn _delete_file(file: &FileInfo) -> Result<()> {
if file.read_only()? {
file.set_readonly(false)?
}
remove_file(file.as_path())
}