1use regex::Regex;
2use std::path::Path;
3use std::sync::LazyLock;
4use std::{cell::OnceCell, str::FromStr};
5
6use crate::{Actor, Error, ModifiedFile, Repository};
7
8fn iter_co_authors(haystack: &str) -> impl Iterator<Item = &str> {
11 const CO_AUTHOR_REGEX: &str = r"(?m)^Co-authored-by: (.*) <(.*?)>$";
12 static RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(CO_AUTHOR_REGEX).unwrap());
14
15 let prefix = "Co-authored-by:";
16 RE.find_iter(haystack).map(move |re_match| {
17 re_match
18 .as_str()
19 .strip_prefix(prefix)
20 .unwrap_or_default()
21 .trim()
22 })
23}
24
25pub struct Commit<'repo> {
27 inner: git2::Commit<'repo>,
28 ctx: &'repo Repository,
29 cache: OnceCell<git2::Diff<'repo>>,
30}
31
32impl<'repo> Commit<'repo> {
33 pub fn new(commit: git2::Commit<'repo>, repository: &'repo Repository) -> Self {
35 Self {
36 inner: commit.to_owned(),
37 ctx: repository,
38 cache: OnceCell::new(),
39 }
40 }
41
42 pub fn hash(&self) -> String {
44 self.inner.id().to_string()
45 }
46
47 pub fn msg(&self) -> Option<&str> {
49 self.inner.message()
50 }
51
52 pub fn author(&self) -> Actor {
54 Actor::new(self.inner.author())
55 }
56
57 pub fn co_authors(&self) -> impl Iterator<Item = Result<Actor, Error>> {
62 let commit_msg = self.msg().unwrap_or_default();
63 iter_co_authors(commit_msg).map(Actor::from_str)
64 }
65
66 pub fn committer(&self) -> Actor {
68 Actor::new(self.inner.committer())
69 }
70
71 pub fn branches(&self) -> Result<impl Iterator<Item = Result<String, Error>>, Error> {
77 self.branch_iterator(None)
78 }
79
80 pub fn local_branches(&self) -> Result<impl Iterator<Item = Result<String, Error>>, Error> {
86 let flag = Some(git2::BranchType::Local);
87 self.branch_iterator(flag)
88 }
89
90 pub fn remote_branches(&self) -> Result<impl Iterator<Item = Result<String, Error>>, Error> {
96 let flag = Some(git2::BranchType::Remote);
97 self.branch_iterator(flag)
98 }
99
100 pub fn parent_commits(&self) -> impl Iterator<Item = Result<Commit<'_>, Error>> {
102 self.inner.parent_ids().map(|oid| {
103 self.ctx
104 .raw()
105 .find_commit(oid)
106 .map_err(Error::Git)
107 .map(|gitc| Commit::new(gitc, self.ctx))
108 })
109 }
110
111 pub fn parents(&self) -> impl Iterator<Item = String> {
113 self.inner.parent_ids().map(|p| p.to_string())
114 }
115
116 pub fn is_merge(&self) -> bool {
118 self.inner.parent_count() > 1
119 }
120
121 pub fn in_main(&self) -> Result<bool, Error> {
123 let b = self
124 .local_branches()?
125 .collect::<Vec<Result<String, Error>>>();
126 Ok(b.contains(&Ok("main".to_string())) || b.contains(&Ok("master".to_string())))
127 }
128
129 pub fn mod_files(&self) -> Result<impl Iterator<Item = ModifiedFile<'_>>, Error> {
131 let diff = self.diff()?;
132
133 Ok((0..diff.deltas().len()).map(move |n| ModifiedFile::new(diff, n)))
134 }
135
136 pub fn insertions(&self) -> Result<usize, Error> {
138 Ok(self.stats()?.insertions())
139 }
140
141 pub fn deletions(&self) -> Result<usize, Error> {
143 Ok(self.stats()?.deletions())
144 }
145
146 pub fn lines(&self) -> Result<usize, Error> {
148 Ok(self.insertions()? + self.deletions()?)
149 }
150
151 pub fn files(&self) -> Result<usize, Error> {
153 Ok(self.stats()?.files_changed())
154 }
155
156 pub fn project_path(&self) -> &Path {
158 let git_folder = self.ctx.raw().path();
159 git_folder.parent().unwrap()
161 }
162
163 pub fn project_name(&self) -> Option<&str> {
165 self.project_path().file_name().and_then(|s| s.to_str())
166 }
167
168 fn stats(&self) -> Result<git2::DiffStats, Error> {
171 let diff = self.diff()?;
172 diff.stats().map_err(Error::Git)
173 }
174
175 fn diff(&self) -> Result<&git2::Diff<'repo>, Error> {
179 let diff = self.calculate_diff()?;
180 Ok(self.cache.get_or_init(|| diff))
181 }
182
183 fn calculate_diff(&self) -> Result<git2::Diff<'repo>, Error> {
186 let this_tree = self.inner.tree().ok();
187 let parent_tree = self.resolve_parent_tree()?;
188
189 self.ctx
190 .raw()
191 .diff_tree_to_tree(parent_tree.as_ref(), this_tree.as_ref(), None)
193 .map_err(Error::Git)
194 }
195
196 fn resolve_parent_tree(&self) -> Result<Option<git2::Tree<'_>>, Error> {
199 Ok(match self.inner.parent_count() {
200 0 => None,
201 1 => self.inner.parent(0).map_err(Error::Git)?.tree().ok(),
202 _ => return Err(Error::PathError("Placeholder error".to_string())),
204 })
205 }
206
207 fn commit_contains_branch(&self, branch: git2::Oid, commit: git2::Oid) -> bool {
212 self.ctx.raw().graph_descendant_of(branch, commit).is_ok()
213 }
214
215 fn branch_iterator(
217 &self,
218 bt: Option<git2::BranchType>,
219 ) -> Result<impl Iterator<Item = Result<String, Error>>, Error> {
220 let commit_id = self.inner.id();
221 let branches = self.ctx.raw().branches(bt).map_err(Error::Git)?;
222
223 Ok(branches.filter_map(move |res| {
224 let branch = match res {
225 Ok(v) => v.0,
226 Err(e) => return Some(Err(Error::Git(e))),
227 };
228
229 let oid = match branch.get().target() {
233 Some(v) => v,
234 None => return None,
235 };
236
237 if !self.commit_contains_branch(oid, commit_id) {
239 return None;
240 }
241
242 match branch.name() {
243 Ok(Some(name)) => Some(Ok(name.to_string())),
244 Ok(None) => None, Err(e) => Some(Err(Error::Git(e))),
246 }
247 }))
248 }
249}
250
251#[cfg(test)]
252mod test {
253 use super::*;
254 use crate::{Local, Repository, common::init_repo};
255
256 fn commit_fixture<F, R>(f: F) -> R
257 where
258 F: FnOnce(&Repository<Local>, &Commit) -> R,
259 {
260 let repo = init_repo();
261
262 let repo = Repository::<Local>::from_repository(repo);
263 let commit = repo.head().expect("Failed to get HEAD");
264
265 f(&repo, &commit)
266 }
267
268 #[test]
269 fn test_stat() {
270 commit_fixture(|_, commit| {
271 let _: git2::DiffStats = commit
274 .stats()
275 .expect("Failed to construct git2 Stats object");
276 });
277 }
278
279 #[test]
280 fn test_iter_matches() {
281 let haystack = "Co-authored-by: John <john@example.com>";
282 assert_eq!(iter_co_authors(haystack).collect::<Vec<&str>>().len(), 1);
283
284 let haystack = "No matches expected";
285 assert_eq!(iter_co_authors(haystack).collect::<Vec<&str>>().len(), 0);
286 }
287}