summaryrefslogtreecommitdiffstats
path: root/src/project.rs
blob: 2b3e028a0ca39fa5408e1424bd4c6fa6b13fb54f (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
70
71
72
73
74
75
76
77
78
79
use std::{
    ops::{Deref, DerefMut},
    path::PathBuf,
    time::{Duration, SystemTime},
};

use tracing::warn;

pub mod path;

#[cfg(feature = "git")]
pub mod git;

pub trait ProjectParser {
    fn parse(&self, path_buf: PathBuf) -> Result<Project, Box<dyn std::error::Error>>;
}

#[derive(Default)]
pub struct ProjectParserGroup {
    pub parsers: Vec<Box<dyn ProjectParser>>,
}

impl ProjectParserGroup {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn parse(&self, path_buf: std::path::PathBuf) -> Option<Project> {
        if self.parsers.is_empty() {
            return path_buf.try_into().ok();
        }

        self.iter()
            .map(|p| p.parse(path_buf.to_owned()))
            .inspect(|res| {
                if let Err(err) = res {
                    warn!(%err, "Parser failed to match");
                }
            })
            .flatten()
            .reduce(|max, p| p.max(max))
    }
}

impl Deref for ProjectParserGroup {
    type Target = Vec<Box<dyn ProjectParser>>;

    fn deref(&self) -> &Self::Target {
        &self.parsers
    }
}

impl DerefMut for ProjectParserGroup {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.parsers
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Project {
    pub timestamp: Duration,
    pub worktree: PathBuf,
}

impl TryFrom<PathBuf> for Project {
    type Error = std::io::Error;

    fn try_from(value: PathBuf) -> Result<Self, Self::Error> {
        let timestamp = value
            .metadata()?
            .modified()?
            .duration_since(SystemTime::UNIX_EPOCH)
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err.to_string()))?;
        Ok(Self {
            worktree: value,
            timestamp,
        })
    }
}