1use crate::core::context::{ChangeType, RecentCommit, StagedFile};
2use crate::git::utils::is_binary_diff;
3use anyhow::{Result, anyhow};
4use chrono;
5use git2::{FileMode, Repository};
6use log::debug;
7
8use super::ignore_matcher::GitIgnoreMatcher;
9
10#[derive(Debug)]
12pub struct CommitResult {
13 pub branch: String,
14 pub commit_hash: String,
15 pub files_changed: usize,
16 pub insertions: usize,
17 pub deletions: usize,
18 pub new_files: Vec<(String, FileMode)>,
19}
20
21#[derive(Debug)]
23pub struct CommitInfo {
24 pub branch: String,
25 pub commit: RecentCommit,
26 pub file_paths: Vec<String>,
27}
28
29pub fn amend_commit(
42 repo: &Repository,
43 message: &str,
44 commit_ref: &str,
45 is_remote: bool,
46) -> Result<CommitResult> {
47 if is_remote {
48 return Err(anyhow!(
49 "Cannot amend commits in a remote repository in read-only mode"
50 ));
51 }
52
53 if commit_ref != "HEAD" {
55 return Err(anyhow!("Only amending HEAD is currently supported"));
56 }
57
58 let head_commit = repo.head()?.peel_to_commit()?;
60
61 let signature = repo.signature()?;
63
64 let tree = if repo
66 .statuses(None)?
67 .iter()
68 .any(|s| s.status() != git2::Status::CURRENT)
69 {
70 let mut index = repo.index()?;
72 let tree_id = index.write_tree()?;
73 repo.find_tree(tree_id)?
74 } else {
75 head_commit.tree()?
77 };
78
79 let parents: Vec<git2::Commit> = head_commit.parents().collect();
81 let parent_refs: Vec<&git2::Commit> = parents.iter().collect();
82
83 let commit_oid = repo.commit(
85 None, &signature,
87 &signature,
88 message,
89 &tree,
90 &parent_refs,
91 )?;
92
93 repo.head()?
95 .set_target(commit_oid, "amend commit message")?;
96
97 let branch_name = repo.head()?.shorthand().unwrap_or("HEAD").to_string();
98 let commit = repo.find_commit(commit_oid)?;
99 let short_hash = commit.id().to_string()[..7].to_string();
100
101 let mut files_changed = 0;
102 let insertions = 0;
103 let deletions = 0;
104 let mut new_files = Vec::new();
105
106 let statuses = repo.statuses(None)?;
108 for entry in statuses.iter() {
109 if entry.status().contains(git2::Status::INDEX_NEW)
110 || entry.status().contains(git2::Status::INDEX_MODIFIED)
111 || entry.status().contains(git2::Status::INDEX_DELETED)
112 {
113 files_changed += 1;
114 }
115 }
116
117 let statuses = repo.statuses(None)?;
118
119 for entry in statuses.iter() {
120 if entry.status().contains(git2::Status::INDEX_NEW)
121 && let Some(path) = entry.path()
122 {
123 let mode = entry
124 .index_to_workdir()
125 .map_or(git2::FileMode::Blob, |d| d.new_file().mode());
126 new_files.push((path.to_string(), mode));
127 }
128 }
129
130 Ok(CommitResult {
131 branch: branch_name,
132 commit_hash: short_hash,
133 files_changed,
134 insertions,
135 deletions,
136 new_files,
137 })
138}
139
140pub fn commit(repo: &Repository, message: &str, is_remote: bool) -> Result<CommitResult> {
148 if is_remote {
149 return Err(anyhow!(
150 "Cannot commit to a remote repository in read-only mode"
151 ));
152 }
153
154 let signature = repo.signature()?;
155
156 let mut index = repo.index()?;
157
158 let mut files_changed = 0;
160 let insertions = 0;
161 let deletions = 0;
162 let mut new_files = Vec::new();
163
164 let head_tree = if let Ok(head) = repo.head() {
166 Some(head.peel_to_commit()?.tree()?)
167 } else {
168 None
169 };
170
171 for entry in index.iter() {
173 let path_str = std::str::from_utf8(&entry.path)?;
174 let path = std::path::Path::new(path_str);
175
176 let is_changed = if let Some(ref head_tree) = head_tree {
177 match head_tree.get_path(path) {
179 Ok(head_entry) => {
180 let head_oid = head_entry.id();
182 head_oid != entry.id
183 }
184 Err(_) => {
185 true
187 }
188 }
189 } else {
190 true
192 };
193
194 if is_changed {
195 files_changed += 1;
196 if let Some(ref head_tree) = head_tree {
198 if head_tree.get_path(path).is_err() {
199 new_files.push((path_str.to_string(), FileMode::Blob));
200 }
201 } else {
202 new_files.push((path_str.to_string(), FileMode::Blob));
203 }
204 }
205 }
206
207 let tree_id = index.write_tree()?;
208 let tree = repo.find_tree(tree_id)?;
209
210 let (commit_oid, branch_name) = if let Ok(head) = repo.head() {
212 let parent_commit = head.peel_to_commit()?;
214 let commit_oid = repo.commit(
215 Some("HEAD"),
216 &signature,
217 &signature,
218 message,
219 &tree,
220 &[&parent_commit],
221 )?;
222 (commit_oid, head.shorthand().unwrap_or("HEAD").to_string())
223 } else {
224 let commit_oid = repo.commit(Some("HEAD"), &signature, &signature, message, &tree, &[])?;
226 (commit_oid, "main".to_string())
227 };
228
229 let commit = repo.find_commit(commit_oid)?;
230 let short_hash = commit.id().to_string()[..7].to_string();
231
232 Ok(CommitResult {
233 branch: branch_name,
234 commit_hash: short_hash,
235 files_changed,
236 insertions,
237 deletions,
238 new_files,
239 })
240}
241
242pub fn get_commits_between_with_callback<T, F>(
255 repo: &Repository,
256 from: &str,
257 to: &str,
258 mut callback: F,
259) -> Result<Vec<T>>
260where
261 F: FnMut(&RecentCommit) -> Result<T>,
262{
263 let from_commit = repo.revparse_single(from)?.peel_to_commit()?;
264 let to_commit = repo.revparse_single(to)?.peel_to_commit()?;
265
266 let mut revwalk = repo.revwalk()?;
267 revwalk.push(to_commit.id())?;
268 revwalk.hide(from_commit.id())?;
269
270 revwalk
271 .filter_map(std::result::Result::ok)
272 .map(|id| {
273 let commit = repo.find_commit(id)?;
274 let recent_commit = RecentCommit {
275 hash: commit.id().to_string(),
276 message: commit.message().unwrap_or_default().to_string(),
277 author: commit.author().name().unwrap_or_default().to_string(),
278 timestamp: commit.time().seconds().to_string(),
279 };
280 callback(&recent_commit)
281 })
282 .collect()
283}
284
285pub fn get_commits_between_stream<F>(
291 repo: &Repository,
292 from: &str,
293 to: &str,
294 mut callback: F,
295) -> Result<()>
296where
297 F: FnMut(&RecentCommit) -> Result<()>,
298{
299 let from_commit = repo.revparse_single(from)?.peel_to_commit()?;
300 let to_commit = repo.revparse_single(to)?.peel_to_commit()?;
301
302 let mut revwalk = repo.revwalk()?;
303 revwalk.push(to_commit.id())?;
304 revwalk.hide(from_commit.id())?;
305
306 for oid in revwalk {
307 let oid = oid?;
308 let commit = repo.find_commit(oid)?;
309 let commit_message = commit.message().unwrap_or("").to_string();
310 let author = commit.author().name().unwrap_or("").to_string();
311 let timestamp = commit.time().seconds().to_string();
312
313 let recent_commit = RecentCommit {
314 hash: oid.to_string(),
315 message: commit_message,
316 author,
317 timestamp,
318 };
319
320 callback(&recent_commit)?;
321 }
322
323 Ok(())
324}
325
326pub fn get_commit_files(
337 repo: &Repository,
338 commit_id: &str,
339 gitignore_matcher: &GitIgnoreMatcher,
340) -> Result<Vec<StagedFile>> {
341 debug!("Getting files for commit: {}", commit_id);
342
343 let obj = repo.revparse_single(commit_id)?;
345 let commit = obj.peel_to_commit()?;
346
347 let commit_tree = commit.tree()?;
348 let parent_commit = if commit.parent_count() > 0 {
349 Some(commit.parent(0)?)
350 } else {
351 None
352 };
353
354 let parent_tree = parent_commit.map(|c| c.tree()).transpose()?;
355
356 let mut commit_files = Vec::new();
357
358 let diff = repo.diff_tree_to_tree(parent_tree.as_ref(), Some(&commit_tree), None)?;
359
360 diff.foreach(
362 &mut |delta, _| {
363 if let Some(path) = delta.new_file().path().and_then(|p| p.to_str()) {
364 let change_type = match delta.status() {
365 git2::Delta::Added => ChangeType::Added,
366 git2::Delta::Modified => ChangeType::Modified,
367 git2::Delta::Deleted => ChangeType::Deleted,
368 _ => return true, };
370
371 let should_exclude = gitignore_matcher.should_exclude(path);
372
373 commit_files.push(StagedFile {
374 path: path.to_string(),
375 change_type,
376 diff: String::new(), content: None,
378 content_excluded: should_exclude,
379 });
380 }
381 true
382 },
383 None,
384 None,
385 None,
386 )?;
387
388 for file in &mut commit_files {
390 if file.content_excluded {
391 file.diff = String::from("[Content excluded]");
392 continue;
393 }
394
395 let mut diff_options = git2::DiffOptions::new();
396 diff_options.pathspec(&file.path);
397
398 let file_diff = repo.diff_tree_to_tree(
399 parent_tree.as_ref(),
400 Some(&commit_tree),
401 Some(&mut diff_options),
402 )?;
403
404 let mut diff_string = String::new();
405 file_diff.print(git2::DiffFormat::Patch, |_delta, _hunk, line| {
406 let origin = match line.origin() {
407 '+' | '-' | ' ' => line.origin(),
408 _ => ' ',
409 };
410 diff_string.push(origin);
411 diff_string.push_str(&String::from_utf8_lossy(line.content()));
412 true
413 })?;
414
415 if is_binary_diff(&diff_string) {
416 file.diff = "[Binary file changed]".to_string();
417 } else {
418 file.diff = diff_string;
419 }
420 }
421
422 debug!("Found {} files in commit", commit_files.len());
423 Ok(commit_files)
424}
425
426pub fn extract_commit_info(repo: &Repository, commit_id: &str, branch: &str) -> Result<CommitInfo> {
428 let obj = repo.revparse_single(commit_id)?;
430 let commit = obj.peel_to_commit()?;
431
432 let commit_author = commit.author();
434 let author_name = commit_author.name().unwrap_or_default().to_string();
435 let commit_message = commit.message().unwrap_or_default().to_string();
436 let commit_time = commit.time().seconds().to_string();
437 let commit_hash = commit.id().to_string();
438
439 let recent_commit = RecentCommit {
441 hash: commit_hash,
442 message: commit_message,
443 author: author_name,
444 timestamp: commit_time,
445 };
446
447 let file_paths = get_file_paths_for_commit(repo, commit_id)?;
449
450 Ok(CommitInfo {
451 branch: branch.to_string(),
452 commit: recent_commit,
453 file_paths,
454 })
455}
456
457pub fn get_file_paths_for_commit(repo: &Repository, commit_id: &str) -> Result<Vec<String>> {
459 let obj = repo.revparse_single(commit_id)?;
461 let commit = obj.peel_to_commit()?;
462
463 let commit_tree = commit.tree()?;
464 let parent_commit = if commit.parent_count() > 0 {
465 Some(commit.parent(0)?)
466 } else {
467 None
468 };
469
470 let parent_tree = parent_commit.map(|c| c.tree()).transpose()?;
471
472 let mut file_paths = Vec::new();
473
474 let diff = repo.diff_tree_to_tree(parent_tree.as_ref(), Some(&commit_tree), None)?;
476
477 diff.foreach(
479 &mut |delta, _| {
480 if let Some(path) = delta.new_file().path().and_then(|p| p.to_str()) {
481 match delta.status() {
482 git2::Delta::Added | git2::Delta::Modified | git2::Delta::Deleted => {
483 file_paths.push(path.to_string());
484 }
485 _ => {} }
487 }
488 true
489 },
490 None,
491 None,
492 None,
493 )?;
494
495 Ok(file_paths)
496}
497
498pub fn get_commit_date(repo: &Repository, commit_ish: &str) -> Result<String> {
509 let obj = repo.revparse_single(commit_ish)?;
511 let commit = obj.peel_to_commit()?;
512
513 let time = commit.time();
515
516 let datetime = chrono::DateTime::<chrono::Utc>::from_timestamp(time.seconds(), 0)
518 .ok_or_else(|| anyhow!("Invalid timestamp"))?;
519
520 Ok(datetime.format("%Y-%m-%d").to_string())
522}
523
524pub fn get_branch_diff_files(
536 repo: &Repository,
537 base_branch: &str,
538 target_branch: &str,
539 gitignore_matcher: &GitIgnoreMatcher,
540) -> Result<Vec<StagedFile>> {
541 debug!(
542 "Getting files changed between branches: {} -> {}",
543 base_branch, target_branch
544 );
545
546 let base_commit = resolve_branch(repo, base_branch)?;
548 let target_commit = repo.revparse_single(target_branch)?.peel_to_commit()?;
549
550 let merge_base_oid = repo.merge_base(base_commit.id(), target_commit.id())?;
553 let merge_base_commit = repo.find_commit(merge_base_oid)?;
554
555 debug!("Using merge-base {} for comparison", merge_base_oid);
556
557 let base_tree = merge_base_commit.tree()?;
558 let target_tree = target_commit.tree()?;
559
560 let mut branch_files = Vec::new();
561
562 let diff = repo.diff_tree_to_tree(Some(&base_tree), Some(&target_tree), None)?;
565
566 diff.foreach(
568 &mut |delta, _| {
569 if let Some(path) = delta.new_file().path().and_then(|p| p.to_str()) {
570 let change_type = match delta.status() {
571 git2::Delta::Added => ChangeType::Added,
572 git2::Delta::Modified => ChangeType::Modified,
573 git2::Delta::Deleted => ChangeType::Deleted,
574 _ => return true, };
576
577 let should_exclude = gitignore_matcher.should_exclude(path);
578
579 branch_files.push(StagedFile {
580 path: path.to_string(),
581 change_type,
582 diff: String::new(), content: None,
584 content_excluded: should_exclude,
585 });
586 }
587 true
588 },
589 None,
590 None,
591 None,
592 )?;
593
594 for file in &mut branch_files {
596 if file.content_excluded {
597 file.diff = String::from("[Content excluded]");
598 continue;
599 }
600
601 let mut diff_options = git2::DiffOptions::new();
602 diff_options.pathspec(&file.path);
603
604 let file_diff = repo.diff_tree_to_tree(
605 Some(&base_tree),
606 Some(&target_tree),
607 Some(&mut diff_options),
608 )?;
609
610 let mut diff_string = String::new();
611 file_diff.print(git2::DiffFormat::Patch, |_delta, _hunk, line| {
612 let origin = match line.origin() {
613 '+' | '-' | ' ' => line.origin(),
614 _ => ' ',
615 };
616 diff_string.push(origin);
617 diff_string.push_str(&String::from_utf8_lossy(line.content()));
618 true
619 })?;
620
621 if is_binary_diff(&diff_string) {
622 file.diff = "[Binary file changed]".to_string();
623 } else {
624 file.diff = diff_string;
625 }
626
627 if matches!(file.change_type, ChangeType::Added | ChangeType::Modified)
629 && let Ok(entry) = target_tree.get_path(std::path::Path::new(&file.path))
630 && let Ok(object) = entry.to_object(repo)
631 && let Some(blob) = object.as_blob()
632 && let Ok(content) = std::str::from_utf8(blob.content())
633 {
634 file.content = Some(content.to_string());
635 }
636 }
637
638 debug!(
639 "Found {} files changed between branches (using merge-base)",
640 branch_files.len()
641 );
642 Ok(branch_files)
643}
644
645pub fn extract_branch_diff_info(
647 repo: &Repository,
648 base_branch: &str,
649 target_branch: &str,
650 gitignore_matcher: &GitIgnoreMatcher,
651) -> Result<(String, Vec<RecentCommit>, Vec<String>)> {
652 let display_branch = format!("{base_branch} -> {target_branch}");
654
655 let base_commit = resolve_branch_strict(repo, base_branch)?;
658 let target_commit = resolve_branch_strict(repo, target_branch)?;
659
660 let merge_base_oid = repo.merge_base(base_commit.id(), target_commit.id())?;
662 debug!("Using merge-base {} for commit history", merge_base_oid);
663
664 let mut revwalk = repo.revwalk()?;
665 revwalk.push(target_commit.id())?;
666 revwalk.hide(merge_base_oid)?; let recent_commits: Result<Vec<RecentCommit>> = revwalk
669 .take(10) .map(|oid| {
671 let oid = oid?;
672 let commit = repo.find_commit(oid)?;
673 let author = commit.author();
674 Ok(RecentCommit {
675 hash: oid.to_string(),
676 message: commit.message().unwrap_or_default().to_string(),
677 author: author.name().unwrap_or_default().to_string(),
678 timestamp: commit.time().seconds().to_string(),
679 })
680 })
681 .collect();
682
683 let recent_commits = recent_commits?;
684
685 let diff_files = get_branch_diff_files(repo, base_branch, target_branch, gitignore_matcher)?;
687 let file_paths: Vec<String> = diff_files.iter().map(|file| file.path.clone()).collect();
688
689 Ok((display_branch, recent_commits, file_paths))
690}
691
692pub fn get_commits_for_pr(repo: &Repository, from: &str, to: &str) -> Result<Vec<String>> {
704 debug!("Getting commits for PR between {} and {}", from, to);
705
706 let from_commit = repo.revparse_single(from)?.peel_to_commit()?;
707 let to_commit = repo.revparse_single(to)?.peel_to_commit()?;
708
709 let mut revwalk = repo.revwalk()?;
710 revwalk.push(to_commit.id())?;
711 revwalk.hide(from_commit.id())?;
712
713 let commits: Result<Vec<String>> = revwalk
714 .map(|oid| {
715 let oid = oid?;
716 let commit = repo.find_commit(oid)?;
717 let message = commit.message().unwrap_or_default();
718 let title = message.lines().next().unwrap_or_default();
720 Ok(format!("{}: {}", &oid.to_string()[..7], title))
721 })
722 .collect();
723
724 let mut result = commits?;
725 result.reverse(); debug!("Found {} commits for PR", result.len());
728 Ok(result)
729}
730
731pub fn get_commit_range_files(
743 repo: &Repository,
744 from: &str,
745 to: &str,
746 gitignore_matcher: &GitIgnoreMatcher,
747) -> Result<Vec<StagedFile>> {
748 debug!("Getting files changed in commit range: {} -> {}", from, to);
749
750 let from_commit = repo.revparse_single(from)?.peel_to_commit()?;
752 let to_commit = repo.revparse_single(to)?.peel_to_commit()?;
753
754 let from_tree = from_commit.tree()?;
755 let to_tree = to_commit.tree()?;
756
757 let mut range_files = Vec::new();
758
759 let diff = repo.diff_tree_to_tree(Some(&from_tree), Some(&to_tree), None)?;
761
762 diff.foreach(
764 &mut |delta, _| {
765 if let Some(path) = delta.new_file().path().and_then(|p| p.to_str()) {
766 let change_type = match delta.status() {
767 git2::Delta::Added => ChangeType::Added,
768 git2::Delta::Modified => ChangeType::Modified,
769 git2::Delta::Deleted => ChangeType::Deleted,
770 _ => return true, };
772
773 let should_exclude = gitignore_matcher.should_exclude(path);
774
775 range_files.push(StagedFile {
776 path: path.to_string(),
777 change_type,
778 diff: String::new(), content: None,
780 content_excluded: should_exclude,
781 });
782 }
783 true
784 },
785 None,
786 None,
787 None,
788 )?;
789
790 for file in &mut range_files {
792 if file.content_excluded {
793 file.diff = String::from("[Content excluded]");
794 continue;
795 }
796
797 let mut diff_options = git2::DiffOptions::new();
798 diff_options.pathspec(&file.path);
799
800 let file_diff =
801 repo.diff_tree_to_tree(Some(&from_tree), Some(&to_tree), Some(&mut diff_options))?;
802
803 let mut diff_string = String::new();
804 file_diff.print(git2::DiffFormat::Patch, |_delta, _hunk, line| {
805 let origin = match line.origin() {
806 '+' | '-' | ' ' => line.origin(),
807 _ => ' ',
808 };
809 diff_string.push(origin);
810 diff_string.push_str(&String::from_utf8_lossy(line.content()));
811 true
812 })?;
813
814 if is_binary_diff(&diff_string) {
815 file.diff = "[Binary file changed]".to_string();
816 } else {
817 file.diff = diff_string;
818 }
819
820 if matches!(file.change_type, ChangeType::Added | ChangeType::Modified)
822 && let Ok(entry) = to_tree.get_path(std::path::Path::new(&file.path))
823 && let Ok(object) = entry.to_object(repo)
824 && let Some(blob) = object.as_blob()
825 && let Ok(content) = std::str::from_utf8(blob.content())
826 {
827 file.content = Some(content.to_string());
828 }
829 }
830
831 debug!("Found {} files changed in commit range", range_files.len());
832 Ok(range_files)
833}
834
835pub fn extract_commit_range_info(
837 repo: &Repository,
838 from: &str,
839 to: &str,
840 gitignore_matcher: &GitIgnoreMatcher,
841) -> Result<(String, Vec<RecentCommit>, Vec<String>)> {
842 let display_range = format!("{from}..{to}");
844
845 let recent_commits: Result<Vec<RecentCommit>> =
847 get_commits_between_with_callback(repo, from, to, |commit| Ok(commit.clone()));
848 let recent_commits = recent_commits?;
849
850 let range_files = get_commit_range_files(repo, from, to, gitignore_matcher)?;
852 let file_paths: Vec<String> = range_files.iter().map(|file| file.path.clone()).collect();
853
854 Ok((display_range, recent_commits, file_paths))
855}
856
857fn resolve_branch_strict<'a>(
859 repo: &'a Repository,
860 branch_name: &'a str,
861) -> Result<git2::Commit<'a>> {
862 match repo.revparse_single(branch_name) {
863 Ok(obj) => Ok(obj.peel_to_commit()?),
864 Err(e) => Err(anyhow!(
865 "Could not resolve branch reference '{branch_name}': {e}"
866 )),
867 }
868}
869
870fn resolve_branch<'a>(repo: &'a Repository, branch_name: &'a str) -> Result<git2::Commit<'a>> {
872 if let Ok(obj) = repo.revparse_single(branch_name) {
874 Ok(obj.peel_to_commit()?)
875 } else {
876 debug!(
877 "Branch '{}' not found, trying common alternatives",
878 branch_name
879 );
880
881 let possible_branches = ["main", "master", "develop", "development"];
883
884 for &possible_branch in &possible_branches {
885 if possible_branch != branch_name {
886 match repo.revparse_single(possible_branch) {
887 Ok(obj) => {
888 debug!("Using alternative branch '{}'", possible_branch);
889 return Ok(obj.peel_to_commit()?);
890 }
891 Err(_) => {
892 debug!("Alternative branch '{}' not found", possible_branch);
893 }
894 }
895 }
896 }
897
898 Err(anyhow!(
899 "Could not resolve branch reference '{branch_name}'. Tried alternatives: {possible_branches:?}"
900 ))
901 }
902}