Skip to main content

gitpoulpi_cli_backend/
journal_ops.rs

1//! The undo journal's backend primitives over the system `git`
2//! (`ref_snapshot`, `update_refs`, `config_section`,
3//! `set_config_section`). See the undo-redo design ยง2.7.
4
5use 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
14/// One `for-each-ref` (HEAD marked with `%(HEAD)`), plus a `symbolic-ref`
15/// (and a `rev-parse` when detached) only when HEAD is not on a listed
16/// branch: unborn, detached, or a scope without branches.
17pub 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
62/// HEAD as it is right now.
63fn 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
88/// `git update-ref --stdin -z`: one transaction, so a stale expectation
89/// anywhere changes nothing. A failure is turned into the typed
90/// `RefMoved` by re-reading the refs involved.
91pub fn update_refs(repo: &RepoRef, updates: &[RefUpdate], reflog_message: &str) -> Result<()> {
92    // Keep-alive pins are the hot case (every journaled operation writes
93    // some): a loose ref is a one-line file, so write it ourselves rather
94    // than spend a process on it.
95    if write_pins_directly(repo, updates) || delete_pins_directly(repo, updates) {
96        return Ok(());
97    }
98    // HEAD moves are verified first, applied after the ref transaction.
99    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                    // Atomic with the rest.
115                    (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
204/// A failed transaction: name the first ref that is not as expected, or
205/// pass git's own message through when every expectation holds.
206fn 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
228/// `git reset --keep`: the checked-out `branch` moves from `from` to `to`
229/// and the index and files follow, refusing (nothing changed) when a
230/// local change would be overwritten.
231pub 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
259/// A checked-out submodule that the move turns back into a plain folder
260/// (undoing "extract as a submodule") is de-initialised first: git would
261/// otherwise leave its files in the way of the folder's own. Edits inside
262/// it refuse the move, nothing changed.
263fn 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
314/// `branch.<name>` and `remote.<name>` only: this is an undo helper, not
315/// a config API.
316pub fn check_section(section: &str) -> Result<()> {
317    // The allow-listed repo-config keys (`core.autocrlf`, `core.eol`) are
318    // one-variable pseudo-sections, so the undo journal restores them with
319    // the same steps; `core` as a whole is never accepted.
320    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
335/// The local config as `(key, value)` pairs, in file order.
336pub(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
348/// One process for any number of sections.
349pub 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
373/// The `branch.<name>` sections whose `remote` is `remote`, sorted.
374pub fn remote_dependents(repo: &RepoRef, remote: &str) -> Result<Vec<String>> {
375    Ok(dependents_in(&local_entries(repo)?, remote))
376}
377
378/// [`remote_dependents`] over already-read config entries (git2 shares it).
379pub fn dependents_in(entries: &[(String, String)], remote: &str) -> Vec<String> {
380    // `branch.<b>.remote` (git's upstream) and GitPoulpi's extra push
381    // targets / pull sources, whose values are `<remote>[:<branch>]`.
382    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
401/// Whether `key` is a variable of `section` (`branch.a` owns
402/// `branch.a.remote` but not `branch.a.b.remote`, which is branch `a.b`'s).
403pub 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
412/// `section` is one allow-listed key standing for itself (see `check_section`).
413pub 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
457/// The directory holding `refs/` for this repository (the common git dir
458/// of a linked worktree), only for the files ref backend: a reftable
459/// repository does not read loose ref files.
460fn 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
472/// Creates the pin refs of `updates` as loose ref files, when `updates`
473/// is nothing but `Create`s under the pin namespace. All or nothing: any
474/// trouble (the ref exists, no permission) removes what was written and
475/// reports `false`, and the caller takes the ordinary `update-ref` path,
476/// which words the failure.
477fn 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    // `git update-ref` refuses an id the repository does not have; a file
502    // written here would not. A loose object or one listed by a pack index
503    // is checked without a process (an unstage's "after" tree is usually
504    // HEAD's own, packed after a `gc`): anything else (in an alternate,
505    // missing) takes the `update-ref` path, which verifies it.
506    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
536/// Whether some pack index of `objects/pack` lists `oid` (idx version 2:
537/// 8-byte header, 256-entry fanout, then the sorted 20-byte names). An
538/// unreadable or unknown index counts as "not found", which only costs the
539/// `update-ref` process that would have run anyway.
540fn 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
567/// Binary search of one idx file by seeking: only the 1 KB header and
568/// about log2(n) 20-byte names are read, never the whole index.
569fn 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
603/// Releases pin refs as loose ref files, when `updates` is nothing but
604/// `Delete`s under the pin namespace whose loose files hold the expected
605/// oid. A pin that is not a loose file (packed by `git pack-refs`, or
606/// already gone) sends the whole batch down the ordinary `update-ref`
607/// path, which also words the failure; nothing is removed in that case.
608fn 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        // The entry's directory goes with its last pin (best effort).
643        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}