Skip to content

Commit

Permalink
Run rust fmt. Implement list for Windows.
Browse files Browse the repository at this point in the history
  • Loading branch information
ArturKovacs committed Oct 31, 2019
1 parent 79ee69e commit 3f29636
Show file tree
Hide file tree
Showing 6 changed files with 424 additions and 24 deletions.
17 changes: 16 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,22 @@ keywords = ["remove", "trash", "rubbish", "recycle", "bin"]
repository = "https://github.com/ArturKovacs/trash"
edition = "2018"

[features]
default = ["coinit_apartmentthreaded"]
coinit_apartmentthreaded = []
coinit_multithreaded = []
coinit_disable_ole1dde = []
coinit_speed_over_memory = []

[dependencies]

[target.'cfg(windows)'.dependencies]
winapi = { version = "^0.3.0", features = ["shellapi", "winerror"] }
scopeguard = "1.0.0"

[target.'cfg(windows)'.dependencies.winapi]
git = "https://github.com/ArturKovacs/winapi-rs.git"
branch = "add-ishellfolder"
features = [
"combaseapi", "objbase", "shlobj", "shellapi", "winerror", "shlobj", "shlwapi", "shobjidl_core",
"shobjidl", "oleauto", "oaidl", "wtypes", "errhandlingapi", "timezoneapi"
]
13 changes: 13 additions & 0 deletions examples/list.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use trash;
use trash::TrashItem;

fn main() {
let list = trash::list().unwrap();

for item in list.iter() {
println!("------------------------------------------------");
println!("{}", item.name);
println!("{}", item.original_path().to_str().unwrap());
println!("{}", item.time_deleted);
}
}
108 changes: 102 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::path::Path;
use std::ffi::OsString;
use std::path::{Path, PathBuf};

#[cfg(test)]
mod tests;
Expand All @@ -15,11 +16,23 @@ mod platform;
#[path = "macos.rs"]
mod platform;

