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 52e6602793b03ca0ca4799965e5276858cad3d1b 5577 bytes (plain)
1
use std::str::FromStr;
2
use std::{borrow::Cow, collections::HashMap};
3
4
use gix::{bstr::BStr, utils::AsBStr};
5
6
use crate::{prelude::*, time::Time};
7
8
pub struct Commit<'repo> {
9
    pub id: String,
10
    pub tree_id: String,
11
    pub parents: Vec<String>,
12
    pub author: GitSignature,
13
    pub committer: GitSignature,
14
    pub time: Time,
15
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
        let commit_id = gix.id().to_string();
22
23
        let tree_id = gix.tree_id()?.to_string();
24
        let parents = gix.parent_ids().map(|id| id.to_string()).collect();
25
        Ok(Commit {
26
            id: commit_id,
27
            tree_id,
28
            parents,
29
            author: GitSignature::from_gix(gix.author()?),
30
            committer: GitSignature::from_gix(gix.committer()?),
31
            time: Time::new(gix.time()?),
32
33
            gix,
34
        })
35
    }
36
37
    pub fn summary(&'repo self) -> Result<Cow<'repo, BStr>, Error> {
38
        Ok(self.gix.message()?.summary())
39
    }
40
41
    pub fn body(&'repo self) -> Result<&'repo BStr, Error> {
42
        Ok(self.gix.message()?.body.unwrap_or(BStr::new("")))
43
    }
44
45
    pub fn branch_name(&self, repo: &Repository) -> Result<Option<String>, Error> {
46
        Ok(self.branch_tips(repo)?.into_iter().next())
47
    }
48
49
    pub fn branch_tips(&self, repo: &Repository) -> Result<Vec<String>, Error> {
50
        let branch_tips = repo.branch_tips_by_commit()?;
51
        Ok(branch_tips.get(&self.id).cloned().unwrap_or_default())
52
    }
53
54
    pub fn is_head(&self, repo: &Repository) -> Result<bool, Error> {
55
        let head_commit_id: Option<String> =
56
            repo.gix().head_commit().ok().map(|c| c.id().to_string());
57
        Ok(head_commit_id.as_deref() == Some(&self.id))
58
    }
59
}
60
61
impl Repository {
62
    /// Looks up a Commit by its 40-character hex SHA-1 hash.
63
    pub fn find_commit<'repo>(
64
        &self,
65
        gix_repo: &'repo gix::Repository,
66
        id: &str,
67
    ) -> Result<Commit<'repo>, Error> {
68
        let oid = gix::ObjectId::from_str(id)?;
69
        Commit::from_gix(gix_repo.find_commit(oid)?)
70
    }
71
72
    /// Resolves a Commit either from an explicit `?id=<sha>` query parameter,
73
    /// or by peeling the active branch/tag reference (`current_ref`) to its latest commit.
74
    pub fn resolve_commit<'repo>(
75
        &self,
76
        gix_repo: &'repo gix::Repository,
77
        id: Option<&str>,
78
        current_ref: &Ref,
79
    ) -> Result<Commit<'repo>, Error> {
80
        if let Some(id) = id {
81
            self.find_commit(gix_repo, id)
82
        } else {
83
            let mut reference = gix_repo.find_reference(&current_ref.name)?;
84
            Commit::from_gix(reference.peel_to_commit()?)
85
        }
86
    }
87
88
    /// Returns the latest commit on `HEAD` (or falls back to the first valid reference in the repo).
89
    pub fn last_commit<'repo>(
90
        &self,
91
        gix_repo: &'repo gix::Repository,
92
    ) -> Result<Option<Commit<'repo>>, Error> {
93
        if let Ok(commit) = gix_repo.head_commit() {
94
            return Ok(Some(Commit::from_gix(commit)?));
95
        }
96
        for reference in gix_repo.references()?.all()? {
97
            if let Ok(commit) = reference?.peel_to_commit() {
98
                return Ok(Some(Commit::from_gix(commit)?));
99
            }
100
        }
101
        Ok(None)
102
    }
103
104
    /// Builds a map of `commit_sha -> [branch_names]` for every local branch (`refs/heads/*`).
105
    pub fn branch_tips_by_commit(&self) -> Result<HashMap<String, Vec<String>>, Error> {
106
        let gix_repo = self.gix();
107
        let references = gix_repo.references()?;
108
        let local_branches = references.local_branches()?;
109
110
        let mut map: HashMap<String, Vec<String>> = HashMap::new();
111
        for branch in local_branches {
112
            let mut branch = branch?;
113
            let commit_id = branch.peel_to_commit()?.id().to_string();
114
            map.entry(commit_id)
115
                .or_default()
116
                .push(branch.name().shorten().to_string());
117
        }
118
        Ok(map)
119
    }
120
121
    /// Walks the commit graph backwards starting from `current_ref` (like `git log`),
122
    /// sorted newest-first by commit timestamp, with optional filtering and pagination.
123
    pub fn commits<'repo>(
124
        &self,
125
        gix_repo: &'repo gix::Repository,
126
        current_ref: &Ref,
127
        offset: usize,
128
        limit: usize,
129
        filter: Option<&dyn Fn(&Commit) -> bool>,
130
    ) -> Result<(Vec<Commit<'repo>>, bool), Error> {
131
        // 1. Parse the branch/tag name (e.g. "main") into its starting commit ObjectId
132
        let start = gix_repo.rev_parse_single(current_ref.name.as_bstr())?;
133
        // 2. Walk parent links backwards from `start`, ordered by commit time
134
        let revwalk = gix_repo
135
            .rev_walk([start])
136
            .sorting(gix::revision::walk::Sorting::ByCommitTime(
137
                Default::default(),
138
            ))
139
            .all()?;
140
141
        let mut commits: Vec<Commit> = Vec::new();
142
        let mut has_next = false;
143
        let mut matched = 0usize;
144
145
        for rev in revwalk {
146
            let rev = rev?;
147
            let object = rev.object()?;
148
            let commit = Commit::from_gix(object)?;
149
            if let Some(f) = filter
150
                && !f(&commit)
151
            {
152
                continue;
153
            }
154
155
            if matched < offset {
156
                matched += 1;
157
                continue;
158
            }
159
160
            if commits.len() >= limit {
161
                has_next = true;
162
                break;
163
            }
164
165
            commits.push(commit);
166
        }
167
168
        Ok((commits, has_next))
169
    }
170
}