Skip to main content

stratum/domain/
commit.rs

1use regex::Regex;
2use std::sync::LazyLock;
3use std::{cell::OnceCell, str::FromStr};
4
5use crate::{Actor, Error, ModifiedFile, Repository};
6
7/// Iterate all co-author matches in the haystack string formatting the return
8/// string to be formatted as "Name <Email>"
9fn iter_co_authors(haystack: &str) -> impl Iterator<Item = &str> {
10    const CO_AUTHOR_REGEX: &str = r"(?m)^Co-authored-by: (.*) <(.*?)>$";
11    // Regex should always compile hence bare unwrap.
12    static RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(CO_AUTHOR_REGEX).unwrap());
13
14    let prefix = "Co-authored-by:";
15    RE.find_iter(haystack).map(move |re_match| {
16        re_match
17            .as_str()
18            .strip_prefix(prefix)
19            .unwrap_or_default()
20            .trim()
21    })
22}
23
24/// A singular git commit for the repository being inspected
25pub struct Commit<'repo> {
26    inner: git2::Commit<'repo>,
27    ctx: &'repo Repository,
28    cache: OnceCell<git2::Diff<'repo>>,
29}
30
31impl<'repo> Commit<'repo> {
32    /// Instantiate a new Commit object from a git2 commit
33    pub fn new(commit: git2::Commit<'repo>, repository: &'repo Repository) -> Self {
34        Self {
35            inner: commit.to_owned(),
36            ctx: repository,
37            cache: OnceCell::new(),
38        }
39    }
40
41    /// Return the commit hash
42    pub fn hash(&self) -> String {
43        self.inner.id().to_string()
44    }
45
46    /// Return the commit message if it exists
47    pub fn msg(&self) -> Option<&str> {
48        self.inner.message()
49    }
50
51    /// Return the commit author
52    pub fn author(&self) -> Actor {
53        Actor::new(self.inner.author())
54    }
55
56    /// Return the co-authors as listed in the commit message
57    ///
58    /// Lazilly returning as an iterator means the co-authors, if entered more
59    /// than once, will **not** be de-duplicated.
60    pub fn co_authors(&self) -> impl Iterator<Item = Result<Actor, Error>> {
61        let commit_msg = self.msg().unwrap_or_default();
62        iter_co_authors(commit_msg).map(Actor::from_str)
63    }
64
65    /// Return the commit committer
66    pub fn committer(&self) -> Actor {
67        Actor::new(self.inner.committer())
68    }
69
70    /// Iterate all utf-8 branch names that the current commit is contained in
71    ///
72    /// ## Note
73    ///
74    /// Potentially expensive method. Take caution when using within a loop.
75    pub fn branches(&self) -> Result<impl Iterator<Item = Result<String, Error>>, Error> {
76        self.branch_iterator(None)
77    }
78
79    /// Iterate all **local** utf-8 branch names that the current commit is contained in
80    ///
81    /// ## Note
82    ///
83    /// Potentially expensive method. Take caution when using within a loop.
84    pub fn local_branches(&self) -> Result<impl Iterator<Item = Result<String, Error>>, Error> {
85        let flag = Some(git2::BranchType::Local);
86        self.branch_iterator(flag)
87    }
88
89    /// Iterate all **remote** utf-8 branch names that the current commit is contained in
90    ///
91    /// ## Note
92    ///
93    /// Potentially expensive method. Take caution when using within a loop.
94    pub fn remote_branches(&self) -> Result<impl Iterator<Item = Result<String, Error>>, Error> {
95        let flag = Some(git2::BranchType::Remote);
96        self.branch_iterator(flag)
97    }
98
99    /// Retrun the hashes of all commit parents
100    pub fn parents(&self) -> impl Iterator<Item = String> {
101        self.inner.parent_ids().map(|id| id.to_string())
102    }
103
104    /// Return whether the commit is a merge commit
105    pub fn is_merge(&self) -> bool {
106        self.inner.parent_count() > 1
107    }
108
109    /// Return an iterator over the modified files that belong to a commit
110    pub fn mod_files(&self) -> Result<impl Iterator<Item = ModifiedFile<'_>>, Error> {
111        let diff = self.diff()?;
112
113        Ok((0..diff.deltas().len()).map(move |n| ModifiedFile::new(diff, n)))
114    }
115
116    /// The number of insertions in the commit
117    pub fn insertions(&self) -> Result<usize, Error> {
118        Ok(self.stats()?.insertions())
119    }
120
121    /// The number of deletions in the commit
122    pub fn deletions(&self) -> Result<usize, Error> {
123        Ok(self.stats()?.deletions())
124    }
125
126    /// The total number of lines modified in the commit
127    pub fn lines(&self) -> Result<usize, Error> {
128        Ok(self.insertions()? + self.deletions()?)
129    }
130
131    /// The number of files modified in the commit
132    pub fn files(&self) -> Result<usize, Error> {
133        Ok(self.stats()?.files_changed())
134    }
135
136    //TODO: Should stats also be cached?
137    /// Return the git2 Stats from the commits diff
138    fn stats(&self) -> Result<git2::DiffStats, Error> {
139        let diff = self.diff()?;
140        diff.stats().map_err(Error::Git)
141    }
142
143    /// Return the git diff for the current commit within the context of a
144    /// repository.
145    //TODO: https://github.com/segfault-merchant/git-stratum/issues/32
146    fn diff(&self) -> Result<&git2::Diff<'repo>, Error> {
147        let diff = self.calculate_diff()?;
148        Ok(self.cache.get_or_init(|| diff))
149    }
150
151    /// Diff the current commit to it's parent(s) adjusting strategy based on the
152    /// number of parents
153    fn calculate_diff(&self) -> Result<git2::Diff<'repo>, Error> {
154        let this_tree = self.inner.tree().ok();
155        let parent_tree = self.resolve_parent_tree()?;
156
157        self.ctx
158            .raw()
159            //TODO: Expose opts?
160            .diff_tree_to_tree(parent_tree.as_ref(), this_tree.as_ref(), None)
161            .map_err(Error::Git)
162    }
163
164    /// Resolve to the correct parent tree changing strategies based on number
165    /// of parents.
166    fn resolve_parent_tree(&self) -> Result<Option<git2::Tree<'_>>, Error> {
167        Ok(match self.inner.parent_count() {
168            0 => None,
169            1 => self.inner.parent(0).map_err(Error::Git)?.tree().ok(),
170            //TODO: Resolve merge commit process
171            _ => return Err(Error::PathError("Placeholder error".to_string())),
172        })
173    }
174
175    /// Check if a commit contains a branch
176    ///
177    /// If an error occurs returns false, this is done so any erroring branches
178    /// are filtered out of any dependant processes
179    fn commit_contains_branch(&self, branch: git2::Oid, commit: git2::Oid) -> bool {
180        self.ctx.raw().graph_descendant_of(branch, commit).is_ok()
181    }
182
183    /// Iterate over the specified branch types, None will return all branches
184    fn branch_iterator(
185        &self,
186        bt: Option<git2::BranchType>,
187    ) -> Result<impl Iterator<Item = Result<String, Error>>, Error> {
188        let commit_id = self.inner.id();
189        let branches = self.ctx.raw().branches(bt).map_err(Error::Git)?;
190
191        Ok(branches.filter_map(move |res| {
192            let branch = match res {
193                Ok(v) => v.0,
194                Err(e) => return Some(Err(Error::Git(e))),
195            };
196
197            // If a branch does not have a valid target then filter that
198            // branch out
199            // TODO: Is this excluding a subset of symbolic references
200            let oid = match branch.get().target() {
201                Some(v) => v,
202                None => return None,
203            };
204
205            // Filter out a branch if the commit does NOT contain it
206            if !self.commit_contains_branch(oid, commit_id) {
207                return None;
208            }
209
210            match branch.name() {
211                Ok(Some(name)) => Some(Ok(name.to_string())),
212                Ok(None) => None, // drop non-utf8 branches
213                Err(e) => Some(Err(Error::Git(e))),
214            }
215        }))
216    }
217}
218
219#[cfg(test)]
220mod test {
221    use super::*;
222    use crate::{
223        Local, Repository,
224        common::{EXPECTED_ACTOR_EMAIL, EXPECTED_ACTOR_NAME, EXPECTED_MSG, init_repo},
225    };
226
227    fn commit_fixture<F, R>(f: F) -> R
228    where
229        F: FnOnce(&Repository<Local>, &Commit) -> R,
230    {
231        let repo = init_repo();
232
233        let repo = Repository::<Local>::from_repository(repo);
234        let commit = repo.head().expect("Failed to get HEAD");
235
236        f(&repo, &commit)
237    }
238
239    #[test]
240    fn test_msg() {
241        commit_fixture(|_, commit| {
242            // use mfile here
243            assert_eq!(commit.msg(), Some(EXPECTED_MSG));
244        });
245    }
246
247    #[test]
248    fn test_author() {
249        commit_fixture(|_, commit| {
250            assert_eq!(
251                commit.author().name().unwrap(),
252                EXPECTED_ACTOR_NAME.to_string()
253            );
254            assert_eq!(
255                commit.author().email().unwrap(),
256                EXPECTED_ACTOR_EMAIL.to_string()
257            );
258        });
259    }
260
261    #[test]
262    fn test_co_authors() {
263        commit_fixture(|_, commit| {
264            for co_auth in commit.co_authors() {
265                assert!(co_auth.is_ok());
266            }
267        });
268    }
269
270    #[test]
271    fn test_committer() {
272        commit_fixture(|_, commit| {
273            assert_eq!(
274                commit.committer().name().unwrap(),
275                EXPECTED_ACTOR_NAME.to_string()
276            );
277            assert_eq!(
278                commit.committer().email().unwrap(),
279                EXPECTED_ACTOR_EMAIL.to_string()
280            );
281        });
282    }
283
284    #[test]
285    fn test_parents() {
286        commit_fixture(|_, commit| {
287            assert_eq!(commit.parents().collect::<Vec<String>>().len(), 1);
288        });
289    }
290
291    #[test]
292    fn test_is_merge() {
293        commit_fixture(|_, commit| {
294            assert!(!commit.is_merge());
295        });
296    }
297
298    #[test]
299    fn test_insertions() {
300        commit_fixture(|_, commit| {
301            assert_eq!(commit.insertions().unwrap(), 1);
302        });
303    }
304
305    #[test]
306    fn test_deletions() {
307        commit_fixture(|_, commit| {
308            assert_eq!(commit.deletions().unwrap(), 0);
309        });
310    }
311
312    #[test]
313    fn test_lines() {
314        commit_fixture(|_, commit| {
315            assert_eq!(commit.lines().unwrap(), 1);
316        });
317    }
318
319    #[test]
320    fn test_stat() {
321        commit_fixture(|_, commit| {
322            // Won't compile if return type is bad, stat otherwise checked in insertions
323            // and deletions test functions
324            let _: git2::DiffStats = commit
325                .stats()
326                .expect("Failed to construct git2 Stats object");
327        });
328    }
329
330    #[test]
331    fn test_iter_matches() {
332        let haystack = "Co-authored-by: John <john@example.com>";
333        assert_eq!(iter_co_authors(haystack).collect::<Vec<&str>>().len(), 1);
334
335        let haystack = "No matches expected";
336        assert_eq!(iter_co_authors(haystack).collect::<Vec<&str>>().len(), 0);
337    }
338}