/// Error that might happen during a remove operation.
/// Error that might happen during a trash operation.
#[derive(Debug)]
pub enum Error {
Unknown,

/// Any error that might happen during a direct call to a platform specific API.
///
/// `function_name`: the name of the function during which the error occured.
/// `code`: An error code that the function provided or was obtained otherwise.
///
/// On Windows the `code` will contain the HRESULT that the function returned or that was
/// obtained with `HRESULT_FROM_WIN32(GetLastError())`
PlatformApi {
function_name: String,
code: Option<i32>,
},

/// Error while canonicalizing path.
/// `code` contains a raw os error code if accessible.
CanonicalizePath {
Expand All @@ -31,12 +44,95 @@ pub enum Error {
Remove {
code: Option<i32>,
},

/// Error while converting an OsString to a String.
/// `original` is the string that was attempted to be converted.
ConvertOsString {
original: OsString,
},
}

/// This struct holds information about a single item within the trash.
///
/// Some functions associated with this struct are defined in the `TrahsItemPlatformDep` trait.
/// That trait is implemented for `TrashItem` by each platform specific source file individually.
///
/// A trahs item can be a file or folder or any other object that the target operating system
/// allows to put into the trash.
#[derive(Debug)]
pub struct TrashItem {
/// A system specific identifier of the item in the trash.
///
/// On Windows it is the string returned by `IShellFolder::GetDisplayNameOf` with the
/// `SHGDN_FORPARSING` flag.
///
/// On Linux ...
///
/// On MacOS ...
pub id: OsString,

/// The name of the item. For example if the folder '/home/user/New Folder' was deleted,
/// its `name` is 'New Folder'
pub name: String,

/// The path to the parent folder of this item before it was put inside the trash.
/// For example if the folder '/home/user/New Folder' was deleted, its `original_parent`
/// is '/home/user'
pub original_parent: PathBuf,

/// The date and time in UNIX Epoch time when the item was put into the trash.
pub time_deleted: i64,
}

/// Platform independent functions of `TrashItem`.
///
/// See `TrahsItemPlatformDep` for platform dependent functions.
impl TrashItem {
/// Joins the `original_parent` and `name` fields to obtain the full path to the original file.
pub fn original_path(&self) -> PathBuf {
self.original_parent.join(&self.name)
}
}

/// Returns all `TrashItem`s that are currently in the trash.
pub fn list() -> Result<Vec<TrashItem>, Error> {
platform::list()
}

/// Deletes all the provided items permanently.
///
/// This function consumes the provided `TrashItem`s.
pub fn purge_all<I>(items: I) -> Result<(), Error>
where
I: IntoIterator<Item = TrashItem>,
{
platform::purge_all(items)
}

/// Restores all the provided items to their original location.
///
/// This function consumes the provided `TrashItem`s.
pub fn restore_all<I>(items: I) -> Result<(), Error>
where
I: IntoIterator<Item = TrashItem>,
{
platform::restore_all(items)
}

/// This trait lists all the `TrashItem` related functions that have a platform dependent
/// implementation
trait TrahsItemPlatformDep {
/// Permanently delete the item.
fn purge(self) -> Result<(), ()>;

/// Restore the item from the trash to its original location.
fn restore(self) -> Result<(), ()>;
}

/// Removes a single file or directory.
///
///
/// # Example
///
///
/// ```
/// extern crate trash;
/// use std::fs::File;
Expand All @@ -50,9 +146,9 @@ pub fn remove<T: AsRef<Path>>(path: T) -> Result<(), Error> {
}

/// Removes all files/directories specified by the collection of paths provided as an argument.
///
///
/// # Example
///
///
/// ```
/// extern crate trash;
/// use std::fs::File;
Expand Down
20 changes: 11 additions & 9 deletions src/linux.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@

use std::path::Path;
use std::ffi::OsString;
use std::env;
use std::ffi::OsString;
use std::path::Path;
use std::process::Command;

use crate::Error;
Expand Down Expand Up @@ -30,8 +29,7 @@ where
let trash = {
// Determine desktop environment and set accordingly.
let desktop_env = get_desktop_environment();
if desktop_env == DesktopEnvironment::Kde4 ||
desktop_env == DesktopEnvironment::Kde5 {
if desktop_env == DesktopEnvironment::Kde4 || desktop_env == DesktopEnvironment::Kde5 {
"kioclient5"
} else if desktop_env == DesktopEnvironment::Kde3 {
"kioclient"
Expand Down Expand Up @@ -60,11 +58,13 @@ where
// Execute command
let mut command = Command::new(trash);
command.args(argv);
let result = command.output().map_err(|e| Error::Remove { code: e.raw_os_error() })?;

let result = command.output().map_err(|e| Error::Remove {
code: e.raw_os_error(),
})?;

if !result.status.success() {
return Err(Error::Remove {
code: result.status.code()
code: result.status.code(),
});
}

Expand Down Expand Up @@ -102,7 +102,9 @@ fn get_desktop_environment() -> DesktopEnvironment {
// It could have multiple values separated by colon in priority order.
for value in xdg_current_desktop.split(":") {
let value = value.trim();
if value.len() == 0 { continue; }
if value.len() == 0 {
continue;
}
if value == "Unity" {
// gnome-fallback sessions set XDG_CURRENT_DESKTOP to Unity
// DESKTOP_SESSION can be gnome-fallback or gnome-fallback-compiz
Expand Down
6 changes: 4 additions & 2 deletions src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{remove, remove_all};
use std::fs::{File, create_dir};
use std::fs::{create_dir, File};
use std::path::PathBuf;

#[test]
Expand All @@ -26,7 +26,9 @@ fn create_remove_folder() {
fn create_multiple_remove_all() {
let count: usize = 3;

let paths: Vec<_> = (0..count).map(|i| format!("test_file_to_remove_{}", i)).collect();
let paths: Vec<_> = (0..count)
.map(|i| format!("test_file_to_remove_{}", i))
.collect();
for path in paths.iter() {
File::create(path).unwrap();
}
Expand Down

0 comments on commit 3f29636

Please sign in to comment.