Skip to main content

agent_hub_runtime/core/project_git/
history.rs

1//! Read-only commit inspection against the first parent (or the empty initial tree).
2use anyhow::{bail, Result};
3use serde::Serialize;
4use std::path::Path;
5
6#[derive(Serialize)]
7pub struct CommitFile {
8    pub path: String,
9    pub old_path: Option<String>,
10    pub status: String,
11    pub additions: Option<usize>,
12    pub deletions: Option<usize>,
13}
14
15#[derive(Serialize)]
16pub struct GitCommitDetails {
17    pub sha: String,
18    pub message: String,
19    pub author: String,
20    pub committer: String,
21    pub author_email: String,
22    pub committer_email: String,
23    pub time: i64,
24    pub parents: Vec<String>,
25    pub files: Vec<CommitFile>,
26    pub additions: usize,
27    pub deletions: usize,
28    pub truncated: bool,
29}
30
31fn oid(sha: &str) -> Result<git2::Oid> {
32    if sha.len() != 40 || !sha.bytes().all(|byte| byte.is_ascii_hexdigit()) {
33        bail!("Invalid full commit ID");
34    }
35    Ok(git2::Oid::from_str(sha)?)
36}
37
38fn trees<'a>(
39    repo: &'a git2::Repository,
40    sha: &str,
41) -> Result<(Option<git2::Tree<'a>>, git2::Tree<'a>)> {
42    let commit = repo.find_commit(oid(sha)?)?;
43    let parent = if commit.parent_count() > 0 {
44        Some(commit.parent(0)?.tree()?)
45    } else {
46        None
47    };
48    Ok((parent, commit.tree()?))
49}
50
51pub fn commit_details(root: &Path, sha: &str, path: Option<&str>) -> Result<GitCommitDetails> {
52    if let Some(path) = path {
53        super::validate_file_path(path)?;
54    }
55    let repo =
56        git2::Repository::open_ext(root, git2::RepositoryOpenFlags::NO_SEARCH, &[] as &[&Path])?;
57    let commit = repo.find_commit(oid(sha)?)?;
58    let (parent, tree) = trees(&repo, sha)?;
59    let mut diff = repo.diff_tree_to_tree(parent.as_ref(), Some(&tree), None)?;
60    diff.find_similar(None)?;
61    let (files, additions, deletions, truncated) = commit_files(&diff, path.map(Path::new))?;
62    let author = commit.author().name().unwrap_or_default().to_owned();
63    let committer = commit.committer().name().unwrap_or_default().to_owned();
64    let author_email = commit.author().email().unwrap_or_default().to_owned();
65    let committer_email = commit.committer().email().unwrap_or_default().to_owned();
66    Ok(GitCommitDetails {
67        sha: commit.id().to_string(),
68        message: commit.message().unwrap_or_default().into(),
69        author,
70        committer,
71        author_email,
72        committer_email,
73        time: commit.time().seconds(),
74        parents: commit.parent_ids().map(|id| id.to_string()).collect(),
75        files,
76        additions,
77        deletions,
78        truncated,
79    })
80}
81
82fn commit_files(
83    diff: &git2::Diff<'_>,
84    scope: Option<&Path>,
85) -> Result<(Vec<CommitFile>, usize, usize, bool)> {
86    const FILE_LIMIT: usize = 1000;
87    let mut additions = 0;
88    let mut deletions = 0;
89    let mut truncated = false;
90    let mut files = Vec::new();
91    for (index, delta) in diff.deltas().enumerate() {
92        if let Some(scope) = scope {
93            if ![delta.old_file().path(), delta.new_file().path()]
94                .into_iter()
95                .flatten()
96                .any(|path| path.starts_with(scope))
97            {
98                continue;
99            }
100        }
101        if files.len() == FILE_LIMIT {
102            truncated = true;
103            if scope.is_none() {
104                break;
105            }
106        }
107        let patch = git2::Patch::from_diff(diff, index)?;
108        let lines = patch
109            .as_ref()
110            .filter(|patch| {
111                let delta = patch.delta();
112                !delta.old_file().is_binary() && !delta.new_file().is_binary()
113            })
114            .map(|patch| patch.line_stats())
115            .transpose()?;
116        if let Some((_, added, deleted)) = lines {
117            additions += added;
118            deletions += deleted;
119        }
120        if truncated {
121            continue;
122        }
123        let path = delta
124            .new_file()
125            .path()
126            .or(delta.old_file().path())
127            .map(|path| path.to_string_lossy().into_owned())
128            .unwrap_or_default();
129        let old_path = delta
130            .old_file()
131            .path()
132            .map(|path| path.to_string_lossy().into_owned())
133            .filter(|old| old != &path);
134        files.push(CommitFile {
135            path,
136            old_path,
137            additions: lines.map(|(_, added, _)| added),
138            deletions: lines.map(|(_, _, deleted)| deleted),
139            status: match delta.status() {
140                git2::Delta::Added => "added",
141                git2::Delta::Deleted => "deleted",
142                git2::Delta::Renamed => "renamed",
143                _ => "modified",
144            }
145            .into(),
146        });
147    }
148    if scope.is_none() {
149        let stats = diff.stats()?;
150        additions = stats.insertions();
151        deletions = stats.deletions();
152    }
153    Ok((files, additions, deletions, truncated))
154}
155
156#[derive(Serialize)]
157pub struct GitCommitFileView {
158    pub content: String,
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub unchanged_text: Option<String>,
161}
162
163fn commit_diff(root: &Path, sha: &str, path: &str) -> Result<GitCommitFileView> {
164    super::validate_file_path(path)?;
165    let repo =
166        git2::Repository::open_ext(root, git2::RepositoryOpenFlags::NO_SEARCH, &[] as &[&Path])?;
167    let (parent, tree) = trees(&repo, sha)?;
168    let mut options = git2::DiffOptions::new();
169    options.context_lines(super::DIFF_CONTEXT_LINES);
170    let mut diff = repo.diff_tree_to_tree(parent.as_ref(), Some(&tree), Some(&mut options))?;
171    diff.find_similar(None)?;
172    let content = super::render_diff_for_path(&diff, Some(path))?;
173    let unchanged_text = match diff
174        .deltas()
175        .find(|delta| super::matches_diff_path(delta, Path::new(path)))
176    {
177        Some(delta) => unchanged_blob_text(&repo, &delta)?,
178        None => None,
179    };
180    Ok(GitCommitFileView {
181        content,
182        unchanged_text,
183    })
184}
185
186fn unchanged_blob_text(
187    repo: &git2::Repository,
188    delta: &git2::DiffDelta<'_>,
189) -> Result<Option<String>> {
190    use git2::FileMode::{Blob, BlobExecutable, BlobGroupWritable};
191
192    let before = delta.old_file();
193    let after = delta.new_file();
194    // Exact renames and executable-bit changes have two versions but no text hunks.
195    if before.id() != after.id()
196        || !matches!(before.mode(), Blob | BlobExecutable | BlobGroupWritable)
197        || !matches!(after.mode(), Blob | BlobExecutable | BlobGroupWritable)
198        || delta.flags().contains(git2::DiffFlags::BINARY)
199    {
200        return Ok(None);
201    }
202    let blob = repo.find_blob(after.id())?;
203    if blob.size() > super::MAX_DIFF_BYTES || blob.is_binary() {
204        return Ok(None);
205    }
206    Ok(std::str::from_utf8(blob.content()).ok().map(str::to_owned))
207}
208
209/// Read an immutable file or compare its committed tree with the current checkout.
210pub fn commit_file_view(
211    root: &Path,
212    sha: &str,
213    path: &str,
214    view: Option<&str>,
215) -> Result<GitCommitFileView> {
216    if view.is_none() {
217        return commit_diff(root, sha, path);
218    }
219    super::validate_file_path(path)?;
220    let repo =
221        git2::Repository::open_ext(root, git2::RepositoryOpenFlags::NO_SEARCH, &[] as &[&Path])?;
222    let tree = repo.find_commit(oid(sha)?)?.tree()?;
223    let content = match view {
224        Some("revision") => {
225            let entry = tree.get_path(Path::new(path))?;
226            let blob = repo.find_blob(entry.id())?;
227            if blob.size() > 2 * 1024 * 1024 {
228                bail!("File exceeds the preview limit");
229            }
230            if blob.is_binary() {
231                bail!("Binary files cannot be previewed as text");
232            }
233            std::str::from_utf8(blob.content())?.to_owned()
234        }
235        Some("working") => {
236            let mut options = git2::DiffOptions::new();
237            options
238                .context_lines(super::DIFF_CONTEXT_LINES)
239                .include_untracked(true)
240                .show_untracked_content(true);
241            let diff = repo.diff_tree_to_workdir_with_index(Some(&tree), Some(&mut options))?;
242            super::render_diff_for_path(&diff, Some(path))?
243        }
244        _ => bail!("Unsupported commit file view"),
245    };
246    Ok(GitCommitFileView {
247        content,
248        unchanged_text: None,
249    })
250}
251
252#[derive(Serialize)]
253pub struct GitHistoryPage {
254    pub commits: Vec<super::GitCommit>,
255    pub has_more: bool,
256}
257
258/// Browse the immutable history reachable from a selected commit, ten rows at a time.
259pub fn commit_history(root: &Path, sha: &str, offset: usize) -> Result<GitHistoryPage> {
260    if offset > 100_000 {
261        bail!("History offset exceeds the preview limit");
262    }
263    let repo =
264        git2::Repository::open_ext(root, git2::RepositoryOpenFlags::NO_SEARCH, &[] as &[&Path])?;
265    let commit = repo.find_commit(oid(sha)?)?;
266    let walk = super::history_walk(&repo, commit.id())?;
267    let mut commits = Vec::new();
268    for id in walk.skip(offset).take(11) {
269        commits.push(super::summarize_commit(&repo.find_commit(id?)?));
270    }
271    let has_more = commits.len() > 10;
272    commits.truncate(10);
273    Ok(GitHistoryPage { commits, has_more })
274}
275
276#[cfg(test)]
277mod tests;