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 parents(&self) -> impl Iterator<Item = String> {
102 self.inner.parent_ids().map(|id| id.to_string())
103 }
104
105 pub fn is_merge(&self) -> bool {
107 self.inner.parent_count() > 1
108 }
109
110 pub fn in_main(&self) -> Result<bool, Error> {
112 let b = self
113 .local_branches()?
114 .collect::<Vec<Result<String, Error>>>();
115 Ok(b.contains(&Ok("main".to_string())) || b.contains(&Ok("master".to_string())))
116 }
117
118 pub fn mod_files(&self) -> Result<impl Iterator<Item = ModifiedFile<'_>>, Error> {
120 let diff = self.diff()?;
121
122 Ok((0..diff.deltas().len()).map(move |n| ModifiedFile::new(diff, n)))
123 }
124
125 pub fn insertions(&self) -> Result<usize, Error> {
127 Ok(self.stats()?.insertions())
128 }
129
130 pub fn deletions(&self) -> Result<usize, Error> {
132 Ok(self.stats()?.deletions())
133 }
134
135 pub fn lines(&self) -> Result<usize, Error> {
137 Ok(self.insertions()? + self.deletions()?)
138 }
139
140 pub fn files(&self) -> Result<usize, Error> {
142 Ok(self.stats()?.files_changed())
143 }
144
145 pub fn project_path(&self) -> &Path {
147 let git_folder = self.ctx.raw().path();
148 git_folder.parent().unwrap()
150 }
151
152 fn stats(&self) -> Result<git2::DiffStats, Error> {
155 let diff = self.diff()?;
156 diff.stats().map_err(Error::Git)
157 }
158
159 fn diff(&self) -> Result<&git2::Diff<'repo>, Error> {
163 let diff = self.calculate_diff()?;
164 Ok(self.cache.get_or_init(|| diff))
165 }
166
167 fn calculate_diff(&self) -> Result<git2::Diff<'repo>, Error> {
170 let this_tree = self.inner.tree().ok();
171 let parent_tree = self.resolve_parent_tree()?;
172
173 self.ctx
174 .raw()
175 .diff_tree_to_tree(parent_tree.as_ref(), this_tree.as_ref(), None)
177 .map_err(Error::Git)
178 }
179
180 fn resolve_parent_tree(&self) -> Result<Option<git2::Tree<'_>>, Error> {
183 Ok(match self.inner.parent_count() {
184 0 => None,
185 1 => self.inner.parent(0).map_err(Error::Git)?.tree().ok(),
186 _ => return Err(Error::PathError("Placeholder error".to_string())),
188 })
189 }
190
191 fn commit_contains_branch(&self, branch: git2::Oid, commit: git2::Oid) -> bool {
196 self.ctx.raw().graph_descendant_of(branch, commit).is_ok()
197 }
198
199 fn branch_iterator(
201 &self,
202 bt: Option<git2::BranchType>,
203 ) -> Result<impl Iterator<Item = Result<String, Error>>, Error> {
204 let commit_id = self.inner.id();
205 let branches = self.ctx.raw().branches(bt).map_err(Error::Git)?;
206
207 Ok(branches.filter_map(move |res| {
208 let branch = match res {
209 Ok(v) => v.0,
210 Err(e) => return Some(Err(Error::Git(e))),
211 };
212
213 let oid = match branch.get().target() {
217 Some(v) => v,
218 None => return None,
219 };
220
221 if !self.commit_contains_branch(oid, commit_id) {
223 return None;
224 }
225
226 match branch.name() {
227 Ok(Some(name)) => Some(Ok(name.to_string())),
228 Ok(None) => None, Err(e) => Some(Err(Error::Git(e))),
230 }
231 }))
232 }
233}
234
235#[cfg(test)]
236mod test {
237 use super::*;
238 use crate::{
239 Local, Repository,
240 common::{EXPECTED_ACTOR_EMAIL, EXPECTED_ACTOR_NAME, EXPECTED_MSG, init_repo},
241 };
242
243 fn commit_fixture<F, R>(f: F) -> R
244 where
245 F: FnOnce(&Repository<Local>, &Commit) -> R,
246 {
247 let repo = init_repo();
248
249 let repo = Repository::<Local>::from_repository(repo);
250 let commit = repo.head().expect("Failed to get HEAD");
251
252 f(&repo, &commit)
253 }
254
255 #[test]
256 fn test_msg() {
257 commit_fixture(|_, commit| {
258 assert_eq!(commit.msg(), Some(EXPECTED_MSG));
260 });
261 }
262
263 #[test]
264 fn test_author() {
265 commit_fixture(|_, commit| {
266 assert_eq!(
267 commit.author().name().unwrap(),
268 EXPECTED_ACTOR_NAME.to_string()
269 );
270 assert_eq!(
271 commit.author().email().unwrap(),
272 EXPECTED_ACTOR_EMAIL.to_string()
273 );
274 });
275 }
276
277 #[test]
278 fn test_co_authors() {
279 commit_fixture(|_, commit| {
280 for co_auth in commit.co_authors() {
281 assert!(co_auth.is_ok());
282 }
283 });
284 }
285
286 #[test]
287 fn test_committer() {
288 commit_fixture(|_, commit| {
289 assert_eq!(
290 commit.committer().name().unwrap(),
291 EXPECTED_ACTOR_NAME.to_string()
292 );
293 assert_eq!(
294 commit.committer().email().unwrap(),
295 EXPECTED_ACTOR_EMAIL.to_string()
296 );
297 });
298 }
299
300 #[test]
301 fn test_parents() {
302 commit_fixture(|_, commit| {
303 assert_eq!(commit.parents().collect::<Vec<String>>().len(), 1);
304 });
305 }
306
307 #[test]
308 fn test_is_merge() {
309 commit_fixture(|_, commit| {
310 assert!(!commit.is_merge());
311 });
312 }
313
314 #[test]
315 fn test_insertions() {
316 commit_fixture(|_, commit| {
317 assert_eq!(commit.insertions().unwrap(), 1);
318 });
319 }
320
321 #[test]
322 fn test_deletions() {
323 commit_fixture(|_, commit| {
324 assert_eq!(commit.deletions().unwrap(), 0);
325 });
326 }
327
328 #[test]
329 fn test_lines() {
330 commit_fixture(|_, commit| {
331 assert_eq!(commit.lines().unwrap(), 1);
332 });
333 }
334
335 #[test]
336 fn test_stat() {
337 commit_fixture(|_, commit| {
338 let _: git2::DiffStats = commit
341 .stats()
342 .expect("Failed to construct git2 Stats object");
343 });
344 }
345
346 #[test]
347 fn test_iter_matches() {
348 let haystack = "Co-authored-by: John <john@example.com>";
349 assert_eq!(iter_co_authors(haystack).collect::<Vec<&str>>().len(), 1);
350
351 let haystack = "No matches expected";
352 assert_eq!(iter_co_authors(haystack).collect::<Vec<&str>>().len(), 0);
353 }
354}