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 dfda921aa323cfa07d31dc09b27df8fbdf19e41c 6877 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 is_head: bool,
15
    pub branch_tips: Vec<String>,
16
    pub gix: gix::Commit<'repo>,
17
}
18
19
impl<'repo> Commit<'repo> {
20
    pub fn from_gix(gix: gix::Commit<'_>) -> Result<Commit<'_>, Error> {
21
        // Decode the raw commit object once instead of re-parsing it 5 times via
22
        // `.tree_id()`, `.parent_ids()`, `.author()`, `.committer()`, and `.time()`.
23
        let (tree_id, parents, author, committer) = {
24
            let decoded = gix.decode()?;
25
            (
26
                decoded.tree().to_string(),
27
                decoded.parents().map(|id| id.to_string()).collect(),
28
                GitSignature::from_gix(decoded.author()?),
29
                GitSignature::from_gix(decoded.committer()?),
30
            )
31
        };
32
        let time = committer.time.clone();
33
34
        Ok(Commit {
35
            id: gix.id().to_string(),
36
            tree_id,
37
            parents,
38
            author,
39
            committer,
40
            time,
41
            is_head: false,
42
            branch_tips: Vec::new(),
43
            gix,
44
        })
45
    }
46
47
    pub fn summary(&'repo self) -> Result<Cow<'repo, BStr>, Error> {
48
        Ok(self.gix.message()?.summary())
49
    }
50
51
    pub fn body(&'repo self) -> Result<&'repo BStr, Error> {
52
        Ok(self.gix.message()?.body.unwrap_or(BStr::new("")))
53
    }
54
55
    pub fn branch_name(&self, _repo: &Repository) -> Result<Option<&str>, Error> {
56
        Ok(self.branch_tips.first().map(String::as_str))
57
    }
58
59
    pub fn branch_tips(&self, _repo: &Repository) -> Result<&[String], Error> {
60
        Ok(&self.branch_tips)
61
    }
62
63
    pub fn is_head(&self, _repo: &Repository) -> Result<bool, Error> {
64
        Ok(self.is_head)
65
    }
66
}
67
68
impl Repository {
69
    pub fn find_commit<'repo>(
70
        &self,
71
        gix_repo: &'repo gix::Repository,
72
        id: &str,
73
    ) -> Result<Commit<'repo>, Error> {
74
        let oid = gix::ObjectId::from_str(id)?;
75
        Commit::from_gix(gix_repo.find_commit(oid)?)
76
    }
77
78
    pub fn resolve_commit<'repo>(
79
        &self,
80
        gix_repo: &'repo gix::Repository,
81
        id: Option<&str>,
82
        current_ref: &Ref,
83
    ) -> Result<Commit<'repo>, Error> {
84
        let mut commit = if let Some(id) = id {
85
            self.find_commit(gix_repo, id)?
86
        } else {
87
            let mut reference = gix_repo.find_reference(&current_ref.name)?;
88
            Commit::from_gix(reference.peel_to_commit()?)?
89
        };
90
        let head_id = gix_repo.head_id().ok().map(|id| id.to_string());
91
        let mut branch_tips = Self::branch_tips_from_repo(gix_repo)?;
92
        commit.is_head = head_id.as_deref() == Some(&commit.id);
93
        commit.branch_tips = branch_tips.remove(&commit.id).unwrap_or_default();
94
        Ok(commit)
95
    }
96
97
    pub fn last_commit<'repo>(
98
        &self,
99
        gix_repo: &'repo gix::Repository,
100
    ) -> Result<Option<Commit<'repo>>, Error> {
101
        if let Ok(commit) = gix_repo.head_commit() {
102
            return Ok(Some(Commit::from_gix(commit)?));
103
        }
104
        for reference in gix_repo.references()?.all()? {
105
            if let Ok(commit) = reference?.peel_to_commit() {
106
                return Ok(Some(Commit::from_gix(commit)?));
107
            }
108
        }
