Skip to main content

file_handle/
file_handle.rs

1#[cfg(feature = "show")]
2use std::path::Path;
3
4#[allow(unused_imports)]
5use crate::FileHandleError;
6
7#[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
8mod linux_unix;
9#[cfg(target_os = "macos")]
10mod macos;
11#[cfg(target_os = "windows")]
12mod windows;
13
14/// A humble helper for file-related UI operations.
15pub struct FileHandle;
16
17impl FileHandle {
18    // --- feature: show ---
19    /// Opens the file manager and selects the path (or opens the directory).
20    #[cfg(feature = "show")]
21    pub fn show<P: AsRef<Path>>(path: P) -> Result<(), FileHandleError> {
22        let path = path.as_ref();
23
24        let is_dir = path
25            .metadata()
26            .map_err(|_| FileHandleError::NotFound(path.to_owned()))?
27            .is_dir();
28
29        Self::dispatch_show(path, is_dir)
30    }
31
32    // --- feature: terminal ---
33    /// Opens a terminal emulator at the given path.
34    #[cfg(feature = "terminal")]
35    pub fn open_terminal<P: AsRef<Path>>(path: P) -> Result<(), FileHandleError> {
36        let path = path.as_ref();
37
38        let dir = if path.is_dir() {
39            path
40        } else {
41            path.parent()
42                .ok_or_else(|| FileHandleError::OpFailed("No parent".into()))?
43        };
44
45        Self::dispatch_terminal(dir)
46    }
47
48    // --- feature: trash ---
49    /// Moves the given path to the system trash.
50    #[cfg(feature = "trash")]
51    pub fn trash<P: AsRef<Path>>(path: P) -> Result<(), FileHandleError> {
52        trash_lib::delete(path).map_err(|e| FileHandleError::Trash(e.to_string()))
53    }
54}