aboutsummaryrefslogtreecommitdiffstats
path: root/src/project/path.rs
blob: 03bcac61dadc754a48b28ee54e947582c224ac48 (plain)
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
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
use tracing::debug;

use super::{ProjectItem, ProjectParser};

#[derive(Debug, Clone)]
pub struct PathMatcher(pub String);

impl ProjectParser for PathMatcher {
    #[tracing::instrument]
    fn parse_project(&self, path_buf: PathBuf) -> Option<ProjectItem> {
        if path_buf.join(&self.0).exists() {
            Some(Box::new(PathProject::new(path_buf)))
        } else {
            debug!("Failed to match pattern in directory");
            None
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub struct PathProject(PathBuf, Duration);

impl PathProject {
    pub fn new(path_buf: PathBuf) -> Self {
        let modified = Self::get_modified(&path_buf).unwrap_or_default();
        Self(path_buf, modified)
    }

    fn get_modified(path_buf: &Path) -> Result<Duration, std::io::Error> {
        path_buf
            .metadata()?
            .modified()?
            .duration_since(SystemTime::UNIX_EPOCH)
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err.to_string()))
    }
}

impl AsRef<PathBuf> for PathProject {
    fn as_ref(&self) -> &PathBuf {
        &self.0
    }
}

impl AsRef<Duration> for PathProject {
    fn as_ref(&self) -> &Duration {
        &self.1
    }
}

#[cfg(feature = "preview")]
impl super::Preview for PathProject {
    type Error = std::io::Error;

    fn preview(&self) -> Result<(), Self::Error> {
        use std::io::Write;
        use std::process::{Command, Stdio};

        let output = Command::new("ls")
            .arg("-l")
            .arg("-a")
            .arg(&self.0)
            .stdout(Stdio::piped())
            .output()?;

        std::io::stdout().write_all(&output.stdout)
    }
}