1use std::collections::BTreeMap;
6
7use gitpoulpi_core::domain::{
8 HeadState, Oid, RefScope, RefSnapshot, RefUpdate, RepoRef, UndoRefusal,
9};
10use gitpoulpi_core::{Error, Result};
11
12use crate::process::{run, run_bytes, run_lenient, run_with_stdin};
13
14pub fn ref_snapshot(repo: &RepoRef, scope: &RefScope) -> Result<RefSnapshot> {
18 let mut args: Vec<&str> = vec![
19 "for-each-ref",
20 "--format=%(HEAD)%00%(refname)%00%(objectname)%00%(symref)",
21 ];
22 let patterns: Vec<&str> = scope
23 .prefixes
24 .iter()
25 .map(|p| p.trim_end_matches('/'))
26 .collect();
27 args.extend(patterns.iter().copied());
28 let raw = run(&repo.root, &args)?;
29 let mut refs = BTreeMap::new();
30 let mut symrefs = BTreeMap::new();
31 let mut head = None;
32 for line in raw.lines().filter(|l| !l.is_empty()) {
33 let mut parts = line.splitn(4, '\0');
34 let (Some(marker), Some(name), Some(oid)) = (parts.next(), parts.next(), parts.next())
35 else {
36 continue;
37 };
38 if let Some(target) = parts.next().map(str::trim).filter(|t| !t.is_empty()) {
39 symrefs.insert(name.to_string(), target.to_string());
40 }
41 let Some(oid) = Oid::from_hex(oid.trim()) else {
42 continue;
43 };
44 if marker == "*" {
45 if let Some(branch) = name.strip_prefix("refs/heads/") {
46 head = Some(HeadState::Branch(branch.to_string()));
47 }
48 }
49 refs.insert(name.to_string(), oid);
50 }
51 let head = match head {
52 Some(head) => head,
53 None => current_head(repo)?,
54 };
55 Ok(RefSnapshot {
56 head,
57 refs,
58 symrefs,
59 })
60}
61
62fn current_head(repo: &RepoRef) -> Result<HeadState> {
64 let (symbolic, target) = run_lenient(&repo.root, &["symbolic-ref", "-q", "HEAD"])?;
65 if symbolic {
66 let target = target.trim();
67 return Ok(HeadState::Branch(
68 target
69 .strip_prefix("refs/heads/")
70 .unwrap_or(target)
71 .to_string(),
72 ));
73 }
74 let raw = run(&repo.root, &["rev-parse", "--verify", "HEAD"])?;
75 Oid::from_hex(raw.trim())
76 .map(HeadState::Detached)
77 .ok_or_else(|| Error::Backend("HEAD did not resolve to a commit".into()))
78}
79
80fn ref_value(repo: &RepoRef, name: &str) -> Option<Oid> {
81 let (ok, out) = run_lenient(&repo.root, &["rev-parse", "--verify", "-q", name]).ok()?;
82 if !ok {
83 return None;
84 }
85 Oid::from_hex(out.trim())
86}
87
88pub fn update_refs(repo: &RepoRef, updates: &[RefUpdate], reflog_message: &str) -> Result<()> {
92 if write_pins_directly(repo, updates) || delete_pins_directly(repo, updates) {
96 return Ok(());
97 }
98 let mut head_moves: Vec<(&HeadState, &HeadState)> = Vec::new();
100 let mut symbolic: Vec<(&String, &Option<String>)> = Vec::new();
101 let mut input = String::from("start\0");
102 let mut any_ref = false;
103 for update in updates {
104 match update {
105 RefUpdate::SetHead { old, new } => {
106 let actual = current_head(repo)?;
107 if &actual != old {
108 return Err(Error::UndoRefused(UndoRefusal::HeadMoved {
109 expected: old.clone(),
110 actual,
111 }));
112 }
113 match (old, new) {
114 (HeadState::Detached(o), HeadState::Detached(n)) => {
116 input.push_str(&format!("update HEAD\0{n}\0{o}\0"));
117 any_ref = true;
118 }
119 _ => head_moves.push((old, new)),
120 }
121 }
122 RefUpdate::SetSymbolic { name, new, .. } => symbolic.push((name, new)),
123 RefUpdate::Create { name, new } => {
124 input.push_str(&format!("create {name}\0{new}\0"));
125 any_ref = true;
126 }
127 RefUpdate::Update { name, old, new } => {
128 input.push_str(&format!("update {name}\0{new}\0{old}\0"));
129 any_ref = true;
130 }
131 RefUpdate::Delete { name, old } => {
132 input.push_str(&format!("delete {name}\0{old}\0"));
133 any_ref = true;
134 }
135 RefUpdate::Verify { name, old } => {
136 input.push_str(&format!("verify {name}\0{old}\0"));
137 any_ref = true;
138 }
139 }
140 }
141 if any_ref {
142 input.push_str("prepare\0commit\0");
143 let result = run_with_stdin(
144 &repo.root,
145 &[
146 "update-ref",
147 "--no-deref",
148 "-m",
149 reflog_message,
150 "--stdin",
151 "-z",
152 ],
153 &input,
154 );
155 if let Err(e) = result {
156 return Err(explain_failure(repo, updates, e));
157 }
158 }
159 for (name, target) in symbolic {
160 match target {
161 Some(target) => {
162 run(
163 &repo.root,
164 &["symbolic-ref", "-m", reflog_message, name, target],
165 )?;
166 }
167 None => {
168 run_lenient(&repo.root, &["symbolic-ref", "--delete", "-q", name])?;
169 }
170 }
171 }
172 for (_, new) in head_moves {
173 match new {
174 HeadState::Branch(name) => {
175 run(
176 &repo.root,
177 &[
178 "symbolic-ref",
179 "-m",
180 reflog_message,
181 "HEAD",
182 &format!("refs/heads/{name}"),
183 ],
184 )?;
185 }
186 HeadState::Detached(oid) => {
187 run(
188 &repo.root,
189 &[
190 "update-ref",
191 "--no-deref",
192 "-m",
193 reflog_message,
194 "HEAD",
195 &oid.to_hex(),
196 ],
197 )?;
198 }
199 }
200 }
201 Ok(())
202}
203
204fn explain_failure(repo: &RepoRef, updates: &[RefUpdate], original: Error) -> Error {
207 for update in updates {
208 let (name, expected) = match update {
209 RefUpdate::Create { name, .. } => (name, None),
210 RefUpdate::Update { name, old, .. }
211 | RefUpdate::Delete { name, old }
212 | RefUpdate::Verify { name, old } => (name, Some(*old)),
213 RefUpdate::SetHead { .. } | RefUpdate::SetSymbolic { .. } => continue,
214 };
215 let actual = ref_value(repo, name);
216 if actual != expected {
217 return Error::UndoRefused(UndoRefusal::RefMoved {
218 name: name.clone(),
219 expected,
220 actual,
221 restore: None,
222 });
223 }
224 }
225 original
226}
227
228pub fn move_head_keep(repo: &RepoRef, branch: &str, from: Oid, to: Oid) -> Result<()> {
232 let expected = HeadState::Branch(branch.to_string());
233 let actual = current_head(repo)?;
234 if actual != expected {
235 return Err(Error::UndoRefused(UndoRefusal::HeadMoved {
236 expected,
237 actual,
238 }));
239 }
240 let name = format!("refs/heads/{branch}");
241 let tip = ref_value(repo, &name);
242 if tip != Some(from) {
243 return Err(Error::UndoRefused(UndoRefusal::RefMoved {
244 name,
245 expected: Some(from),
246 actual: tip,
247 restore: None,
248 }));
249 }
250 release_submodules(repo, from, to)?;
251 run(&repo.root, &["reset", "--keep", "--quiet", &to.to_hex()]).map_err(|e| {
252 Error::UndoRefused(UndoRefusal::WouldOverwrite {
253 detail: e.to_string(),
254 })
255 })?;
256 Ok(())
257}
258
259fn release_submodules(repo: &RepoRef, from: Oid, to: Oid) -> Result<()> {
264 let raw = run_bytes(
265 &repo.root,
266 &[
267 "diff-tree",
268 "-r",
269 "-z",
270 "--no-renames",
271 "--raw",
272 &from.to_hex(),
273 &to.to_hex(),
274 ],
275 )?;
276 let mut fields = raw.split(|b| *b == 0);
277 let mut gone: Vec<String> = Vec::new();
278 while let Some(meta) = fields.next() {
279 if meta.is_empty() {
280 continue;
281 }
282 let Some(path) = fields.next() else { break };
283 let meta = String::from_utf8_lossy(meta);
284 let mut parts = meta.trim_start_matches(':').split(' ');
285 let (old_mode, new_mode) = (parts.next(), parts.next());
286 if old_mode == Some("160000") && new_mode != Some("160000") {
287 gone.push(String::from_utf8_lossy(path).into_owned());
288 }
289 }
290 for path in gone {
291 let dir = repo.root.join(&path);
292 if !dir.join(".git").exists() {
293 continue;
294 }
295 let dirty = run(&dir, &["status", "--porcelain"])?;
296 if !dirty.trim().is_empty() {
297 return Err(Error::UndoRefused(UndoRefusal::WouldOverwrite {
298 detail: format!("{path} is a submodule with local changes"),
299 }));
300 }
301 run(
302 &repo.root,
303 &["submodule", "deinit", "--force", "--quiet", "--", &path],
304 )
305 .map_err(|e| {
306 Error::UndoRefused(UndoRefusal::WouldOverwrite {
307 detail: e.to_string(),
308 })
309 })?;
310 }
311 Ok(())
312}
313
314pub fn check_section(section: &str) -> Result<()> {
317 if is_key_section(section) {
321 return Ok(());
322 }
323 match section
324 .strip_prefix("branch.")
325 .or_else(|| section.strip_prefix("remote."))
326 {
327 Some(name) if !name.is_empty() => Ok(()),
328 _ => Err(Error::Backend(format!(
329 "only `branch.<name>` and `remote.<name>` config sections can be read or \
330 restored, not `{section}`"
331 ))),
332 }
333}
334
335pub(crate) fn local_entries(repo: &RepoRef) -> Result<Vec<(String, String)>> {
337 let (_, raw) = run_lenient(&repo.root, &["config", "--local", "--list", "-z"])?;
338 Ok(raw
339 .split('\0')
340 .filter(|entry| !entry.is_empty())
341 .map(|entry| {
342 let (key, value) = entry.split_once('\n').unwrap_or((entry, ""));
343 (key.to_string(), value.to_string())
344 })
345 .collect())
346}
347
348pub fn config_sections(
350 repo: &RepoRef,
351 sections: &[String],
352) -> Result<Vec<gitpoulpi_core::backend::ConfigSection>> {
353 for section in sections {
354 check_section(section)?;
355 }
356 if sections.is_empty() {
357 return Ok(Vec::new());
358 }
359 let all = local_entries(repo)?;
360 Ok(sections
361 .iter()
362 .map(|section| {
363 let entries = all
364 .iter()
365 .filter(|(key, _)| in_section(section, key))
366 .cloned()
367 .collect();
368 (section.clone(), entries)
369 })
370 .collect())
371}
372
373pub fn remote_dependents(repo: &RepoRef, remote: &str) -> Result<Vec<String>> {
375 Ok(dependents_in(&local_entries(repo)?, remote))
376}
377
378pub fn dependents_in(entries: &[(String, String)], remote: &str) -> Vec<String> {
380 let mut out: Vec<String> = entries
383 .iter()
384 .filter_map(|(key, value)| {
385 if key.starts_with("branch.") && key.ends_with(".remote") && value == remote {
386 Some(key[..key.len() - ".remote".len()].to_string())
387 } else if gitpoulpi_core::domain::is_remote_group_key(key)
388 && gitpoulpi_core::domain::value_remote(value) == remote
389 {
390 key.rsplit_once('.').map(|(section, _)| section.to_string())
391 } else {
392 None
393 }
394 })
395 .collect();
396 out.sort();
397 out.dedup();
398 out
399}
400
401pub fn in_section(section: &str, key: &str) -> bool {
404 if is_key_section(section) {
405 return key.eq_ignore_ascii_case(section);
406 }
407 key.strip_prefix(section)
408 .and_then(|rest| rest.strip_prefix('.'))
409 .is_some_and(|variable| !variable.is_empty() && !variable.contains('.'))
410}
411
412pub fn is_key_section(section: &str) -> bool {
414 gitpoulpi_core::repo_config::REPO_CONFIG_KEYS
415 .iter()
416 .any(|(k, _)| *k == section)
417}
418
419pub fn config_section(repo: &RepoRef, section: &str) -> Result<Vec<(String, String)>> {
420 check_section(section)?;
421 Ok(local_entries(repo)?
422 .into_iter()
423 .filter(|(key, _)| in_section(section, key))
424 .collect())
425}
426
427pub fn set_config_section(
428 repo: &RepoRef,
429 section: &str,
430 entries: &[(String, String)],
431) -> Result<()> {
432 check_section(section)?;
433 if let Some((key, _)) = entries.iter().find(|(key, _)| !in_section(section, key)) {
434 return Err(Error::Backend(format!(
435 "`{key}` is not a variable of `{section}`"
436 )));
437 }
438 if is_key_section(section) {
439 for (key, value) in entries {
440 gitpoulpi_core::repo_config::check_repo_config_value(key, value)?;
441 }
442 if !config_section(repo, section)?.is_empty() {
443 run(&repo.root, &["config", "--local", "--unset-all", section])?;
444 }
445 } else if !config_section(repo, section)?.is_empty() {
446 run(
447 &repo.root,
448 &["config", "--local", "--remove-section", section],
449 )?;
450 }
451 for (key, value) in entries {
452 run(&repo.root, &["config", "--local", "--add", key, value])?;
453 }
454 Ok(())
455}
456
457fn loose_refs_root(repo: &RepoRef) -> Option<std::path::PathBuf> {
461 let dir = gitpoulpi_core::paths::common_dir(&gitpoulpi_core::paths::git_dir(&repo.root)?);
462 if !dir.join("refs").is_dir() {
463 return None;
464 }
465 let config = std::fs::read_to_string(dir.join("config")).unwrap_or_default();
466 if config.to_ascii_lowercase().contains("reftable") {
467 return None;
468 }
469 Some(dir)
470}
471
472fn write_pins_directly(repo: &RepoRef, updates: &[RefUpdate]) -> bool {
478 use gitpoulpi_core::domain::UNDO_PIN_PREFIX;
479 use std::io::Write;
480 let creates: Vec<(&String, &Oid)> = updates
481 .iter()
482 .filter_map(|u| match u {
483 RefUpdate::Create { name, new } if name.starts_with(UNDO_PIN_PREFIX) => {
484 Some((name, new))
485 }
486 _ => None,
487 })
488 .collect();
489 if creates.is_empty() || creates.len() != updates.len() {
490 return false;
491 }
492 if creates
493 .iter()
494 .any(|(name, _)| name.contains("..") || name.contains('\\') || name.ends_with('/'))
495 {
496 return false;
497 }
498 let Some(root) = loose_refs_root(repo) else {
499 return false;
500 };
501 let objects = root.join("objects");
507 if creates.iter().any(|(_, oid)| {
508 let hex = oid.to_string();
509 !objects.join(&hex[..2]).join(&hex[2..]).is_file() && !in_a_pack(&objects, oid)
510 }) {
511 return false;
512 }
513 let mut written: Vec<std::path::PathBuf> = Vec::new();
514 for (name, oid) in &creates {
515 let path = root.join(name);
516 let ok = (|| {
517 std::fs::create_dir_all(path.parent()?).ok()?;
518 let mut file = std::fs::OpenOptions::new()
519 .write(true)
520 .create_new(true)
521 .open(&path)
522 .ok()?;
523 written.push(path.clone());
524 file.write_all(format!("{oid}\n").as_bytes()).ok()
525 })();
526 if ok.is_none() {
527 for path in &written {
528 let _ = std::fs::remove_file(path);
529 }
530 return false;
531 }
532 }
533 true
534}
535
536fn in_a_pack(objects: &std::path::Path, oid: &Oid) -> bool {
541 let Some(want) = hex_bytes(&oid.to_string()) else {
542 return false;
543 };
544 let Ok(dir) = std::fs::read_dir(objects.join("pack")) else {
545 return false;
546 };
547 dir.flatten()
548 .filter(|e| e.path().extension().is_some_and(|x| x == "idx"))
549 .any(|e| {
550 std::fs::File::open(e.path())
551 .ok()
552 .and_then(|mut f| idx_lists(&mut f, &want))
553 .unwrap_or(false)
554 })
555}
556
557fn hex_bytes(hex: &str) -> Option<Vec<u8>> {
558 if hex.len() != 40 {
559 return None;
560 }
561 (0..hex.len())
562 .step_by(2)
563 .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).ok())
564 .collect()
565}
566
567fn idx_lists(file: &mut std::fs::File, want: &[u8]) -> Option<bool> {
570 use std::io::{Read, Seek, SeekFrom};
571 const FANOUT: u64 = 8;
572 let mut head = [0u8; 8 + 1024];
573 file.read_exact(&mut head).ok()?;
574 if head[..8] != [0xff, b't', b'O', b'c', 0, 0, 0, 2] {
575 return None;
576 }
577 let fan = |i: usize| -> u64 {
578 let o = FANOUT as usize + i * 4;
579 u64::from(u32::from_be_bytes([
580 head[o],
581 head[o + 1],
582 head[o + 2],
583 head[o + 3],
584 ]))
585 };
586 let first = want[0] as usize;
587 let (mut lo, mut hi) = (if first == 0 { 0 } else { fan(first - 1) }, fan(first));
588 let names = FANOUT + 1024;
589 while lo < hi {
590 let mid = (lo + hi) / 2;
591 let mut name = [0u8; 20];
592 file.seek(SeekFrom::Start(names + mid * 20)).ok()?;
593 file.read_exact(&mut name).ok()?;
594 match name.as_slice().cmp(want) {
595 std::cmp::Ordering::Equal => return Some(true),
596 std::cmp::Ordering::Less => lo = mid + 1,
597 std::cmp::Ordering::Greater => hi = mid,
598 }
599 }
600 Some(false)
601}
602
603fn delete_pins_directly(repo: &RepoRef, updates: &[RefUpdate]) -> bool {
609 use gitpoulpi_core::domain::UNDO_PIN_PREFIX;
610 let deletes: Vec<(&String, &Oid)> = updates
611 .iter()
612 .filter_map(|u| match u {
613 RefUpdate::Delete { name, old } if name.starts_with(UNDO_PIN_PREFIX) => {
614 Some((name, old))
615 }
616 _ => None,
617 })
618 .collect();
619 if deletes.is_empty() || deletes.len() != updates.len() {
620 return false;
621 }
622 if deletes
623 .iter()
624 .any(|(name, _)| name.contains("..") || name.contains('\\'))
625 {
626 return false;
627 }
628 let Some(root) = loose_refs_root(repo) else {
629 return false;
630 };
631 let paths: Vec<std::path::PathBuf> = deletes.iter().map(|(n, _)| root.join(n)).collect();
632 for ((_, oid), path) in deletes.iter().zip(&paths) {
633 match std::fs::read_to_string(path) {
634 Ok(text) if text.trim() == oid.to_hex() => {}
635 _ => return false,
636 }
637 }
638 for path in &paths {
639 if std::fs::remove_file(path).is_err() {
640 return false;
641 }
642 if let Some(dir) = path.parent() {
644 let _ = std::fs::remove_dir(dir);
645 }
646 }
647 true
648}
649
650#[cfg(test)]
651mod tests {
652 use super::*;
653
654 #[test]
655 fn a_dotted_branch_name_does_not_claim_its_prefix_branch() {
656 assert!(in_section("branch.a", "branch.a.remote"));
657 assert!(!in_section("branch.a", "branch.a.b.remote"));
658 assert!(in_section("branch.a.b", "branch.a.b.remote"));
659 assert!(!in_section("branch.a", "branch.ab.remote"));
660 }
661
662 #[test]
663 fn only_branch_sections_are_accepted() {
664 assert!(check_section("branch.main").is_ok());
665 assert!(check_section("branch.").is_err());
666 assert!(check_section("core").is_err());
667 assert!(check_section("remote.origin").is_ok());
668 assert!(check_section("remote.").is_err());
669 }
670}