summaryrefslogtreecommitdiffstats
path: root/src/project/git.rs
blob: f1c4d5a215ec0868b46f9493c25c17f54317debc (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
80
81
82
83
84
85
86
87
88
89
90
use crate::{Error, Project};
use git2::{BranchType, Repository};
use ignore::DirEntry;
use std::{cmp::Ordering, path::PathBuf, time::Duration};

#[derive(Debug, Clone)]
pub struct GitProject {
    path_buf: PathBuf,
    latest_commit: Option<Duration>,
}

impl GitProject {
    fn new(path_buf: PathBuf) -> Result<Self, Error> {
        let repository = Repository::open(&path_buf)?;
        let latest_commit = Self::latest_commit(&repository);
        Ok(Self {
            path_buf,
            latest_commit,
        })
    }

    fn latest_commit(repository: &Repository) -> Option<Duration> {
        let mut branches = repository.branches(Some(BranchType::Local)).ok()?;
        branches
            .try_fold(0, |latest, branch| {
                let branch = branch?.0;

                let name = branch
                    .name()?
                    .ok_or_else(|| git2::Error::from_str("Failed to find branch"))?;

                repository
                    .revparse_single(name)?
                    .peel_to_commit()
                    .map(|c| (c.time().seconds() as u64).max(latest))
            })
            .map(Duration::from_secs)
            .ok()
    }
}

impl Project for GitProject {
    fn timestamp(&self) -> Option<Duration> {
        self.latest_commit
    }

    fn to_path_buf(&self) -> PathBuf {
        self.path_buf.to_owned()
    }
}

impl PartialEq for GitProject {
    fn eq(&self, other: &Self) -> bool {
        match (self.latest_commit, other.latest_commit) {
            (Some(time), Some(other_time)) => time.eq(&other_time),
            _ => false,
        }
    }
}

impl PartialOrd for GitProject {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match (self.latest_commit, other.latest_commit) {
            (Some(time), Some(other_time)) => time.partial_cmp(&other_time),
            _ => None,
        }
    }
}

impl TryFrom<PathBuf> for GitProject {
    type Error = Error;

    fn try_from(value: PathBuf) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

impl TryFrom<DirEntry> for GitProject {
    type Error = Error;

    fn try_from(value: DirEntry) -> Result<Self, Self::Error> {
        Self::new(value.into_path())
    }
}

impl From<GitProject> for PathBuf {
    fn from(value: GitProject) -> Self {
        value.path_buf
    }
}