From 37dedb35ed71e4c43af3af7d39ae5d722c8b5a94 Mon Sep 17 00:00:00 2001 From: Sebastian Thiel Date: Mon, 30 Jan 2023 11:16:25 +0100 Subject: [PATCH] thanks clippy --- rustfmt.toml | 1 + src/freedesktop.rs | 111 ++++++++++++++------------------------------- src/lib.rs | 21 +++------ src/macos.rs | 18 +++----- src/tests.rs | 71 +++++++++-------------------- src/windows.rs | 32 ++++--------- tests/trash.rs | 4 +- 7 files changed, 80 insertions(+), 178 deletions(-) diff --git a/rustfmt.toml b/rustfmt.toml index 78304e4..b6ec578 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -2,3 +2,4 @@ edition = "2018" use_try_shorthand = true use_field_init_shorthand = true use_small_heuristics = "Max" +max_width = 120 diff --git a/src/freedesktop.rs b/src/freedesktop.rs index 0c4eb0f..331eaa8 100644 --- a/src/freedesktop.rs +++ b/src/freedesktop.rs @@ -60,7 +60,9 @@ pub fn list() -> Result, Error> { Ok(home_trash) => { if !home_trash.is_dir() { home_error = Some(Error::Unknown { - description: "The 'home trash' either does not exist or is not a directory (or a link pointing to a dir)".into() + description: + "The 'home trash' either does not exist or is not a directory (or a link pointing to a dir)" + .into(), }); } else { trash_folders.insert(home_trash); @@ -83,10 +85,7 @@ pub fn list() -> Result, Error> { })?; } if trash_folders.is_empty() { - warn!( - "No trash folder was found. The error when looking for the 'home trash' was: {:?}", - home_error - ); + warn!("No trash folder was found. The error when looking for the 'home trash' was: {:?}", home_error); return Ok(vec![]); } // List all items from the set of trash folders @@ -96,10 +95,7 @@ pub fn list() -> Result, Error> { let top_dir = get_topdir_for_path(folder, &mount_points); let info_folder = folder.join("info"); if !info_folder.is_dir() { - warn!( - "The path {:?} did not point to a directory, skipping this trash folder.", - info_folder - ); + warn!("The path {:?} did not point to a directory, skipping this trash folder.", info_folder); continue; } let read_dir = match std::fs::read_dir(&info_folder) { @@ -108,10 +104,7 @@ pub fn list() -> Result, Error> { // After all the earlier checks, it's still possible that the directory does not exist at this point (or is not readable) // because another process may have deleted it or modified its access rights in the meantime. // So let's just pring a warning and continue to the rest of the folders - warn!( - "The trash info folder {:?} could not be read. Error was {:?}", - info_folder, e - ); + warn!("The trash info folder {:?} could not be read. Error was {:?}", info_folder, e); continue; } }; @@ -193,7 +186,10 @@ pub fn list() -> Result, Error> { match time { Some(time) => time_deleted = Some(time.timestamp()), None => { - log::error!("Failed to convert the local time to a UTC time. Local time was {:?}", naive_local); + log::error!( + "Failed to convert the local time to a UTC time. Local time was {:?}", + naive_local + ); continue 'trash_item; } } @@ -205,12 +201,7 @@ pub fn list() -> Result, Error> { if time_deleted.is_none() { warn!("Could not determine the deletion time of the trash item. (The `DeletionDate` field is probably missing from the info file.) The info file path is: '{:?}'", info_path); } - result.push(TrashItem { - id, - name, - original_parent, - time_deleted: time_deleted.unwrap_or(-1), - }); + result.push(TrashItem { id, name, original_parent, time_deleted: time_deleted.unwrap_or(-1) }); } else { warn!("Could not determine the original parent folder of the trash item. (The `Path` field is probably missing from the info file.) The info file path is: '{:?}'", info_path); } @@ -277,8 +268,7 @@ where // if it already exists. let original_path = item.original_path(); // Make sure the parent exists so that `create_dir` doesn't faile due to that. - create_dir_all(&item.original_parent) - .map_err(|e| fsys_err_to_unknown(&item.original_parent, e))?; + create_dir_all(&item.original_parent).map_err(|e| fsys_err_to_unknown(&item.original_parent, e))?; let mut collision = false; if file.is_dir() { // NOTE create_dir_all succeeds when the path already exist but create_dir @@ -302,10 +292,7 @@ where } if collision { let remaining: Vec<_> = std::iter::once(item).chain(iter).collect(); - return Err(Error::RestoreCollision { - path: original_path, - remaining_items: remaining, - }); + return Err(Error::RestoreCollision { path: original_path, remaining_items: remaining }); } std::fs::rename(&file, &original_path).map_err(|e| fsys_err_to_unknown(&file, e))?; std::fs::remove_file(info_file).map_err(|e| fsys_err_to_unknown(info_file, e))?; @@ -342,14 +329,11 @@ fn execute_on_mounted_trash_folders Result<(), Error>>( } } } else { - warn!( - "A Trash folder was found at '{:?}', but it's invalid because it's {:?}", - trash_path, validity - ); + warn!("A Trash folder was found at '{:?}', but it's invalid because it's {:?}", trash_path, validity); } } // See if there's a ".Trash-$UID" directory at the mounted location - let trash_path = topdir.join(format!(".Trash-{}", uid)); + let trash_path = topdir.join(format!(".Trash-{uid}")); let should_execute; if !trash_path.exists() || !trash_path.is_dir() { if create_folder { @@ -405,7 +389,7 @@ fn move_to_trash( } else { filename.to_str().unwrap().into() }; - let info_name = format!("{}.trashinfo", in_trash_name); + let info_name = format!("{in_trash_name}.trashinfo"); let info_file_path = info_folder.join(&info_name); let info_result = OpenOptions::new().create_new(true).write(true).open(&info_file_path); match info_result { @@ -423,7 +407,7 @@ fn move_to_trash( writeln!(file, "[Trash Info]") .and_then(|_| { let absolute_uri = encode_uri_path(src); - writeln!(file, "Path={}", absolute_uri).and_then(|_| { + writeln!(file, "Path={absolute_uri}").and_then(|_| { #[cfg(feature = "chrono")] { let now = chrono::Local::now(); @@ -495,10 +479,7 @@ where } /// An error may mean that a collision was found. -fn move_items_no_replace( - src: impl AsRef, - dst: impl AsRef, -) -> Result<(), std::io::Error> { +fn move_items_no_replace(src: impl AsRef, dst: impl AsRef) -> Result<(), std::io::Error> { let src = src.as_ref(); let dst = dst.as_ref(); @@ -508,10 +489,7 @@ fn move_items_no_replace( execute_src_to_dst_operation(src, dst, &|_| Ok(()), &|src, dst| { if let Some(parent) = dst.parent() { if let Err(err) = std::fs::create_dir_all(parent) { - warn!( - "Failed to create destination directory. It probably already exists. {:?}", - err - ); + warn!("Failed to create destination directory. It probably already exists. {:?}", err); } } std::fs::rename(src, dst) @@ -524,10 +502,7 @@ fn move_items_no_replace( Ok(()) } -fn try_creating_placeholders( - src: impl AsRef, - dst: impl AsRef, -) -> Result<(), std::io::Error> { +fn try_creating_placeholders(src: impl AsRef, dst: impl AsRef) -> Result<(), std::io::Error> { let src = src.as_ref(); let dst = dst.as_ref(); let metadata = src.symlink_metadata()?; @@ -591,9 +566,7 @@ fn home_trash() -> Result { return Ok(home_path.join(".local/share/Trash")); } } - Err(Error::Unknown { - description: "Neither the XDG_DATA_HOME nor the HOME environment variable was found".into(), - }) + Err(Error::Unknown { description: "Neither the XDG_DATA_HOME nor the HOME environment variable was found".into() }) } fn home_topdir(mnt_points: &[MountPoint]) -> Result { @@ -609,9 +582,7 @@ fn home_topdir(mnt_points: &[MountPoint]) -> Result { return Ok(get_topdir_for_path(home_path, mnt_points).to_owned()); } } - Err(Error::Unknown { - description: "Neither the XDG_DATA_HOME nor the HOME environment variable was found".into(), - }) + Err(Error::Unknown { description: "Neither the XDG_DATA_HOME nor the HOME environment variable was found".into() }) } fn get_topdir_for_path<'a>(path: &Path, mnt_points: &'a [MountPoint]) -> &'a Path { @@ -659,16 +630,13 @@ fn get_mount_points() -> Result, Error> { //let file; let read_arg = CString::new("r").unwrap(); let mounts_path = CString::new("/proc/mounts").unwrap(); - let mut file = - unsafe { libc::fopen(mounts_path.as_c_str().as_ptr(), read_arg.as_c_str().as_ptr()) }; + let mut file = unsafe { libc::fopen(mounts_path.as_c_str().as_ptr(), read_arg.as_c_str().as_ptr()) }; if file.is_null() { let mtab_path = CString::new("/etc/mtab").unwrap(); file = unsafe { libc::fopen(mtab_path.as_c_str().as_ptr(), read_arg.as_c_str().as_ptr()) }; } if file.is_null() { - return Err(Error::Unknown { - description: "Neither '/proc/mounts' nor '/etc/mtab' could be opened.".into(), - }); + return Err(Error::Unknown { description: "Neither '/proc/mounts' nor '/etc/mtab' could be opened.".into() }); } defer! { unsafe { libc::fclose(file); } } let mut result = Vec::new(); @@ -692,9 +660,7 @@ fn get_mount_points() -> Result, Error> { } if result.is_empty() { return Err(Error::Unknown { - description: - "A mount points file could be opened, but the call to `getmntent` returned NULL." - .into(), + description: "A mount points file could be opened, but the call to `getmntent` returned NULL.".into(), }); } Ok(result) @@ -729,8 +695,7 @@ fn get_mount_points() -> Result, Error> { if count < 1 { return Ok(Vec::new()); } - let fs_infos: &[libc::statfs] = - unsafe { std::slice::from_raw_parts(fs_infos as _, count as _) }; + let fs_infos: &[libc::statfs] = unsafe { std::slice::from_raw_parts(fs_infos as _, count as _) }; let mut result = Vec::new(); for fs_info in fs_infos { @@ -748,11 +713,8 @@ fn get_mount_points() -> Result, Error> { }; let mount_from = c_buf_to_str(&fs_info.f_mntfromname).unwrap_or_default(); - let mount_point = MountPoint { - mnt_dir: mount_to.into(), - _mnt_fsname: mount_from.into(), - _mnt_type: fs_type.into(), - }; + let mount_point = + MountPoint { mnt_dir: mount_to.into(), _mnt_fsname: mount_from.into(), _mnt_type: fs_type.into() }; result.push(mount_point); } Ok(result) @@ -788,8 +750,7 @@ mod tests { let file_name_prefix = get_unique_name(); let batches: usize = 2; let files_per_batch: usize = 3; - let names: Vec<_> = - (0..files_per_batch).map(|i| format!("{}#{}", file_name_prefix, i)).collect(); + let names: Vec<_> = (0..files_per_batch).map(|i| format!("{}#{}", file_name_prefix, i)).collect(); for _ in 0..batches { for path in names.iter() { File::create(path).unwrap(); @@ -798,19 +759,15 @@ mod tests { let result = delete_all_using_system_program(&names); if let Err(SystemTrashError::NoTrashProgram) = &result { // For example may be the case on build systems that don't have a destop environment - warn!( - "No system default trashing utility was found, using this crate's implementation" - ); + warn!("No system default trashing utility was found, using this crate's implementation"); delete_all(&names).unwrap(); } else { result.unwrap(); } } let items = list().unwrap(); - let items: HashMap<_, Vec<_>> = items - .into_iter() - .filter(|x| x.name.starts_with(&file_name_prefix)) - .fold(HashMap::new(), |mut map, x| { + let items: HashMap<_, Vec<_>> = + items.into_iter().filter(|x| x.name.starts_with(&file_name_prefix)).fold(HashMap::new(), |mut map, x| { match map.entry(x.name.clone()) { Entry::Occupied(mut entry) => { entry.get_mut().push(x); @@ -863,9 +820,7 @@ mod tests { /// This is based on the electron library's implementation. /// See: https://github.com/electron/electron/blob/34c4c8d5088fa183f56baea28809de6f2a427e02/shell/common/platform_util_linux.cc#L96 - pub fn delete_all_canonicalized_using_system_program( - full_paths: Vec, - ) -> Result<(), SystemTrashError> { + pub fn delete_all_canonicalized_using_system_program(full_paths: Vec) -> Result<(), SystemTrashError> { static DEFAULT_TRASH: &str = "gio"; let trash = { // Determine desktop environment and set accordingly. diff --git a/src/lib.rs b/src/lib.rs index b59aa57..fbbb7ee 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -143,12 +143,7 @@ pub enum Error { /// **freedesktop only** /// /// Error coming from file system - #[cfg(all( - unix, - not(target_os = "macos"), - not(target_os = "ios"), - not(target_os = "android") - ))] + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] FileSystem { path: PathBuf, kind: std::io::ErrorKind, @@ -211,12 +206,12 @@ pub enum Error { } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Error during a `trash` operation: {:?}", self) + write!(f, "Error during a `trash` operation: {self:?}") } } impl error::Error for Error {} pub fn into_unknown(err: E) -> Error { - Error::Unknown { description: format!("{}", err) } + Error::Unknown { description: format!("{err}") } } pub(crate) fn canonicalize_paths(paths: I) -> Result, Error> @@ -229,17 +224,15 @@ where .map(|x| { let target_ref = x.as_ref(); let target = if target_ref.is_relative() { - let curr_dir = current_dir().map_err(|_| Error::CouldNotAccess { - target: "[Current working directory]".into(), - })?; + let curr_dir = current_dir() + .map_err(|_| Error::CouldNotAccess { target: "[Current working directory]".into() })?; curr_dir.join(target_ref) } else { target_ref.to_owned() }; let parent = target.parent().ok_or(Error::TargetedRoot)?; - let canonical_parent = parent - .canonicalize() - .map_err(|_| Error::CanonicalizePath { original: parent.to_owned() })?; + let canonical_parent = + parent.canonicalize().map_err(|_| Error::CanonicalizePath { original: parent.to_owned() })?; if let Some(file_name) = target.file_name() { Ok(canonical_parent.join(file_name)) } else { diff --git a/src/macos.rs b/src/macos.rs index a127907..dbdff4c 100644 --- a/src/macos.rs +++ b/src/macos.rs @@ -98,7 +98,7 @@ fn delete_using_file_mgr(full_paths: Vec) -> Result<(), Error> { let url: id = unsafe { msg_send![url_cls, fileURLWithPath:string.ptr] }; if url == nil { return Err(Error::Unknown { - description: format!("Failed to convert a path to an NSURL. Path: '{}'", path), + description: format!("Failed to convert a path to an NSURL. Path: '{path}'"), }); } trace!("Finished fileURLWithPath"); @@ -121,9 +121,8 @@ fn delete_using_file_mgr(full_paths: Vec) -> Result<(), Error> { if error == nil { return Err(Error::Unknown { description: format!( - "While deleting '{}', `trashItemAtURL` returned with failure but no error was specified.", - path - ) + "While deleting '{path}', `trashItemAtURL` returned with failure but no error was specified.", + ), }); } let code: isize = unsafe { msg_send![error, code] }; @@ -131,8 +130,7 @@ fn delete_using_file_mgr(full_paths: Vec) -> Result<(), Error> { let domain = unsafe { ns_string_to_rust(domain)? }; return Err(Error::Unknown { description: format!( - "While deleting '{}', `trashItemAtURL` failed, code: {}, domain: {}", - path, code, domain + "While deleting '{path}', `trashItemAtURL` failed, code: {code}, domain: {domain}", ), }); } @@ -145,12 +143,8 @@ fn delete_using_finder(full_paths: Vec) -> Result<(), Error> { // osascript -e 'tell application "Finder" to delete { POSIX file "file1", POSIX "file2" }' // The `-e` flag is used to execute only one line of AppleScript. let mut command = Command::new("osascript"); - let posix_files = full_paths - .into_iter() - .map(|p| format!("POSIX file \"{}\"", p)) - .collect::>() - .join(", "); - let script = format!("tell application \"Finder\" to delete {{ {} }}", posix_files); + let posix_files = full_paths.into_iter().map(|p| format!("POSIX file \"{p}\"")).collect::>().join(", "); + let script = format!("tell application \"Finder\" to delete {{ {posix_files} }}"); let argv: Vec = vec!["-e".into(), script.into()]; command.args(argv); diff --git a/src/tests.rs b/src/tests.rs index 7adf85f..2fae2ab 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -45,8 +45,7 @@ mod os_limited { let file_name_prefix = get_unique_name(); let batches: usize = 2; let files_per_batch: usize = 3; - let names: Vec<_> = - (0..files_per_batch).map(|i| format!("{}#{}", file_name_prefix, i)).collect(); + let names: Vec<_> = (0..files_per_batch).map(|i| format!("{}#{}", file_name_prefix, i)).collect(); for _ in 0..batches { for path in names.iter() { File::create(path).unwrap(); @@ -54,10 +53,8 @@ mod os_limited { trash::delete_all(&names).unwrap(); } let items = trash::os_limited::list().unwrap(); - let items: HashMap<_, Vec<_>> = items - .into_iter() - .filter(|x| x.name.starts_with(&file_name_prefix)) - .fold(HashMap::new(), |mut map, x| { + let items: HashMap<_, Vec<_>> = + items.into_iter().filter(|x| x.name.starts_with(&file_name_prefix)).fold(HashMap::new(), |mut map, x| { match map.entry(x.name.clone()) { Entry::Occupied(mut entry) => { entry.get_mut().push(x); @@ -113,8 +110,7 @@ mod os_limited { let file_name_prefix = get_unique_name(); let batches: usize = 2; let files_per_batch: usize = 3; - let names: Vec<_> = - (0..files_per_batch).map(|i| format!("{}#{}", file_name_prefix, i)).collect(); + let names: Vec<_> = (0..files_per_batch).map(|i| format!("{}#{}", file_name_prefix, i)).collect(); for _ in 0..batches { for path in names.iter() { File::create(path).unwrap(); @@ -123,18 +119,12 @@ mod os_limited { } // Collect it because we need the exact number of items gathered. - let targets: Vec<_> = trash::os_limited::list() - .unwrap() - .into_iter() - .filter(|x| x.name.starts_with(&file_name_prefix)) - .collect(); + let targets: Vec<_> = + trash::os_limited::list().unwrap().into_iter().filter(|x| x.name.starts_with(&file_name_prefix)).collect(); assert_eq!(targets.len(), batches * files_per_batch); trash::os_limited::purge_all(targets).unwrap(); - let remaining = trash::os_limited::list() - .unwrap() - .into_iter() - .filter(|x| x.name.starts_with(&file_name_prefix)) - .count(); + let remaining = + trash::os_limited::list().unwrap().into_iter().filter(|x| x.name.starts_with(&file_name_prefix)).count(); assert_eq!(remaining, 0); } @@ -144,26 +134,19 @@ mod os_limited { init_logging(); let file_name_prefix = get_unique_name(); let file_count: usize = 3; - let names: Vec<_> = - (0..file_count).map(|i| format!("{}#{}", file_name_prefix, i)).collect(); + let names: Vec<_> = (0..file_count).map(|i| format!("{}#{}", file_name_prefix, i)).collect(); for path in names.iter() { File::create(path).unwrap(); } trash::delete_all(&names).unwrap(); // Collect it because we need the exact number of items gathered. - let targets: Vec<_> = trash::os_limited::list() - .unwrap() - .into_iter() - .filter(|x| x.name.starts_with(&file_name_prefix)) - .collect(); + let targets: Vec<_> = + trash::os_limited::list().unwrap().into_iter().filter(|x| x.name.starts_with(&file_name_prefix)).collect(); assert_eq!(targets.len(), file_count); trash::os_limited::restore_all(targets).unwrap(); - let remaining = trash::os_limited::list() - .unwrap() - .into_iter() - .filter(|x| x.name.starts_with(&file_name_prefix)) - .count(); + let remaining = + trash::os_limited::list().unwrap().into_iter().filter(|x| x.name.starts_with(&file_name_prefix)).count(); assert_eq!(remaining, 0); // They are not in the trash anymore but they should be at their original location @@ -187,8 +170,7 @@ mod os_limited { let file_name_prefix = get_unique_name(); let file_count: usize = 3; let collision_remaining = file_count - 1; - let names: Vec<_> = - (0..file_count).map(|i| format!("{}#{}", file_name_prefix, i)).collect(); + let names: Vec<_> = (0..file_count).map(|i| format!("{}#{}", file_name_prefix, i)).collect(); for path in names.iter() { File::create(path).unwrap(); } @@ -196,11 +178,8 @@ mod os_limited { for path in names.iter().skip(file_count - collision_remaining) { File::create(path).unwrap(); } - let mut targets: Vec<_> = trash::os_limited::list() - .unwrap() - .into_iter() - .filter(|x| x.name.starts_with(&file_name_prefix)) - .collect(); + let mut targets: Vec<_> = + trash::os_limited::list().unwrap().into_iter().filter(|x| x.name.starts_with(&file_name_prefix)).collect(); targets.sort_by(|a, b| a.name.cmp(&b.name)); assert_eq!(targets.len(), file_count); let remaining_count; @@ -224,9 +203,7 @@ mod os_limited { for path in names.iter() { std::fs::remove_file(path).ok(); } - panic!( - "restore_all was expected to return `trash::ErrorKind::RestoreCollision` but did not." - ); + panic!("restore_all was expected to return `trash::ErrorKind::RestoreCollision` but did not."); } } let remaining = trash::os_limited::list() @@ -248,8 +225,7 @@ mod os_limited { init_logging(); let file_name_prefix = get_unique_name(); let file_count: usize = 4; - let names: Vec<_> = - (0..file_count).map(|i| format!("{}#{}", file_name_prefix, i)).collect(); + let names: Vec<_> = (0..file_count).map(|i| format!("{}#{}", file_name_prefix, i)).collect(); for path in names.iter() { File::create(path).unwrap(); } @@ -259,11 +235,8 @@ mod os_limited { File::create(twin_name).unwrap(); trash::delete(&twin_name).unwrap(); - let mut targets: Vec<_> = trash::os_limited::list() - .unwrap() - .into_iter() - .filter(|x| x.name.starts_with(&file_name_prefix)) - .collect(); + let mut targets: Vec<_> = + trash::os_limited::list().unwrap().into_iter().filter(|x| x.name.starts_with(&file_name_prefix)).collect(); targets.sort_by(|a, b| a.name.cmp(&b.name)); assert_eq!(targets.len(), file_count + 1); // plus one for one of the twins match trash::os_limited::restore_all(targets) { @@ -271,9 +244,7 @@ mod os_limited { assert_eq!(path.file_name().unwrap().to_str().unwrap(), twin_name); trash::os_limited::purge_all(items).unwrap(); } - _ => panic!( - "restore_all was expected to return `trash::ErrorKind::RestoreTwins` but did not." - ), + _ => panic!("restore_all was expected to return `trash::ErrorKind::RestoreTwins` but did not."), } } } diff --git a/src/windows.rs b/src/windows.rs index 3f4426b..d9a317e 100644 --- a/src/windows.rs +++ b/src/windows.rs @@ -14,10 +14,8 @@ const PSGUID_DISPLACED: GUID = GUID::from_values(0x9b174b33, 0x40ff, 0x11d2, [0xa2, 0x7e, 0x00, 0xc0, 0x4f, 0xc3, 0x8, 0x71]); const PID_DISPLACED_FROM: u32 = 2; const PID_DISPLACED_DATE: u32 = 3; -const SCID_ORIGINAL_LOCATION: PROPERTYKEY = - PROPERTYKEY { fmtid: PSGUID_DISPLACED, pid: PID_DISPLACED_FROM }; -const SCID_DATE_DELETED: PROPERTYKEY = - PROPERTYKEY { fmtid: PSGUID_DISPLACED, pid: PID_DISPLACED_DATE }; +const SCID_ORIGINAL_LOCATION: PROPERTYKEY = PROPERTYKEY { fmtid: PSGUID_DISPLACED, pid: PID_DISPLACED_FROM }; +const SCID_DATE_DELETED: PROPERTYKEY = PROPERTYKEY { fmtid: PSGUID_DISPLACED, pid: PID_DISPLACED_DATE }; const FOF_SILENT: u32 = 0x0004; const FOF_NOCONFIRMATION: u32 = 0x0010; @@ -31,7 +29,7 @@ const FOFX_EARLYFAILURE: u32 = 0x00100000; impl From for Error { fn from(err: windows::core::Error) -> Error { - Error::Unknown { description: format!("windows error: {}", err) } + Error::Unknown { description: format!("windows error: {err}") } } } @@ -47,8 +45,7 @@ impl TrashContext { pub(crate) fn delete_all_canonicalized(&self, full_paths: Vec) -> Result<(), Error> { ensure_com_initialized(); unsafe { - let pfo: IFileOperation = - CoCreateInstance(&FileOperation as *const _, None, CLSCTX_ALL).unwrap(); + let pfo: IFileOperation = CoCreateInstance(&FileOperation as *const _, None, CLSCTX_ALL).unwrap(); pfo.SetOperationFlags(FOF_NO_UI | FOF_ALLOWUNDO | FOF_WANTNUKEWARNING)?; @@ -62,8 +59,7 @@ impl TrashContext { &wide_path_container[0..] }; - let shi: IShellItem = - SHCreateItemFromParsingName(PCWSTR(wide_path_slice.as_ptr()), None)?; + let shi: IShellItem = SHCreateItemFromParsingName(PCWSTR(wide_path_slice.as_ptr()), None)?; pfo.DeleteItem(&shi, None)?; } @@ -104,9 +100,7 @@ pub fn list() -> Result, Error> { item_vec.push(TrashItem { id, - name: name - .into_string() - .map_err(|original| Error::ConvertOsString { original })?, + name: name.into_string().map_err(|original| Error::ConvertOsString { original })?, original_parent: PathBuf::from(original_location), time_deleted: date_deleted, }); @@ -173,12 +167,9 @@ where let trash_item: IShellItem = SHCreateItemFromParsingName(parsing_name, None)?; let parent_path_wide: Vec<_> = item.original_parent.as_os_str().encode_wide().chain(std::iter::once(0)).collect(); - let orig_folder_shi: IShellItem = - SHCreateItemFromParsingName(PCWSTR(parent_path_wide.as_ptr()), None)?; - let name_wstr: Vec<_> = AsRef::::as_ref(&item.name) - .encode_wide() - .chain(std::iter::once(0)) - .collect(); + let orig_folder_shi: IShellItem = SHCreateItemFromParsingName(PCWSTR(parent_path_wide.as_ptr()), None)?; + let name_wstr: Vec<_> = + AsRef::::as_ref(&item.name).encode_wide().chain(std::iter::once(0)).collect(); pfo.MoveItem(&trash_item, &orig_folder_shi, PCWSTR(name_wstr.as_ptr()), None)?; } @@ -222,10 +213,7 @@ struct CoInitializer {} impl CoInitializer { fn new() -> CoInitializer { //let first = INITIALIZER_THREAD_COUNT.fetch_add(1, Ordering::SeqCst) == 0; - #[cfg(all( - not(feature = "coinit_multithreaded"), - not(feature = "coinit_apartmentthreaded") - ))] + #[cfg(all(not(feature = "coinit_multithreaded"), not(feature = "coinit_apartmentthreaded")))] { 0 = "THIS IS AN ERROR ON PURPOSE. Either the `coinit_multithreaded` or the `coinit_apartmentthreaded` feature must be specified"; } diff --git a/tests/trash.rs b/tests/trash.rs index 0726e4f..c0d29f3 100644 --- a/tests/trash.rs +++ b/tests/trash.rs @@ -63,7 +63,7 @@ fn test_delete_all() { trace!("Started test_delete_all"); let count: usize = 3; - let paths: Vec<_> = (0..count).map(|i| format!("test_file_to_delete_{}", i)).collect(); + let paths: Vec<_> = (0..count).map(|i| format!("test_file_to_delete_{i}")).collect(); for path in paths.iter() { File::create(path).unwrap(); } @@ -148,6 +148,6 @@ fn recursive_file_deletion() { File::create(dir1.join("same-name")).unwrap(); File::create(dir2.join("same-name")).unwrap(); - trash::delete(&parent_dir).unwrap(); + trash::delete(parent_dir).unwrap(); assert!(!parent_dir.exists()); }