1use regex::Regex;
2use std::sync::LazyLock;
3use std::{cell::OnceCell, str::FromStr};
4
5use crate::{Actor, Error, ModifiedFile, Repository};
6
7fn iter_co_authors(haystack: &str) -> impl Iterator<Item = &str> {
10 const CO_AUTHOR_REGEX: &str = r"(?m)^Co-authored-by: (.*) <(.*?)>$";
11 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
24pub 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 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 pub fn hash(&self) -> String {
43 self.inner.id().to_string()
44 }
45
46 pub fn msg(&self) -> Option<&str> {
48 self.inner.message()
49 }
50
51 pub fn author(&self) -> Actor {
53 Actor::new(self.inner.author())
54 }
55
56 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 pub fn committer(&self) -> Actor {
67 Actor::new(self.inner.committer())
68 }
69
70 pub fn branches(&self) -> Result<impl Iterator<Item = Result<String, Error>>, Error> {
76 self.branch_iterator(None)
77 }
78
79 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 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 pub fn parents(&self) -> impl Iterator<Item = String> {
101 self.inner.parent_ids().map(|id| id.to_string())
102 }
103
104 pub fn is_merge(&self) -> bool {
106 self.inner.parent_count() > 1
107 }
108
109 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 pub fn insertions(&self) -> Result<usize, Error> {
118 Ok(self.stats()?.insertions())
119 }
120
121 pub fn deletions(&self) -> Result<usize, Error> {
123 Ok(self.stats()?.deletions())
124 }
125
126 pub fn lines(&self) -> Result<usize, Error> {
128 Ok(self.insertions()? + self.deletions()?)
129 }
130
131 pub fn files(&self) -> Result<usize, Error> {
133 Ok(self.stats()?.files_changed())
134 }
135
136 fn stats(&self) -> Result<git2::DiffStats, Error> {
139 let diff = self.diff()?;
140 diff.stats().map_err(Error::Git)
141 }
142
143 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 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 .diff_tree_to_tree(parent_tree.as_ref(), this_tree.as_ref(), None)
161 .map_err(Error::Git)
162 }
163
164 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 _ => return Err(Error::PathError("Placeholder error".to_string())),
172 })
173 }
174
175 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 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 let oid = match branch.get().target() {
201 Some(v) => v,
202 None => return None,
203 };
204
205 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, 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 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 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}