109
        Ok(None)
110
    }
111
112
    /// Returns the committer `Time` of the repository's latest commit without allocating
113
    /// a full `Commit` struct.
114
    pub fn last_commit_time(&self) -> Option<Time> {
115
        let gix_repo = self.gix();
116
        if let Ok(commit) = gix_repo.head_commit()
117
            && let Ok(sig) = commit.committer()
118
            && let Ok(t) = sig.time()
119
        {
120
            return Some(Time::new(t));
121
        }
122
        for reference in gix_repo.references().ok()?.all().ok()? {
123
            if let Ok(commit) = reference.ok()?.peel_to_commit()
124
                && let Ok(sig) = commit.committer()
125
                && let Ok(t) = sig.time()
126
            {
127
                return Some(Time::new(t));
128
            }
129
        }
130
        None
131
    }
132
133
    /// Returns the committer timestamp (in seconds) of the repository's latest commit,
134
    /// or `i64::MIN` if the repository has no commits yet.
135
    pub fn last_commit_timestamp(&self) -> i64 {
136
        self.last_commit_time()
137
            .map(|t| t.seconds())
138
            .unwrap_or(i64::MIN)
139
    }
140
141
    pub fn branch_tips_by_commit(&self) -> Result<HashMap<String, Vec<String>>, Error> {
142
        let gix_repo = self.gix();
143
        Self::branch_tips_from_repo(&gix_repo)
144
    }
145
146
    fn branch_tips_from_repo(
147
        gix_repo: &gix::Repository,
148
    ) -> Result<HashMap<String, Vec<String>>, Error> {
149
        let references = gix_repo.references()?;
150
        let mut map: HashMap<String, Vec<String>> = HashMap::new();
151
152
        for branch in references.local_branches()? {
153
            let mut branch = branch?;
154
            let commit_id = branch.peel_to_commit()?.id().to_string();
155
            map.entry(commit_id)
156
                .or_default()
157
                .push(branch.name().shorten().to_string());
158
        }
159
        Ok(map)
160
    }
161
162
    pub fn commits<'repo>(
163
        &self,
164
        gix_repo: &'repo gix::Repository,
165
        current_ref: &Ref,
166
        offset: usize,
167
        limit: usize,
168
        filter: Option<&dyn Fn(&Commit) -> bool>,
169
    ) -> Result<(Vec<Commit<'repo>>, bool), Error> {
170
        let start = gix_repo.rev_parse_single(current_ref.name.as_bstr())?;
171
        let revwalk = gix_repo
172
            .rev_walk([start])
173
            .sorting(gix::revision::walk::Sorting::ByCommitTime(
174
                Default::default(),
175
            ))
176
            .all()?;
177
178
        let head_id = gix_repo.head_id().ok().map(|id| id.to_string());
179
        let mut branch_tips = Self::branch_tips_from_repo(gix_repo)?;
180
181
        let mut commits = Vec::with_capacity(limit);
182
        let mut has_next = false;
183
        let mut matched = 0usize;
184
185
        for rev in revwalk {
186
            let rev = rev?;
187
            if filter.is_none() && matched < offset {
188
                matched += 1;
189
                continue;
190
            }
191
192
            let mut commit = Commit::from_gix(rev.object()?)?;
193
            if let Some(f) = filter
194
                && !f(&commit)
195
            {
196
                continue;
197
            }
198
199
            if matched < offset {
200
                matched += 1;
201
                continue;
202
            }
203
204
            if commits.len() >= limit {
205
                has_next = true;
206
                break;
207
            }
208
209
            commit.is_head = head_id.as_deref() == Some(&commit.id);
210
            commit.branch_tips = branch_tips.remove(&commit.id).unwrap_or_default();
211
            commits.push(commit);
212
        }
213
214
        Ok((commits, has_next))
215
    }
216
}