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 let head_branch: Option<String> = run(&repo.root, &["symbolic-ref", "--short", "HEAD"])
17 .ok()
18 .map(|s| s.trim().to_string());
19
20 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 let raw = read_with_retry(|| {
37 run(
38 &repo.root,
39 &[
40 "for-each-ref",
41 "--format=%(refname)\u{1}%(objectname)\u{1}%(upstream:short)",
45 "refs/heads",
46 "refs/remotes",
47 "refs/tags",
48 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 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 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 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
112fn 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
133pub(crate) struct Peel {
137 pub(crate) kind: String,
138 pub(crate) commit: Option<Oid>,
139}
140
141pub(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 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
185pub(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
198pub 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
231pub 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
267pub 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
305pub 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 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
326pub 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}