summaryrefslogtreecommitdiffstats
path: root/src/project/git.rs
blob: 6c8f329a3f7dfc7774fdbaa2d2887aee98363945 (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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
use git2::{BranchType, Repository};
use ignore::DirEntry;
use onefetch::ui::printer::Printer;
use std::io;
use std::{path::PathBuf, time::Duration};
use tracing::{debug, warn};

use crate::{Error, Result};

use super::{Preview, ProjectParser, Timestamp};

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

impl ProjectParser for GitMatcher {
    #[tracing::instrument]
    fn parse(&self, path_buf: PathBuf) -> Option<super::ProjectItem> {
        match GitProject::new(path_buf) {
            Ok(g) => Some(Box::new(g)),
            Err(err) => {
                debug!(%err, "Failed to create git project");
                None
            }
        }
    }
}

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

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

    fn get_timestamp(repo: &Repository) -> Duration {
        match Self::latest_commit(repo) {
            Ok(s) => Duration::from_secs(s),
            Err(err) => {
                warn!(%err, "Failed to get latest commit from repository");
                Duration::default()
            }
        }
    }

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

            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_err(Into::into)
        })
    }
}

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

#[cfg(feature = "preview")]
impl Preview for GitProject {
    type Error = Error;

    fn preview(&self) -> Result<()> {
        let config = onefetch::cli::Config {
            input: self.path_buf.to_owned(),
            include_hidden: true,
            ..Default::default()
        };

        let info = onefetch::info::Info::new(&config)?;
        let mut printer = Printer::new(io::BufWriter::new(io::stdout()), info, config)?;

        printer.print().map_err(Into::into)
    }
}

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

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

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

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

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

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