gitai/git/
commit.rs

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/// Results from a commit operation
11#[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/// Collects information about a specific commit
22#[derive(Debug)]
23pub struct CommitInfo {
24    pub branch: String,
25    pub commit: RecentCommit,
26    pub file_paths: Vec<String>,
27}
28
29/// Amend a commit with a new message
30///
31/// # Arguments
32///
33/// * `repo` - The git repository
34/// * `message` - The new commit message
35/// * `commit_ref` - The commit reference to amend (currently only "HEAD" is supported)
36/// * `is_remote` - Whether the repository is remote
37///
38/// # Returns
39///
40/// A Result containing the `CommitResult` or an error
41pub 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    // For now, only support amending HEAD
54    if commit_ref != "HEAD" {
55        return Err(anyhow!("Only amending HEAD is currently supported"));
56    }
57
58    // Get the current HEAD commit
59    let head_commit = repo.head()?.peel_to_commit()?;
60
61    // Get the signature for the new commit
62    let signature = repo.signature()?;
63
64    // Use the HEAD commit's tree (or current index if there are staged changes)
65    let tree = if repo
66        .statuses(None)?
67        .iter()
68        .any(|s| s.status() != git2::Status::CURRENT)
69    {
70        // There are staged changes, use current index
71        let mut index = repo.index()?;
72        let tree_id = index.write_tree()?;
73        repo.find_tree(tree_id)?
74    } else {
75        // No staged changes, use the HEAD commit's tree
76        head_commit.tree()?
77    };
78
79    // Get all parents of the HEAD commit
80    let parents: Vec<git2::Commit> = head_commit.parents().collect();
81    let parent_refs: Vec<&git2::Commit> = parents.iter().collect();
82
83    // Create new commit with same parents but new message
84    let commit_oid = repo.commit(
85        None, // Don't update any reference automatically
86        &signature,
87        &signature,
88        message,
89        &tree,
90        &parent_refs,
91    )?;
92
93    // Manually update HEAD to point to the new commit
94    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    // Count staged files for commit stats
107    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
140/// * `repo` - The git repository
141/// * `message` - The commit message.
142/// * `is_remote` - Whether the repository is remote.
143///
144/// # Returns
145///
146/// A Result containing the `CommitResult` or an error.
147pub 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    // Count staged files BEFORE the commit by comparing index with HEAD
159    let mut files_changed = 0;
160    let insertions = 0;
161    let deletions = 0;
162    let mut new_files = Vec::new();
163
164    // Get HEAD tree for comparison
165    let head_tree = if let Ok(head) = repo.head() {
166        Some(head.peel_to_commit()?.tree()?)
167    } else {
168        None
169    };
170
171    // Compare each index entry with HEAD
172    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            // Check if file exists in HEAD
178            match head_tree.get_path(path) {
179                Ok(head_entry) => {
180                    // File exists in HEAD, check if different
181                    let head_oid = head_entry.id();
182                    head_oid != entry.id
183                }
184                Err(_) => {
185                    // File doesn't exist in HEAD, so it's new
186                    true
187                }
188            }
189        } else {
190            // Fresh repo, all files are new
191            true
192        };
193
194        if is_changed {
195            files_changed += 1;
196            // For new files, check if it's actually new
197            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    // Handle fresh repositories (no HEAD) vs existing repositories
211    let (commit_oid, branch_name) = if let Ok(head) = repo.head() {
212        // Existing repository with HEAD
213        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        // Fresh repository - create initial commit with no parents
225        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
242/// Retrieves commits between two Git references.
243///
244/// # Arguments
245///
246/// * `repo` - The git repository
247/// * `from` - The starting Git reference.
248/// * `to` - The ending Git reference.
249/// * `callback` - A callback function to process each commit.
250///
251/// # Returns
252///
253/// A Result containing a Vec of processed commits or an error.
254pub 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
285/// Stream commits between two references with a callback that sends results
286///
287/// # Returns
288///
289/// A Result indicating success or an error.
290pub 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
326/// Retrieves the files changed in a specific commit
327///
328/// # Arguments
329///
330/// * `repo` - The git repository
331/// * `commit_id` - The ID of the commit to analyze.
332///
333/// # Returns
334///
335/// A Result containing a Vec of `StagedFile` objects for the commit or an error.
336pub 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    // Parse the commit ID
344    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    // Get statistics for each file and convert to our StagedFile format
361    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, // Skip other types of changes
369                };
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(), // Will be populated later
377                    content: None,
378                    content_excluded: should_exclude,
379                });
380            }
381            true
382        },
383        None,
384        None,
385        None,
386    )?;
387
388    // Get the diff for each file
389    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
426/// Extract commit info without crossing async boundaries
427pub fn extract_commit_info(repo: &Repository, commit_id: &str, branch: &str) -> Result<CommitInfo> {
428    // Parse the commit ID
429    let obj = repo.revparse_single(commit_id)?;
430    let commit = obj.peel_to_commit()?;
431
432    // Extract commit information
433    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    // Create the recent commit object
440    let recent_commit = RecentCommit {
441        hash: commit_hash,
442        message: commit_message,
443        author: author_name,
444        timestamp: commit_time,
445    };
446
447    // Get file paths from this commit
448    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
457/// Gets just the file paths for a specific commit (not the full content)
458pub fn get_file_paths_for_commit(repo: &Repository, commit_id: &str) -> Result<Vec<String>> {
459    // Parse the commit ID
460    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    // Create diff between trees
475    let diff = repo.diff_tree_to_tree(parent_tree.as_ref(), Some(&commit_tree), None)?;
476
477    // Extract file paths
478    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                    _ => {} // Skip other types of changes
486                }
487            }
488            true
489        },
490        None,
491        None,
492        None,
493    )?;
494
495    Ok(file_paths)
496}
497
498/// Gets the date of a commit in YYYY-MM-DD format
499///
500/// # Arguments
501///
502/// * `repo` - The git repository
503/// * `commit_ish` - A commit-ish reference (hash, tag, branch, etc.)
504///
505/// # Returns
506///
507/// A Result containing the formatted date string or an error
508pub fn get_commit_date(repo: &Repository, commit_ish: &str) -> Result<String> {
509    // Resolve the commit-ish to an actual commit
510    let obj = repo.revparse_single(commit_ish)?;
511    let commit = obj.peel_to_commit()?;
512
513    // Get the commit time
514    let time = commit.time();
515
516    // Convert to a chrono::DateTime for easier formatting
517    let datetime = chrono::DateTime::<chrono::Utc>::from_timestamp(time.seconds(), 0)
518        .ok_or_else(|| anyhow!("Invalid timestamp"))?;
519
520    // Format as YYYY-MM-DD
521    Ok(datetime.format("%Y-%m-%d").to_string())
522}
523
524/// Gets the files changed between two branches
525///
526/// # Arguments
527///
528/// * `repo` - The git repository
529/// * `base_branch` - The base branch (e.g., "main")
530/// * `target_branch` - The target branch (e.g., "feature-branch")
531///
532/// # Returns
533///
534/// A Result containing a Vec of `StagedFile` objects for the branch comparison or an error.
535pub 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    // Resolve branch references
547    let base_commit = resolve_branch(repo, base_branch)?;
548    let target_commit = repo.revparse_single(target_branch)?.peel_to_commit()?;
549
550    // Find the merge-base (common ancestor) between the branches
551    // This gives us the point where the target branch diverged from the base branch
552    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    // Create diff between the merge-base tree and target tree
563    // This shows only changes made in the target branch since it diverged
564    let diff = repo.diff_tree_to_tree(Some(&base_tree), Some(&target_tree), None)?;
565
566    // Get statistics for each file and convert to our StagedFile format
567    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, // Skip other types of changes
575                };
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(), // Will be populated later
583                    content: None,
584                    content_excluded: should_exclude,
585                });
586            }
587            true
588        },
589        None,
590        None,
591        None,
592    )?;
593
594    // Get the diff for each file
595    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        // Get file content from target branch if it's a modified or added file
628        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
645/// Extract branch comparison info without crossing async boundaries
646pub 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    // Get the target branch name for display
653    let display_branch = format!("{base_branch} -> {target_branch}");
654
655    // Resolve branch references without fallback for explicit branch comparison
656    // This ensures that nonexistent branches will cause an error as expected by tests
657    let base_commit = resolve_branch_strict(repo, base_branch)?;
658    let target_commit = resolve_branch_strict(repo, target_branch)?;
659
660    // Find the merge-base (common ancestor) between the branches
661    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)?; // Hide the merge-base commit itself
667
668    let recent_commits: Result<Vec<RecentCommit>> = revwalk
669        .take(10) // Limit to 10 most recent commits in the branch
670        .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    // Get file paths from the diff for metadata
686    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
692/// Gets commits between two references with their messages for PR descriptions
693///
694/// # Arguments
695///
696/// * `repo` - The git repository
697/// * `from` - The starting Git reference (exclusive)
698/// * `to` - The ending Git reference (inclusive)
699///
700/// # Returns
701///
702/// A Result containing a Vec of formatted commit messages or an error.
703pub 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            // Get just the first line (title) of the commit message
719            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(); // Show commits in chronological order
726
727    debug!("Found {} commits for PR", result.len());
728    Ok(result)
729}
730
731/// Gets the files changed in a commit range (similar to branch diff but for commit range)
732///
733/// # Arguments
734///
735/// * `repo` - The git repository
736/// * `from` - The starting Git reference (exclusive)
737/// * `to` - The ending Git reference (inclusive)
738///
739/// # Returns
740///
741/// A Result containing a Vec of `StagedFile` objects for the commit range or an error.
742pub 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    // Resolve commit references
751    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    // Create diff between the from and to trees
760    let diff = repo.diff_tree_to_tree(Some(&from_tree), Some(&to_tree), None)?;
761
762    // Get statistics for each file and convert to our StagedFile format
763    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, // Skip other types of changes
771                };
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(), // Will be populated later
779                    content: None,
780                    content_excluded: should_exclude,
781                });
782            }
783            true
784        },
785        None,
786        None,
787        None,
788    )?;
789
790    // Get the diff for each file
791    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        // Get file content from to commit if it's a modified or added file
821        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
835/// Extract commit range info without crossing async boundaries
836pub 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    // Get the range name for display
843    let display_range = format!("{from}..{to}");
844
845    // Get commits in the range
846    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    // Get file paths from the range for metadata
851    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
857/// Helper function to strictly resolve a branch reference without fallbacks
858fn 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
870/// Helper function to resolve a branch reference, trying common default names if the specified branch doesn't exist
871fn resolve_branch<'a>(repo: &'a Repository, branch_name: &'a str) -> Result<git2::Commit<'a>> {
872    // Try the specified branch first
873    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        // Common default branch names to try
882        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}