index : gitrs
A lightweight web interface for browsing Git repositories, implemented in Rust
about summary refs log tree commit diff
gitrs / src / git / commit.rs
-rw-r--r-- blob a6cd67e91eb77c2926ead8788616619e30b3c738 4943 bytes (plain)
1
use std::{borrow::Cow, collections::HashMap, str::FromStr};
2
3
use gix::{bstr::BStr, utils::AsBStr};
4
5
use crate::{prelude::*, time::Time};
6
7
pub struct Commit<'repo> {
8
    pub id: String,
9
    pub tree_id: String,
10
    pub parents: Vec<String>,
11
    pub author: GitSignature,
12
    pub committer: GitSignature,
13
    pub time: Time,
14
    pub gix: gix::Commit<'repo>,
15
}
16
17
impl<'repo> Commit<'repo> {
18
    pub fn from_gix(gix: gix::Commit<'_>) -> Result<Commit<'_>, Error> {
19
        Ok(Commit {
20
            id: gix.id().to_string(),
21
            tree_id: gix.tree_id()?.to_string(),
22
            parents: gix.parent_ids().map(|id| id.to_string()).collect(),
23
            author: GitSignature::from_gix(gix.author()?),
24
            committer: GitSignature::from_gix(gix.committer()?),
25
            time: Time::new(gix.time()?),
26
            gix,
27
        })
28
    }
29
30
    pub fn summary(&'repo self) -> Result<Cow<'repo, BStr>, Error> {
31
        Ok(self.gix.message()?.summary())
32
    }
33
34
    pub fn body(&'repo self) -> Result<&'repo BStr, Error> {
35
        Ok(self.gix.message()?.body.unwrap_or(BStr::new("")))
36
    }
37
38
    pub fn branch_name(&self, repo: &Repository) -> Result<Option<String>, Error> {
39
        Ok(self.branch_tips(repo)?.into_iter().next())
40
    }
41
42
    pub fn branch_tips(&self, repo: &Repository) -> Result<Vec<String>, Error> {
43
        let branch_tips = repo.branch_tips_by_commit()?;
44
        Ok(branch_tips.get(&self.id).cloned().unwrap_or_default())
45
    }
46
47
    pub fn is_head(&self, repo: &Repository) -> Result<bool, Error> {
48
        let head_id = repo.gix().head_id().ok().map(|id| id.to_string());
49
        Ok(head_id.as_deref() == Some(&self.id))
50
    }
51
}
52
53
impl Repository {
54
    pub fn find_commit<'repo>(
55
        &self,
56
        gix_repo: &'repo gix::Repository,
57
        id: &str,
58
    ) -> Result<Commit<'repo>, Error> {
59
        let oid = gix::ObjectId::from_str(id)?;
60
        Commit::from_gix(gix_repo.find_commit(oid)?)
61
    }
62
63
    pub fn resolve_commit<'repo>(
64
        &self,
65
        gix_repo: &'repo gix::Repository,
66
        id: Option<&str>,
67
        current_ref: &Ref,
68
    ) -> Result<Commit<'repo>, Error> {
69
        if let Some(id) = id {
70
            self.find_commit(gix_repo, id)
71
        } else {
72
            let mut reference = gix_repo.find_reference(&current_ref.name)?;
73
            Commit::from_gix(reference.peel_to_commit()?)
74
        }
75
    }
76
77
    pub fn last_commit<'repo>(
78
        &self,
79
        gix_repo: &'repo gix::Repository,
80
    ) -> Result<Option<Commit<'repo>>, Error> {
81
        if let Ok(commit) = gix_repo.head_commit() {
82
            return Ok(Some(Commit::from_gix(commit)?));
83
        }
84
        for reference in gix_repo.references()?.all()? {
85
            if let Ok(commit) = reference?.peel_to_commit() {
86
                return Ok(Some(Commit::from_gix(commit)?));
87
            }
88
        }
89
        Ok(None)
90
    }
91
92
    /// Returns the committer timestamp (in seconds) of the repository's latest commit,
93
    /// or `i64::MIN` if the repository has no commits yet.
94
    pub fn last_commit_timestamp(&self) -> i64 {
95
        let gix_repo = self.gix();
96
        self.last_commit(&gix_repo)
97
            .ok()
98
            .flatten()
99
            .map(|c| c.committer.time.seconds())
100
            .unwrap_or(i64::MIN)
101
    }
102
103
    pub fn branch_tips_by_commit(&self) -> Result<HashMap<String, Vec<String>>, Error> {
104
        let gix_repo = self.gix();
105
        let references = gix_repo.references()?;
106
        let mut map: HashMap<String, Vec<String>> = HashMap::new();
107
108
        for branch in references.local_branches()? {
109
            let mut branch = branch?;
110
            let commit_id = branch.peel_to_commit()?.id().to_string();
111
            map.entry(commit_id)
112
                .or_default()
113
                .push(branch.name().shorten().to_string());
114
        }
115
        Ok(map)
116
    }
117
118
    pub fn commits<'repo>(
119
        &self,
120
        gix_repo: &'repo gix::Repository,
121
        current_ref: &Ref,
122
        offset: usize,
123
        limit: usize,
124
        filter: Option<&dyn Fn(&Commit) -> bool>,
125
    ) -> Result<(Vec<Commit<'repo>>, bool), Error> {
126
        let start = gix_repo.rev_parse_single(current_ref.name.as_bstr())?;
127
        let revwalk = gix_repo
128
            .rev_walk([start])
129
            .sorting(gix::revision::walk::Sorting::ByCommitTime(
130
                Default::default(),
131
            ))
132
            .all()?;
133
134
        let mut commits = Vec::new();
135
        let mut has_next = false;
136
        let mut matched = 0usize;
137
138
        for rev in revwalk {
139
            let commit = Commit::from_gix(rev?.object()?)?;
140
            if let Some(f) = filter
141
                && !f(&commit)
142
            {
143
                continue;
144
            }
145
146
            if matched < offset {
147
                matched += 1;
148
                continue;
149
            }
150
151
            if commits.len() >= limit {
152
                has_next = true;
153
                break;
154
            }
155
156
            commits.push(commit);
157
        }
158
159
        Ok((commits, has_next))
160
    }
161
}