Skip to main content

agent_hub_runtime/core/project_git/
graph.rs

1//! Topologically ordered history across local and optionally cached remote branches.
2use anyhow::Result;
3use serde::Serialize;
4use std::{
5    collections::HashMap,
6    io::{Seek, Write},
7    path::Path,
8};
9
10#[derive(Serialize)]
11pub struct GraphReference {
12    pub name: String,
13    pub remote: bool,
14    pub kind: &'static str,
15    pub remote_name: Option<String>,
16    pub current: bool,
17}
18#[derive(Serialize)]
19pub struct GraphCommit {
20    #[serde(flatten)]
21    pub commit: super::GitCommit,
22    pub parents: Vec<String>,
23    pub refs: Vec<GraphReference>,
24    pub head: bool,
25}
26#[derive(Serialize)]
27pub struct GraphBranch {
28    pub name: String,
29    pub remote: bool,
30    pub sha: String,
31}
32
33#[derive(Serialize)]
34pub struct GitGraph {
35    pub commits: Vec<GraphCommit>,
36    pub has_more: bool,
37    pub branches: Vec<GraphBranch>,
38}
39
40#[cfg(test)]
41fn graph(root: &Path, include_remotes: bool, limit: usize) -> Result<GitGraph> {
42    graph_for_branch(root, include_remotes, limit, None)
43}
44
45pub fn graph_for_branch(
46    root: &Path,
47    include_remotes: bool,
48    limit: usize,
49    branch: Option<&str>,
50) -> Result<GitGraph> {
51    graph_for_path(root, include_remotes, limit, branch, None)
52}
53
54/// Use the same references and commit metadata for the graph of a literal repository path.
55pub fn graph_for_path(
56    root: &Path,
57    include_remotes: bool,
58    limit: usize,
59    branch: Option<&str>,
60    path: Option<&str>,
61) -> Result<GitGraph> {
62    if let Some(path) = path {
63        super::validate_file_path(path)?;
64    }
65    let repo =
66        git2::Repository::open_ext(root, git2::RepositoryOpenFlags::NO_SEARCH, &[] as &[&Path])?;
67    let mut walk = repo.revwalk()?;
68    walk.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::TIME)?;
69    let mut refs: HashMap<git2::Oid, Vec<GraphReference>> = HashMap::new();
70    let mut branches = Vec::new();
71    let head = repo.head().ok();
72    let head_id = head.as_ref().and_then(|head| head.target());
73    let remote_names = repo.remotes()?;
74    for reference in repo.references()? {
75        let reference = reference?;
76        if !(reference.is_branch()
77            || reference.is_tag()
78            || (include_remotes && reference.is_remote()))
79        {
80            continue;
81        }
82        let Ok(commit) = reference.peel_to_commit() else {
83            continue;
84        };
85        walk.push(commit.id())?;
86        let name = reference.shorthand().unwrap_or_default();
87        if !reference.is_tag() && reference.symbolic_target().is_none() {
88            branches.push(GraphBranch {
89                name: name.into(),
90                remote: reference.is_remote(),
91                sha: commit.id().to_string(),
92            });
93        }
94        let remote_name = if reference.is_remote() {
95            remote_names
96                .iter()
97                .flatten()
98                .filter(|remote| {
99                    name.strip_prefix(remote)
100                        .is_some_and(|suffix| suffix.starts_with('/'))
101                })
102                .max_by_key(|remote| remote.len())
103                .map(str::to_owned)
104        } else {
105            None
106        };
107        refs.entry(commit.id()).or_default().push(GraphReference {
108            name: name.into(),
109            remote: reference.is_remote(),
110            kind: if reference.is_tag() {
111                "tag"
112            } else if reference.is_remote() {
113                "remote"
114            } else {
115                "branch"
116            },
117            remote_name,
118            current: reference.is_branch()
119                && head.as_ref().and_then(|head| head.name()) == reference.name(),
120        });
121    }
122    // Detached HEAD must remain visible even when no reference points to it.
123    if let Ok(head) = repo.head().and_then(|head| head.peel_to_commit()) {
124        walk.push(head.id())?;
125    }
126    let mut selected_tip = None;
127    if let Some(branch) = branch {
128        // Accept only a branch tip from this repository's visible references.
129        let selected = branches
130            .iter()
131            .find(|candidate| {
132                let prefix = if candidate.remote {
133                    "refs/remotes/"
134                } else {
135                    "refs/heads/"
136                };
137                branch.strip_prefix(prefix) == Some(candidate.name.as_str())
138            })
139            .ok_or_else(|| anyhow::anyhow!("Selected branch is no longer available"))?;
140        let tip = git2::Oid::from_str(&selected.sha)?;
141        selected_tip = Some(tip);
142        walk.reset()?;
143        walk.push(tip)?;
144    }
145    let limit = limit.clamp(100, 5000);
146    let rows = path
147        .map(|path| {
148            let mut tips = match selected_tip {
149                Some(tip) => vec![tip],
150                None => refs.keys().copied().chain(head_id).collect::<Vec<_>>(),
151            };
152            tips.sort_unstable();
153            tips.dedup();
154            path_rows(root, path, limit + 1, &tips)
155        })
156        .transpose()?;
157    let rows: Box<dyn Iterator<Item = Result<_>>> = match rows {
158        Some(rows) => Box::new(
159            rows.into_iter()
160                .map(|(id, parents)| Ok((id, Some(parents)))),
161        ),
162        None => Box::new(walk.take(limit + 1).map(|id| Ok((id?, None)))),
163    };
164    let mut commits = Vec::new();
165    let mut add_commit = |id, parents: Option<Vec<String>>| -> Result<()> {
166        let commit = repo.find_commit(id)?;
167        let mut labels = refs.remove(&id).unwrap_or_default();
168        labels.sort_by(|a, b| a.name.cmp(&b.name));
169        commits.push(GraphCommit {
170            commit: super::summarize_commit(&commit),
171            parents: parents
172                .unwrap_or_else(|| commit.parent_ids().map(|id| id.to_string()).collect()),
173            refs: labels,
174            head: head_id == Some(id),
175        });
176        Ok(())
177    };
178    for row in rows {
179        let (id, parents) = row?;
180        add_commit(id, parents)?;
181    }
182    let has_more = commits.len() > limit;
183    commits.truncate(limit);
184    Ok(GitGraph {
185        commits,
186        has_more,
187        branches,
188    })
189}
190
191// Parent rewriting connects the visible changes across commits that did not touch this path.
192fn path_rows(
193    root: &Path,
194    path: &str,
195    limit: usize,
196    tips: &[git2::Oid],
197) -> Result<Vec<(git2::Oid, Vec<String>)>> {
198    if tips.is_empty() {
199        return Ok(Vec::new());
200    }
201    let mut input = tempfile::tempfile()?;
202    for tip in tips {
203        writeln!(input, "{tip}")?;
204    }
205    input.rewind()?;
206    let mut command = super::actions::git_command(root);
207    command
208        .env("GIT_NO_LAZY_FETCH", "1")
209        .env("GIT_NO_REPLACE_OBJECTS", "1")
210        .args([
211            "rev-list",
212            "--stdin",
213            "--topo-order",
214            "--parents",
215            "--full-history",
216            "--simplify-merges",
217        ])
218        .arg(format!("--max-count={limit}"))
219        .args(["--", path]);
220    let (output, _) = super::super::cli_process::capture_prepared_with_input(
221        command,
222        "git",
223        30,
224        None,
225        Some(input),
226    )
227    .map_err(anyhow::Error::msg)?;
228    output
229        .lines()
230        .map(|line| {
231            let mut fields = line.split_whitespace();
232            let id = git2::Oid::from_str(fields.next().unwrap_or_default())?;
233            Ok((id, fields.map(str::to_owned).collect()))
234        })
235        .collect()
236}
237
238#[cfg(test)]
239mod tests;