Skip to main content

gitpoulpi_cli_backend/
refs.rs

1use std::collections::BTreeMap;
2
3use gitpoulpi_core::domain::{
4    parse_remote_tag_mirror_ref, split_remote_ref, Oid, Ref, RefKind, RefVisibility, RepoRef,
5    TagSync, REMOTE_TAG_MIRROR_PREFIX,
6};
7use gitpoulpi_core::{Error, Result};
8
9use crate::process::{read_with_retry, run, run_bytes_with_stdin};
10
11pub fn refs(repo: &RepoRef) -> Result<Vec<Ref>> {
12    // `symbolic-ref` fails (non-zero exit -> Err here) on a detached HEAD
13    // or an unborn branch -- both cases correctly leave `head_branch` as
14    // None, so no ref gets marked is_head, matching Git2Backend's
15    // `head().ok().filter(is_branch)` behavior for the same states.
16    let head_branch: Option<String> = run(&repo.root, &["symbolic-ref", "--short", "HEAD"])
17        .ok()
18        .map(|s| s.trim().to_string());
19
20    // The remote list is read *before* the refs so `refs/remotes/<rest>`
21    // can be split against the remotes that exist rather than on the first
22    // `/` -- see `split_remote_ref`.
23    let remote_names: Vec<String> = run(&repo.root, &["remote"])
24        .map(|raw| {
25            raw.lines()
26                .map(str::trim)
27                .filter(|l| !l.is_empty())
28                .map(str::to_string)
29                .collect()
30        })
31        .unwrap_or_default();
32
33    // No `%(*objectname)`: git 2.5x aborts (SIGABRT, a double free) on a ref
34    // whose object is missing, which a repository being deleted or
35    // half-written shows for a moment. Tags are peeled below instead.
36    let raw = read_with_retry(|| {
37        run(
38            &repo.root,
39            &[
40                "for-each-ref",
41                // `%(upstream:short)` is already spelled the way
42                // `RefKind::RemoteBranch` spells a remote branch
43                // (`origin/feature/login`), and empty for untracked refs.
44                "--format=%(refname)\u{1}%(objectname)\u{1}%(upstream:short)",
45                "refs/heads",
46                "refs/remotes",
47                "refs/tags",
48                // GitPoulpi's own remote-tag mirror, walked in the same
49                // `for-each-ref` rather than a second spawn. These rows never
50                // become `Ref`s; they only fill in each tag's `tag_sync`.
51                REMOTE_TAG_MIRROR_PREFIX,
52            ],
53        )
54    })?;
55
56    let rows: Vec<(&str, Oid, &str)> = raw
57        .lines()
58        .filter_map(|line| {
59            let mut parts = line.splitn(3, '\u{1}');
60            let (refname, objectname) = (parts.next()?, parts.next()?);
61            let upstream = parts.next().unwrap_or("").trim();
62            Some((refname, Oid::from_hex(objectname.trim())?, upstream))
63        })
64        .collect();
65    let peeled = peel_tags(repo, &rows)?;
66
67    // tag name -> the commits the remotes are known to have it at.
68    let mut mirror: BTreeMap<String, Vec<(String, Oid)>> = BTreeMap::new();
69    let mut refs: Vec<Ref> = Vec::new();
70
71    for (refname, listed, upstream) in rows {
72        let target = peeled.get(&listed).copied().unwrap_or(listed);
73
74        if let Some((remote, tag)) = parse_remote_tag_mirror_ref(refname, &remote_names) {
75            // A mirror whose remote is gone (removed outside GitPoulpi) is
76            // stale: skipped, so no tag reads as on a remote that is not there.
77            if remote_names.contains(&remote) {
78                mirror
79                    .entry(tag.to_string())
80                    .or_default()
81                    .push((remote, target));
82            }
83            continue;
84        }
85        let Some(kind) = parse_ref_kind(refname, &remote_names) else {
86            continue;
87        };
88        let is_head = matches!(&kind, RefKind::LocalBranch { name } if Some(name.as_str()) == head_branch.as_deref());
89        // Only a local branch can track anything; git leaves the field
90        // empty for the rest, but pinning it here means a future format
91        // change cannot invent one.
92        let upstream = match (&kind, upstream.is_empty()) {
93            (RefKind::LocalBranch { .. }, false) => Some(upstream.to_string()),
94            _ => None,
95        };
96        refs.push(Ref {
97            kind,
98            target,
99            visibility: RefVisibility::Shown,
100            is_head,
101            upstream,
102            tag_sync: None,
103            multi_remote: None,
104        });
105    }
106
107    apply_tag_sync(&mut refs, &mirror);
108
109    Ok(refs)
110}
111
112/// The commit each annotated tag row (a tag or a mirror of one) points at,
113/// keyed by the row's own object id. One `cat-file --batch-check` for all of
114/// them, and only when there is a tag row. An object that is missing, or
115/// that peels to something other than a commit, is left out: the row keeps
116/// its own id, as `Git2Backend` does.
117fn peel_tags(
118    repo: &RepoRef,
119    rows: &[(&str, Oid, &str)],
120) -> Result<std::collections::HashMap<Oid, Oid>> {
121    let mut ids: Vec<Oid> = rows
122        .iter()
123        .filter(|(name, _, _)| {
124            name.starts_with("refs/tags/") || name.starts_with(REMOTE_TAG_MIRROR_PREFIX)
125        })
126        .map(|(_, id, _)| *id)
127        .collect();
128    ids.sort_by_key(|id| id.0);
129    ids.dedup();
130    peel_commits(&repo.root, &ids)
131}
132
133/// What `cat-file` says about one object: its own type (`missing` for an
134/// object that is gone) and the commit it peels to (through any number of
135/// tags), when it does.
136pub(crate) struct Peel {
137    pub(crate) kind: String,
138    pub(crate) commit: Option<Oid>,
139}
140
141/// `ids` described by one `cat-file --batch-check` (`<id>` and `<id>^{}` per
142/// id; no spawn for an empty list), keyed by the id asked for. Used instead
143/// of `%(*objectname)` / `%(objecttype)` in a `for-each-ref` format: git 2.5x
144/// aborts (or exits 128) on a ref to a missing object.
145pub(crate) fn peel_info(
146    root: &std::path::Path,
147    ids: &[Oid],
148) -> Result<std::collections::HashMap<Oid, Peel>> {
149    let mut info = std::collections::HashMap::new();
150    if ids.is_empty() {
151        return Ok(info);
152    }
153    let mut stdin = String::new();
154    for id in ids {
155        stdin.push_str(&format!("{id}\n{id}^{{}}\n"));
156    }
157    let answer = read_with_retry(|| {
158        run_bytes_with_stdin(
159            root,
160            &["cat-file", "--batch-check=%(objectname) %(objecttype)"],
161            stdin.as_bytes(),
162        )
163    })?;
164    // Two answer lines per id, in order. A missing object answers
165    // `<input> missing`, so the type is whatever follows the last space.
166    let text = String::from_utf8_lossy(&answer);
167    let mut lines = text.lines();
168    for id in ids {
169        let (Some(own), Some(peeled)) = (lines.next(), lines.next()) else {
170            break;
171        };
172        let kind = own.rsplit_once(' ').map_or("missing", |(_, kind)| kind);
173        let commit = peeled.strip_suffix(" commit").and_then(Oid::from_hex);
174        info.insert(
175            *id,
176            Peel {
177                kind: kind.to_string(),
178                commit,
179            },
180        );
181    }
182    Ok(info)
183}
184
185/// The commit each of `ids` peels to, keyed by the id asked for. An id whose
186/// object is missing, or that peels to something other than a commit, is
187/// left out.
188pub(crate) fn peel_commits(
189    root: &std::path::Path,
190    ids: &[Oid],
191) -> Result<std::collections::HashMap<Oid, Oid>> {
192    Ok(peel_info(root, ids)?
193        .into_iter()
194        .filter_map(|(id, p)| Some((id, p.commit?)))
195        .collect())
196}
197
198/// Which remotes hold `name`, split by whether they hold it **at this
199/// commit**; `local` says whether the tag exists here at all.
200///
201/// A remote holding the tag at a *different* commit would only accept a
202/// `--force` push, so reporting it as "pushed" would hide a divergence: it
203/// goes to `differs_on` instead.
204///
205/// Shared verbatim with `Git2Backend`: the one place the rule lives.
206pub fn tag_sync_for(
207    name: &str,
208    target: Oid,
209    mirror: &BTreeMap<String, Vec<(String, Oid)>>,
210) -> TagSync {
211    let mut pushed_to = Vec::new();
212    let mut differs_on = Vec::new();
213    for (remote, oid) in mirror.get(name).map(Vec::as_slice).unwrap_or_default() {
214        if *oid == target {
215            pushed_to.push(remote.clone());
216        } else {
217            differs_on.push(remote.clone());
218        }
219    }
220    pushed_to.sort();
221    pushed_to.dedup();
222    differs_on.sort();
223    differs_on.dedup();
224    TagSync {
225        pushed_to,
226        differs_on,
227        local: true,
228    }
229}
230
231/// Fills in every tag's `tag_sync` and appends one **remote-only** row per
232/// mirrored tag name that has no `refs/tags/<name>` here.
233///
234/// A remote-only row is a `RefKind::Tag` whose `tag_sync.local` is false
235/// and whose target is the commit of the first remote (in name order)
236/// that has it; remotes that disagree with that one land in `differs_on`.
237/// One function for both backends, so they cannot disagree about it.
238pub fn apply_tag_sync(refs: &mut Vec<Ref>, mirror: &BTreeMap<String, Vec<(String, Oid)>>) {
239    let mut local: std::collections::BTreeSet<String> = Default::default();
240    for r in refs.iter_mut() {
241        if let RefKind::Tag { name } = &r.kind {
242            local.insert(name.clone());
243            r.tag_sync = Some(tag_sync_for(name, r.target, mirror));
244        }
245    }
246    for (name, entries) in mirror {
247        if local.contains(name) {
248            continue;
249        }
250        let Some(first) = entries.iter().min_by(|a, b| a.0.cmp(&b.0)) else {
251            continue;
252        };
253        let mut sync = tag_sync_for(name, first.1, mirror);
254        sync.local = false;
255        refs.push(Ref {
256            kind: RefKind::Tag { name: name.clone() },
257            target: first.1,
258            visibility: RefVisibility::Shown,
259            is_head: false,
260            upstream: None,
261            tag_sync: Some(sync),
262            multi_remote: None,
263        });
264    }
265}
266
267/// See `GitBackend::resolve`.
268///
269/// Two details are load-bearing. `^{commit}` makes git peel whatever the
270/// revision names down to a commit, so an annotated tag yields the commit
271/// it tags rather than the tag object's own oid. `--end-of-options` stops
272/// a revision that happens to start with a dash (a branch literally named
273/// `-x`, or a typo) from being parsed as a flag by this very command.
274pub fn resolve(repo: &RepoRef, rev: &str) -> Result<Oid> {
275    let spec = format!("{rev}^{{commit}}");
276    let raw = run(
277        &repo.root,
278        &["rev-parse", "--verify", "--end-of-options", &spec],
279    )?;
280    Oid::from_hex(raw.trim())
281        .ok_or_else(|| Error::Backend(format!("`{rev}` did not resolve to a commit")))
282}
283
284fn parse_ref_kind(refname: &str, remote_names: &[String]) -> Option<RefKind> {
285    if let Some(name) = refname.strip_prefix("refs/heads/") {
286        return Some(RefKind::LocalBranch {
287            name: name.to_string(),
288        });
289    }
290    if let Some(rest) = refname.strip_prefix("refs/remotes/") {
291        let (remote, name) = split_remote_ref(rest, remote_names)?;
292        return Some(RefKind::RemoteBranch {
293            remote,
294            name: name.to_string(),
295        });
296    }
297    if let Some(name) = refname.strip_prefix("refs/tags/") {
298        return Some(RefKind::Tag {
299            name: name.to_string(),
300        });
301    }
302    None
303}
304
305/// See `GitBackend::merge_base`. `git merge-base` exits 1 with no output
306/// when the commits share no history.
307pub fn merge_base(repo: &RepoRef, a: Oid, b: Oid) -> Result<Option<Oid>> {
308    match run(&repo.root, &["merge-base", &a.to_hex(), &b.to_hex()]) {
309        Ok(raw) => Ok(Oid::from_hex(raw.trim())),
310        Err(_) => {
311            // Distinguish "unrelated" from a real failure by asking again
312            // whether both commits exist.
313            run(
314                &repo.root,
315                &["cat-file", "-e", &format!("{}^{{commit}}", a.to_hex())],
316            )?;
317            run(
318                &repo.root,
319                &["cat-file", "-e", &format!("{}^{{commit}}", b.to_hex())],
320            )?;
321            Ok(None)
322        }
323    }
324}
325
326/// See `GitBackend::ahead_behind`.
327pub fn cherry_counts(repo: &RepoRef, local: Oid, remote: Oid) -> Result<(u32, u32)> {
328    let range = format!("{}...{}", local.to_hex(), remote.to_hex());
329    let raw = run(
330        &repo.root,
331        &[
332            "rev-list",
333            "--cherry-pick",
334            "--left-right",
335            "--count",
336            &range,
337        ],
338    )?;
339    let mut counts = raw.split_whitespace().map(|n| n.parse::<u32>());
340    match (counts.next(), counts.next()) {
341        (Some(Ok(l)), Some(Ok(r))) => Ok((l, r)),
342        _ => Err(Error::Backend(format!(
343            "unexpected `rev-list --count` output: {raw:?}"
344        ))),
345    }
346}
347
348pub fn ahead_behind(repo: &RepoRef, tip: Oid, base: Oid) -> Result<(u32, u32)> {
349    let range = format!("{}...{}", tip.to_hex(), base.to_hex());
350    let raw = run(&repo.root, &["rev-list", "--left-right", "--count", &range])?;
351    let mut counts = raw.split_whitespace().map(|n| n.parse::<u32>());
352    match (counts.next(), counts.next()) {
353        (Some(Ok(ahead)), Some(Ok(behind))) => Ok((ahead, behind)),
354        _ => Err(Error::Backend(format!(
355            "unexpected `rev-list --count` output: {raw:?}"
356        ))),
357    }
358}