aboutsummaryrefslogtreecommitdiff
path: root/src/file_system_utils.rs
blob: 32963248ac9adc3f430c37f542483b2b50b210ef (plain) (blame)
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
use std::io::Error;
use std::path::PathBuf;
use std::process::Command;

pub fn open_in_explorer(path: PathBuf) -> Result<(), Error> {
    let absolute_path = if path.is_relative() {
        std::env::current_dir()?.join(path)
    } else {
        path
    };

    let absolute_path = absolute_path.canonicalize().unwrap_or(absolute_path);

    if !absolute_path.exists() {
        return Err(Error::new(
            std::io::ErrorKind::NotFound,
            format!("Path does not exist: {}", absolute_path.display())
        ));
    }

    if cfg!(target_os = "windows") {
        if absolute_path.is_file() {
            absolute_path.parent()
                .ok_or_else(|| Error::new(
                    std::io::ErrorKind::InvalidInput,
                    "File has no parent directory"
                ))?;

            Command::new("explorer")
                .args(&["/select,", absolute_path.to_str().unwrap()])
                .spawn()?;
        } else {
            Command::new("explorer")
                .arg(absolute_path.to_str().unwrap())
                .spawn()?;
        }
    } else if cfg!(target_os = "macos") {
        if absolute_path.is_file() {
            Command::new("open")
                .args(&["-R", absolute_path.to_str().unwrap()])
                .spawn()?;
        } else {
            Command::new("open")
                .arg(absolute_path.to_str().unwrap())
                .spawn()?;
        }
    } else {
        Command::new("xdg-open")
            .arg(absolute_path.to_str().unwrap())
            .spawn()?;
    }

    Ok(())
}