gitai/git/
files.rs

1use crate::core::context::{ChangeType, RecentCommit, StagedFile};
2use crate::git::utils::is_binary_diff;
3use anyhow::{Context, Result};
4use git2::{DiffOptions, Repository, StatusOptions};
5use log::debug;
6use std::fs;
7use std::path::Path;
8
9use super::ignore_matcher::GitIgnoreMatcher;
10
11/// Collects repository information about files and branches
12#[derive(Debug)]
13pub struct RepoFilesInfo {
14    pub branch: String,
15    pub recent_commits: Vec<RecentCommit>,
16    pub staged_files: Vec<StagedFile>,
17    pub file_paths: Vec<String>,
18}
19
20/// Retrieves the status of files in the repository.
21///
22/// # Arguments
23///
24/// * `repo` - The git repository
25/// * `gitignore_matcher` - The gitignore matcher for file exclusion
26///
27/// # Returns
28///
29/// A Result containing a Vec of `StagedFile` objects or an error.
30pub fn get_file_statuses(
31    repo: &Repository,
32    gitignore_matcher: &GitIgnoreMatcher,
33) -> Result<Vec<StagedFile>> {
34    debug!("Getting file statuses");
35    let mut staged_files = Vec::new();
36
37    let mut opts = StatusOptions::new();
38    opts.include_untracked(true);
39    let statuses = repo.statuses(Some(&mut opts))?;
40
41    for entry in statuses.iter() {
42        let path = entry.path().context("Could not get path")?;
43        let status = entry.status();
44
45        if status.is_index_new() || status.is_index_modified() || status.is_index_deleted() {
46            let change_type = if status.is_index_new() {
47                ChangeType::Added
48            } else if status.is_index_modified() {
49                ChangeType::Modified
50            } else {
51                ChangeType::Deleted
52            };
53
54            let should_exclude = gitignore_matcher.should_exclude(path);
55            let diff = if should_exclude {
56                String::from("[Content excluded]")
57            } else {
58                get_diff_for_file(repo, path)?
59            };
60
61            let content =
62                if should_exclude || change_type != ChangeType::Modified || is_binary_diff(&diff) {
63                    None
64                } else {
65                    let path_obj = Path::new(path);
66                    if path_obj.exists() {
67                        Some(fs::read_to_string(path_obj)?)
68                    } else {
69                        None
70                    }
71                };
72
73            staged_files.push(StagedFile {
74                path: path.to_string(),
75                change_type,
76                diff,
77                content,
78                content_excluded: should_exclude,
79            });
80        }
81    }
82
83    debug!("Found {} staged files", staged_files.len());
84    Ok(staged_files)
85}
86
87/// Retrieves the diff for a specific file.
88///
89/// # Arguments
90///
91/// * `repo` - The git repository
92/// * `path` - The path of the file to get the diff for.
93///
94/// # Returns
95///
96/// A Result containing the diff as a String or an error.
97pub fn get_diff_for_file(repo: &Repository, path: &str) -> Result<String> {
98    debug!("Getting diff for file: {}", path);
99    let mut diff_options = DiffOptions::new();
100    diff_options.pathspec(path);
101
102    let tree = match repo.head() {
103        Ok(head) => Some(head.peel_to_tree()?),
104        Err(_) => {
105            // For fresh repos with no HEAD, treat as if comparing against empty tree
106            None
107        }
108    };
109
110    let diff = repo.diff_tree_to_workdir_with_index(tree.as_ref(), Some(&mut diff_options))?;
111
112    let mut diff_string = String::new();
113    diff.print(git2::DiffFormat::Patch, |_delta, _hunk, line| {
114        let origin = match line.origin() {
115            '+' | '-' | ' ' => line.origin(),
116            _ => ' ',
117        };
118        diff_string.push(origin);
119        diff_string.push_str(&String::from_utf8_lossy(line.content()));
120        true
121    })?;
122
123    if is_binary_diff(&diff_string) {
124        Ok("[Binary file changed]".to_string())
125    } else {
126        debug!("Generated diff for {} ({} bytes)", path, diff_string.len());
127        Ok(diff_string)
128    }
129}
130
131/// Gets unstaged file changes from the repository
132///
133/// # Returns
134///
135/// A Result containing a Vec of `StagedFile` objects for unstaged changes or an error.
136pub fn get_unstaged_file_statuses(
137    repo: &Repository,
138    gitignore_matcher: &GitIgnoreMatcher,
139) -> Result<Vec<StagedFile>> {
140    debug!("Getting unstaged file statuses");
141    let mut unstaged_files = Vec::new();
142
143    let mut opts = StatusOptions::new();
144    opts.include_untracked(true);
145    let statuses = repo.statuses(Some(&mut opts))?;
146
147    for entry in statuses.iter() {
148        let path = entry.path().context("Could not get path")?;
149        let status = entry.status();
150
151        // Look for changes in the working directory (unstaged)
152        if status.is_wt_new() || status.is_wt_modified() || status.is_wt_deleted() {
153            let change_type = if status.is_wt_new() {
154                ChangeType::Added
155            } else if status.is_wt_modified() {
156                ChangeType::Modified
157            } else {
158                ChangeType::Deleted
159            };
160
161            let should_exclude = gitignore_matcher.should_exclude(path);
162            let diff = if should_exclude {
163                String::from("[Content excluded]")
164            } else {
165                get_diff_for_unstaged_file(repo, path)?
166            };
167
168            let content =
169                if should_exclude || change_type != ChangeType::Modified || is_binary_diff(&diff) {
170                    None
171                } else {
172                    let path_obj = Path::new(path);
173                    if path_obj.exists() {
174                        Some(fs::read_to_string(path_obj)?)
175                    } else {
176                        None
177                    }
178                };
179
180            unstaged_files.push(StagedFile {
181                path: path.to_string(),
182                change_type,
183                diff,
184                content,
185                content_excluded: should_exclude,
186            });
187        }
188    }
189
190    debug!("Found {} unstaged files", unstaged_files.len());
191    Ok(unstaged_files)
192}
193
194/// Gets the diff for an unstaged file
195///
196/// # Arguments
197///
198/// * `repo` - The git repository
199/// * `path` - The path of the file to get the diff for.
200///
201/// # Returns
202///
203/// A Result containing the diff as a String or an error.
204pub fn get_diff_for_unstaged_file(repo: &Repository, path: &str) -> Result<String> {
205    debug!("Getting unstaged diff for file: {}", path);
206    let mut diff_options = DiffOptions::new();
207    diff_options.pathspec(path);
208
209    // For unstaged changes, we compare the index (staged) to the working directory
210    let diff = repo.diff_index_to_workdir(None, Some(&mut diff_options))?;
211
212    let mut diff_string = String::new();
213    diff.print(git2::DiffFormat::Patch, |_delta, _hunk, line| {
214        let origin = match line.origin() {
215            '+' | '-' | ' ' => line.origin(),
216            _ => ' ',
217        };
218        diff_string.push(origin);
219        diff_string.push_str(&String::from_utf8_lossy(line.content()));
220        true
221    })?;
222
223    if is_binary_diff(&diff_string) {
224        Ok("[Binary file changed]".to_string())
225    } else {
226        debug!(
227            "Generated unstaged diff for {} ({} bytes)",
228            path,
229            diff_string.len()
230        );
231        Ok(diff_string)
232    }
233}