Skip to main content

quarb_git/
lib.rs

1//! Git repository adapter for the Quarb query engine.
2//!
3//! A repository is an arbor with a real DAG for its crosslink
4//! fabric. The root exposes four names:
5//!
6//! - `/branches/<name>`, `/tags/<name>` — the refs. A ref node is
7//!   an *alias for its commit*: same properties, same children.
8//! - `/HEAD` — the checked-out commit, same alias treatment.
9//! - `/commits/<hash>` — every commit. Navigating by literal name
10//!   accepts anything `git rev-parse` does (unique prefixes,
11//!   `HEAD~2`, `v1.0^{}`), without enumerating; enumeration
12//!   (`/commits/*`) lists every commit reachable from any ref, in
13//!   reverse chronological order, batched through one
14//!   `rev-list --all`.
15//!
16//! A commit's properties are its header (`::author`, `::email`,
17//! `::date` as an instant (the author date, offset preserved),
18//! `::committer`, `::subject`,
19//! `::message`, `::parent` — the first parent's hash); its
20//! *children are its tree* — descend `/branches/master/src/lib.rs`
21//! and the blob's content is the node's value (`::`), giving
22//! time-travel file access at any commit. Tree entries carry
23//! `:::type`, `:::mode`, `:::size`, and `:::hash`.
24//!
25//! References are inherent, no schema needed: `::parent-->`
26//! resolves to the first parent, `->parent` enumerates all
27//! parents (merges fan out), and `<-parent` finds the commits
28//! that point *here* (children — served from the enumeration, so
29//! it loads the commit list). Traits name what a node is:
30//! `<commit>`, `<branch>`, `<tag>`, `<tree>`, `<blob>`.
31//!
32//! Everything is read through git plumbing over subprocess
33//! (`rev-list`, `rev-parse`, `ls-tree`, `cat-file`, ...) — no
34//! libgit2, no new dependencies — lazily, one object on first
35//! touch. A walk along `parent` reads ahead: a commit the walk
36//! arrives at is read together with the next of its ancestors (one
37//! `rev-list -n k`, k doubling), so a walk of n commits starts
38//! about log n git processes and not n. The tree and the commits
39//! are kept for the adapter's lifetime; a blob's content is read
40//! again at each read, through one open `cat-file --batch` pipe, so
41//! a large file is never held. The adapter never writes.
42
43use quarb::{AstAdapter, NodeId, Value};
44use std::cell::RefCell;
45use std::collections::HashMap;
46use std::path::PathBuf;
47
48/// An error opening or reading a repository.
49#[derive(Debug, thiserror::Error)]
50pub enum GitError {
51    #[error("git: {0}")]
52    Git(String),
53    #[error("git: running git: {0}")]
54    Spawn(#[from] std::io::Error),
55}
56
57/// A commit's parsed header.
58#[derive(Clone)]
59struct CommitInfo {
60    author: String,
61    email: String,
62    date: i64,
63    /// The author date's UTC offset in minutes (from `%ai`),
64    /// preserved for display on the minted instant.
65    date_offset: Option<i16>,
66    committer: String,
67    subject: String,
68    message: String,
69    tree: String,
70    parents: Vec<String>,
71}
72
73/// What a node is.
74#[derive(Clone)]
75enum Kind {
76    Root,
77    /// `branches`, `tags`, or `commits`.
78    Dir(&'static str),
79    /// A ref (branch, tag, or HEAD): an alias for its commit.
80    Ref {
81        name: String,
82        commit: String,
83    },
84    Commit(String),
85    /// A tree entry: a subtree or a blob.
86    Entry {
87        name: String,
88        oid: String,
89        entry_type: String, // "tree" | "blob"
90        mode: String,
91    },
92}
93
94struct Node {
95    kind: Kind,
96    parent: Option<NodeId>,
97    children: RefCell<Option<Vec<NodeId>>>,
98}
99
100/// A git repository, exposed as an arbor.
101pub struct GitAdapter {
102    repo: PathBuf,
103    /// The mount's rule at the source boundary: a blob's text
104    /// decodes under it (`?encoding=`, else strict UTF-8).
105    decoding: quarb::source::SourceDecoding,
106    nodes: RefCell<Vec<Node>>,
107    commits: RefCell<HashMap<String, CommitInfo>>,
108    /// The parents of the commits held that are not held themselves:
109    /// where a walk goes next (see `commit_info`).
110    frontier: RefCell<std::collections::HashSet<String>>,
111    /// How many commits the last read along a walk took.
112    ahead: std::cell::Cell<usize>,
113    /// The commits the listed refs point at, in the listings' order,
114    /// and where each one not yet asked for stands in it: where a
115    /// sweep of the refs goes next (see `commit_info`).
116    tips: RefCell<Vec<String>>,
117    tip_at: RefCell<HashMap<String, usize>>,
118    /// How many commits the last read along a sweep of the refs took.
119    tips_ahead: std::cell::Cell<usize>,
120    /// The git processes started for commit headers (the tests'
121    /// measure of what a walk costs).
122    header_reads: std::cell::Cell<usize>,
123    /// hash → its `/commits/<hash>` node.
124    commit_nodes: RefCell<HashMap<String, NodeId>>,
125    /// Whether `/commits` has been enumerated (rev-list --all).
126    enumerated: RefCell<bool>,
127    /// hash → the paths its diff (vs first parent) touches.
128    changed: RefCell<HashMap<String, Vec<String>>>,
129    /// commit hash → the tag names pointing at it (lazy).
130    tag_map: RefCell<Option<HashMap<String, Vec<String>>>>,
131    /// commit hash → the commits that list it as a parent (built
132    /// once from the enumeration; `<--` over every commit is one
133    /// pass, not one scan of the list per commit).
134    children_of: RefCell<Option<HashMap<String, Vec<String>>>>,
135    /// One `git cat-file --batch` (contents) and one `--batch-check`
136    /// (sizes) kept open: a blob per request on a pipe, not a git
137    /// process per blob.
138    blobs: RefCell<Option<Batch>>,
139    sizes: RefCell<Option<Batch>>,
140    /// HEAD and every ref with its object, as the last look at them
141    /// answered (see [`GitAdapter::refresh`]); `None` before the
142    /// first look.
143    refs_seen: RefCell<Option<String>>,
144}
145
146/// A `git cat-file --batch[-check]` child on a pipe.
147struct Batch {
148    child: std::process::Child,
149    stdin: std::process::ChildStdin,
150    out: std::io::BufReader<std::process::ChildStdout>,
151}
152
153impl Batch {
154    fn spawn(repo: &std::path::Path, check: bool) -> std::io::Result<Batch> {
155        let mut child = std::process::Command::new("git")
156            .arg("-C")
157            .arg(repo)
158            .args(["cat-file", if check { "--batch-check" } else { "--batch" }])
159            .stdin(std::process::Stdio::piped())
160            .stdout(std::process::Stdio::piped())
161            .stderr(std::process::Stdio::null())
162            .spawn()?;
163        let stdin = child.stdin.take().expect("piped");
164        let out = std::io::BufReader::new(child.stdout.take().expect("piped"));
165        Ok(Batch { child, stdin, out })
166    }
167
168    /// Ask for `oid`: the header line (`<oid> <type> <size>`), or
169    /// `None` when the object is missing.
170    fn header(&mut self, oid: &str) -> std::io::Result<Option<u64>> {
171        use std::io::{BufRead, Write};
172        writeln!(self.stdin, "{oid}")?;
173        self.stdin.flush()?;
174        let mut line = String::new();
175        self.out.read_line(&mut line)?;
176        let mut parts = line.split_whitespace();
177        let _oid = parts.next();
178        match (parts.next(), parts.next()) {
179            (Some("missing"), _) | (None, _) => Ok(None),
180            (Some(_), Some(size)) => Ok(size.parse().ok()),
181            _ => Ok(None),
182        }
183    }
184
185    /// The object's bytes (after `header`, on a `--batch` child).
186    fn body(&mut self, size: u64) -> std::io::Result<Vec<u8>> {
187        use std::io::Read;
188        let mut buf = vec![0u8; size as usize];
189        self.out.read_exact(&mut buf)?;
190        let mut nl = [0u8; 1];
191        self.out.read_exact(&mut nl)?;
192        Ok(buf)
193    }
194}
195
196impl Drop for GitAdapter {
197    fn drop(&mut self) {
198        for b in [self.blobs.get_mut(), self.sizes.get_mut()] {
199            if let Some(b) = b {
200                let _ = b.child.kill();
201                let _ = b.child.wait();
202            }
203        }
204    }
205}
206
207const ROOT: NodeId = NodeId(0);
208/// The most commits one read along a walk takes.
209const AHEAD_MOST: usize = 1024;
210const BRANCHES: NodeId = NodeId(1);
211const TAGS: NodeId = NodeId(2);
212const COMMITS: NodeId = NodeId(3);
213
214impl GitAdapter {
215    /// Open the repository at `path` (any directory inside it).
216    pub fn open(path: &std::path::Path) -> Result<Self, GitError> {
217        Self::open_with_decoding(path, quarb::source::SourceDecoding::default())
218    }
219
220    /// [`open`](Self::open) under a mount's source-boundary rule:
221    /// blobs decode by `?encoding=`, a byte-order mark, else strict
222    /// UTF-8 (a blob that decodes under none has no text).
223    pub fn open_with_decoding(
224        path: &std::path::Path,
225        decoding: quarb::source::SourceDecoding,
226    ) -> Result<Self, GitError> {
227        let adapter = GitAdapter {
228            repo: path.to_path_buf(),
229            decoding,
230            nodes: RefCell::new(vec![
231                Node {
232                    kind: Kind::Root,
233                    parent: None,
234                    children: RefCell::new(None),
235                },
236                Node {
237                    kind: Kind::Dir("branches"),
238                    parent: Some(ROOT),
239                    children: RefCell::new(None),
240                },
241                Node {
242                    kind: Kind::Dir("tags"),
243                    parent: Some(ROOT),
244                    children: RefCell::new(None),
245                },
246                Node {
247                    kind: Kind::Dir("commits"),
248                    parent: Some(ROOT),
249                    children: RefCell::new(None),
250                },
251            ]),
252            commits: RefCell::new(HashMap::new()),
253            frontier: RefCell::new(std::collections::HashSet::new()),
254            ahead: std::cell::Cell::new(1),
255            tips: RefCell::new(Vec::new()),
256            tip_at: RefCell::new(HashMap::new()),
257            tips_ahead: std::cell::Cell::new(1),
258            header_reads: std::cell::Cell::new(0),
259            commit_nodes: RefCell::new(HashMap::new()),
260            enumerated: RefCell::new(false),
261            changed: RefCell::new(HashMap::new()),
262            tag_map: RefCell::new(None),
263            children_of: RefCell::new(None),
264            blobs: RefCell::new(None),
265            sizes: RefCell::new(None),
266            refs_seen: RefCell::new(None),
267        };
268        // Probe: is this a repository at all?
269        adapter.git(&["rev-parse", "--git-dir"])?;
270        Ok(adapter)
271    }
272
273    /// Look at the refs again, as a standing session does before
274    /// each query (the ruling of 2026-11-17: a session over a
275    /// repository answers it as it stands, always): one
276    /// `git show-ref --head`, HEAD and every ref with its object and
277    /// nothing peeled, held against the answer of the look before.
278    /// Where a ref moved, appeared or went, what was read off the
279    /// refs is forgotten and reads again when asked: the HEAD node,
280    /// the listings of `/branches`, `/tags` and `/commits`, the tag
281    /// map, the children index, the sweep's order. Commits, trees
282    /// and changed paths stay: a hash names them. Returns whether
283    /// anything moved.
284    ///
285    /// The look costs 3 ms on a repository of 466 refs and grows
286    /// with them (the Linux mainline has 956; 20,000 take 27 ms).
287    /// Before it a session kept each listing from its first read:
288    /// after a commit `/HEAD` and `/commits/*` answered the old
289    /// state and `/commits/HEAD` the new.
290    ///
291    /// The nodes of the forgotten refs stay in the arena, unreached
292    /// (some hundred a look that finds a change on a repository of
293    /// some hundred refs): ids a caller holds from an earlier query
294    /// keep their meaning.
295    pub fn refresh(&self) -> bool {
296        // no ref at all (a repository before its first commit) is
297        // git's exit 1: an empty answer here
298        let seen = self.git(&["show-ref", "--head"]).unwrap_or_default();
299        let mut last = self.refs_seen.borrow_mut();
300        match last.as_deref() {
301            Some(prev) if prev == seen => false,
302            // the first look: nothing it could differ from, and what
303            // was read before it reads again
304            _ => {
305                let moved = last.is_some();
306                *last = Some(seen);
307                drop(last);
308                self.forget_refs();
309                moved
310            }
311        }
312    }
313
314    /// Forget what was read off the refs (see [`refresh`]).
315    ///
316    /// [`refresh`]: Self::refresh
317    fn forget_refs(&self) {
318        {
319            let nodes = self.nodes.borrow();
320            for dir in [ROOT, BRANCHES, TAGS, COMMITS] {
321                *nodes[dir.0 as usize].children.borrow_mut() = None;
322            }
323        }
324        *self.enumerated.borrow_mut() = false;
325        *self.tag_map.borrow_mut() = None;
326        *self.children_of.borrow_mut() = None;
327        self.tips.borrow_mut().clear();
328        self.tip_at.borrow_mut().clear();
329        self.tips_ahead.set(1);
330    }
331
332    /// A human-readable locator: `/commits/<short>/path`,
333    /// `/branches/<name>/path`, ...
334    pub fn locator(&self, node: NodeId) -> String {
335        let nodes = self.nodes.borrow();
336        let mut parts = Vec::new();
337        let mut cur = Some(node);
338        while let Some(n) = cur {
339            let nd = &nodes[n.0 as usize];
340            match &nd.kind {
341                Kind::Root => {}
342                Kind::Dir(d) => parts.push(d.to_string()),
343                Kind::Ref { name, .. } => parts.push(name.clone()),
344                Kind::Commit(h) => parts.push(h[..7.min(h.len())].to_string()),
345                Kind::Entry { name, .. } => parts.push(name.clone()),
346            }
347            cur = nd.parent;
348        }
349        parts.reverse();
350        format!("/{}", parts.join("/"))
351    }
352
353    /// Run git for structured output (headers, trees, refs): paths
354    /// come unquoted (`core.quotepath=off`) and the output must be
355    /// UTF-8 — the commands that print messages take
356    /// `--encoding=UTF-8`, so git transcodes a commit written in
357    /// another declared encoding. Output that still is not UTF-8
358    /// is an error, never replaced.
359    fn git(&self, args: &[&str]) -> Result<String, GitError> {
360        let out = self.git_bytes(args)?;
361        String::from_utf8(out).map_err(|e| {
362            GitError::Git(format!(
363                "git {}: output is not UTF-8 at byte {}",
364                args.first().unwrap_or(&""),
365                e.utf8_error().valid_up_to()
366            ))
367        })
368    }
369
370    /// A blob's bytes through the open `cat-file --batch` pipe; a
371    /// pipe that fails is dropped and the one-shot command answers.
372    fn blob_bytes(&self, oid: &str) -> Result<Vec<u8>, GitError> {
373        let batched = (|| -> std::io::Result<Option<Vec<u8>>> {
374            let mut slot = self.blobs.borrow_mut();
375            if slot.is_none() {
376                *slot = Some(Batch::spawn(&self.repo, false)?);
377            }
378            let b = slot.as_mut().expect("spawned");
379            match b.header(oid)? {
380                Some(size) => b.body(size).map(Some),
381                None => Ok(None),
382            }
383        })();
384        match batched {
385            Ok(Some(bytes)) => Ok(bytes),
386            Ok(None) => Err(GitError::Git(format!("blob {oid}: missing"))),
387            Err(_) => {
388                *self.blobs.borrow_mut() = None;
389                self.git_bytes(&["cat-file", "blob", oid])
390            }
391        }
392    }
393
394    /// A blob's size through the open `cat-file --batch-check` pipe,
395    /// with the same fallback.
396    fn blob_size(&self, oid: &str) -> Option<u64> {
397        let batched = (|| -> std::io::Result<Option<u64>> {
398            let mut slot = self.sizes.borrow_mut();
399            if slot.is_none() {
400                *slot = Some(Batch::spawn(&self.repo, true)?);
401            }
402            slot.as_mut().expect("spawned").header(oid)
403        })();
404        match batched {
405            Ok(size) => size,
406            Err(_) => {
407                *self.sizes.borrow_mut() = None;
408                self.git(&["cat-file", "-s", oid])
409                    .ok()
410                    .and_then(|s| s.trim().parse().ok())
411            }
412        }
413    }
414
415    /// The commits that list `hash` as a parent, from an index
416    /// built once over the enumeration.
417    fn children_of(&self, hash: &str) -> Vec<String> {
418        self.enumerate_commits();
419        if self.children_of.borrow().is_none() {
420            let mut index: HashMap<String, Vec<String>> = HashMap::new();
421            for (h, info) in self.commits.borrow().iter() {
422                for p in &info.parents {
423                    index.entry(p.clone()).or_default().push(h.clone());
424                }
425            }
426            for v in index.values_mut() {
427                v.sort();
428            }
429            *self.children_of.borrow_mut() = Some(index);
430        }
431        self.children_of
432            .borrow()
433            .as_ref()
434            .and_then(|i| i.get(hash).cloned())
435            .unwrap_or_default()
436    }
437
438    /// Run git for raw bytes (a blob): the caller decodes.
439    fn git_bytes(&self, args: &[&str]) -> Result<Vec<u8>, GitError> {
440        let out = std::process::Command::new("git")
441            .arg("-C")
442            .arg(&self.repo)
443            .args(["-c", "core.quotepath=off"])
444            .args(args)
445            .output()?;
446        if !out.status.success() {
447            return Err(GitError::Git(
448                String::from_utf8(out.stderr)
449                    .map(|s| s.trim().to_string())
450                    .unwrap_or_else(|_| "(git's message is not UTF-8)".to_string()),
451            ));
452        }
453        Ok(out.stdout)
454    }
455
456    fn push_node(&self, kind: Kind, parent: Option<NodeId>) -> NodeId {
457        let mut nodes = self.nodes.borrow_mut();
458        let id = NodeId(nodes.len() as u64);
459        nodes.push(Node {
460            kind,
461            parent,
462            children: RefCell::new(None),
463        });
464        id
465    }
466
467    /// The `/commits/<hash>` node for a full hash, interning it.
468    fn commit_node(&self, hash: &str) -> NodeId {
469        if let Some(&id) = self.commit_nodes.borrow().get(hash) {
470            return id;
471        }
472        let id = self.push_node(Kind::Commit(hash.to_string()), Some(COMMITS));
473        self.commit_nodes.borrow_mut().insert(hash.to_string(), id);
474        id
475    }
476
477    /// Hold a commit's header, and note where a walk from it goes:
478    /// its parents not yet held.
479    fn learn(&self, hash: &str, info: CommitInfo) {
480        let mut commits = self.commits.borrow_mut();
481        let mut frontier = self.frontier.borrow_mut();
482        frontier.remove(hash);
483        for p in &info.parents {
484            if !commits.contains_key(p) {
485                frontier.insert(p.clone());
486            }
487        }
488        commits.insert(hash.to_string(), info);
489    }
490
491    /// Note the commit a listed ref points at, for the sweep of the
492    /// listing to read it with its neighbours.
493    fn note_tip(&self, hash: &str) {
494        if self.commits.borrow().contains_key(hash) {
495            return;
496        }
497        let mut tips = self.tips.borrow_mut();
498        let mut tip_at = self.tip_at.borrow_mut();
499        if !tip_at.contains_key(hash) {
500            tip_at.insert(hash.to_string(), tips.len());
501            tips.push(hash.to_string());
502        }
503    }
504
505    /// The git processes started so far for commit headers: one per
506    /// keyed commit, one per read along a walk, one per listing.
507    #[doc(hidden)]
508    pub fn header_reads(&self) -> usize {
509        self.header_reads.get()
510    }
511
512    /// A commit's parsed header, fetched on first touch.
513    ///
514    /// A commit that is the parent of one already held is a walk
515    /// arriving: it is read together with the next of its ancestors,
516    /// twice as many as the walk's last read took, up to
517    /// [`AHEAD_MOST`] (one `rev-list -n k` from it, the listing's own
518    /// format and parser, so the values are the listing's). A walk of
519    /// n commits then starts about log n processes. It started one
520    /// `git show` a commit: 400 commits took 1.7 s and a history of
521    /// 1,568 took 5.8 s, where listing all of it takes 0.08 s. A
522    /// commit asked for by name alone is still one commit read.
523    ///
524    /// A commit a listed ref points at is a sweep of the refs
525    /// arriving (`/tags/* | ::subject`): it is read together with
526    /// the commits of the refs that follow it in the listing, by
527    /// the same doubling (one `rev-list --no-walk` of them). The
528    /// sweep started one `git show` a ref: 448 tags on 167 commits
529    /// took 0.7 s, where reading those commits together takes
530    /// 0.03 s. A ref asked for by name is one read of two commits.
531    fn commit_info(&self, hash: &str) -> Option<CommitInfo> {
532        if let Some(i) = self.commits.borrow().get(hash) {
533            return Some(i.clone());
534        }
535        if self.frontier.borrow().contains(hash) {
536            let k = (self.ahead.get() * 2).min(AHEAD_MOST);
537            self.ahead.set(k);
538            self.read_ancestry(hash, k);
539            if let Some(i) = self.commits.borrow().get(hash) {
540                return Some(i.clone());
541            }
542        }
543        let tip = self.tip_at.borrow().get(hash).copied();
544        if let Some(at) = tip {
545            let k = (self.tips_ahead.get() * 2).min(AHEAD_MOST);
546            self.tips_ahead.set(k);
547            self.read_tips(at, k);
548            if let Some(i) = self.commits.borrow().get(hash) {
549                return Some(i.clone());
550            }
551        }
552        self.header_reads.set(self.header_reads.get() + 1);
553        let out = self
554            .git(&[
555                "show",
556                "-s",
557                "--encoding=UTF-8",
558                "--format=%an%x00%ae%x00%at%x00%cn%x00%s%x00%B%x00%T%x00%P%x00%ai",
559                hash,
560            ])
561            .ok()?;
562        let info = parse_info(&out)?;
563        self.learn(hash, info.clone());
564        Some(info)
565    }
566
567    /// `hash` and the next `k - 1` of its ancestors, newest first,
568    /// in one `rev-list`: the commits a walk from `hash` reads next.
569    fn read_ancestry(&self, hash: &str, k: usize) {
570        self.header_reads.set(self.header_reads.get() + 1);
571        let n = k.to_string();
572        let Ok(out) = self.git(&[
573            "rev-list",
574            "--encoding=UTF-8",
575            "-n",
576            &n,
577            "--format=%an%x00%ae%x00%at%x00%cn%x00%s%x00%B%x00%T%x00%P%x00%ai%x1e",
578            hash,
579        ]) else {
580            return;
581        };
582        for (h, body) in split_commit_records(&out) {
583            if self.commits.borrow().contains_key(h) {
584                continue;
585            }
586            if let Some(info) = parse_info(body) {
587                self.learn(h, info);
588            }
589        }
590    }
591
592    /// The listed refs' commits from the one at `at` on, those not
593    /// held and not yet asked for, `k` at most, in one
594    /// `rev-list --no-walk`: the commits a sweep of the refs reads
595    /// next. Each is asked for here once: what git does not answer
596    /// (a tag of a tree names no commit) is left to the single read.
597    fn read_tips(&self, at: usize, k: usize) {
598        let batch: Vec<String> = {
599            let tips = self.tips.borrow();
600            let commits = self.commits.borrow();
601            let mut tip_at = self.tip_at.borrow_mut();
602            let mut batch = Vec::new();
603            for h in &tips[at..] {
604                if batch.len() == k {
605                    break;
606                }
607                if tip_at.remove(h).is_some() && !commits.contains_key(h) {
608                    batch.push(h.clone());
609                }
610            }
611            batch
612        };
613        // one commit alone is the single read's
614        if batch.len() < 2 {
615            return;
616        }
617        self.header_reads.set(self.header_reads.get() + 1);
618        let mut args = vec![
619            "rev-list",
620            "--no-walk",
621            "--encoding=UTF-8",
622            "--format=%an%x00%ae%x00%at%x00%cn%x00%s%x00%B%x00%T%x00%P%x00%ai%x1e",
623        ];
624        args.extend(batch.iter().map(String::as_str));
625        let Ok(out) = self.git(&args) else {
626            return;
627        };
628        for (h, body) in split_commit_records(&out) {
629            if self.commits.borrow().contains_key(h) {
630                continue;
631            }
632            if let Some(info) = parse_info(body) {
633                self.learn(h, info);
634            }
635        }
636    }
637
638    /// Enumerate every commit reachable from any ref: one
639    /// `rev-list --all` with the header format, parsed in bulk.
640    /// The first `k` commits of `rev-list --all`, for a step that keeps
641    /// a prefix (the pushdown scanning round, 2026-11-06): the walk
642    /// stops at k, the nodes keyed by hash so the full enumeration
643    /// finds them again; nothing cached as the listing.
644    fn commits_prefix(&self, k: usize) -> Vec<NodeId> {
645        self.header_reads.set(self.header_reads.get() + 1);
646        let n = k.to_string();
647        let out = self
648            .git(&[
649                "rev-list",
650                "--encoding=UTF-8",
651                "--all",
652                "-n",
653                &n,
654                "--format=%an%x00%ae%x00%at%x00%cn%x00%s%x00%B%x00%T%x00%P%x00%ai%x1e",
655            ])
656            .unwrap_or_default();
657        let mut ids = Vec::new();
658        for (hash, body) in split_commit_records(&out) {
659            if let Some(info) = parse_info(body) {
660                self.learn(hash, info);
661            }
662            ids.push(self.commit_node(hash));
663        }
664        ids
665    }
666
667    fn enumerate_commits(&self) -> Vec<NodeId> {
668        if let Some(c) = self.nodes.borrow()[COMMITS.0 as usize]
669            .children
670            .borrow()
671            .as_ref()
672        {
673            return c.clone();
674        }
675        self.header_reads.set(self.header_reads.get() + 1);
676        let out = self
677            .git(&[
678                "rev-list",
679                "--encoding=UTF-8",
680                "--all",
681                "--format=%an%x00%ae%x00%at%x00%cn%x00%s%x00%B%x00%T%x00%P%x00%ai%x1e",
682            ])
683            .unwrap_or_default();
684        let mut ids = Vec::new();
685        for (hash, body) in split_commit_records(&out) {
686            if let Some(info) = parse_info(body) {
687                self.commits.borrow_mut().insert(hash.to_string(), info);
688            }
689            ids.push(self.commit_node(hash));
690        }
691        *self.enumerated.borrow_mut() = true;
692        // every reachable commit is held: no walk has anywhere to
693        // read ahead to
694        self.frontier.borrow_mut().clear();
695        *self.nodes.borrow()[COMMITS.0 as usize]
696            .children
697            .borrow_mut() = Some(ids.clone());
698        ids
699    }
700
701    /// The tag names pointing at `hash` (annotated tags
702    /// dereferenced), from one cached `for-each-ref` sweep.
703    fn tags_at(&self, hash: &str) -> Vec<String> {
704        if self.tag_map.borrow().is_none() {
705            let out = self
706                .git(&[
707                    "for-each-ref",
708                    "refs/tags",
709                    "--format=%(refname:short)%00%(objectname)%00%(*objectname)",
710                ])
711                .unwrap_or_default();
712            let mut map: HashMap<String, Vec<String>> = HashMap::new();
713            for line in out.lines() {
714                let mut f = line.split('\u{0}');
715                let (Some(name), Some(oid)) = (f.next(), f.next()) else {
716                    continue;
717                };
718                let peeled = f.next().filter(|p| !p.is_empty()).unwrap_or(oid);
719                map.entry(peeled.to_string())
720                    .or_default()
721                    .push(name.to_string());
722            }
723            *self.tag_map.borrow_mut() = Some(map);
724        }
725        self.tag_map
726            .borrow()
727            .as_ref()
728            .and_then(|m| m.get(hash).cloned())
729            .unwrap_or_default()
730    }
731
732    /// The refs under `refs/heads` or `refs/tags` (tags
733    /// dereferenced to their commits).
734    fn refs(&self, dir: NodeId, prefix: &str) -> Vec<NodeId> {
735        if let Some(c) = self.nodes.borrow()[dir.0 as usize]
736            .children
737            .borrow()
738            .as_ref()
739        {
740            return c.clone();
741        }
742        let out = self
743            .git(&[
744                "for-each-ref",
745                prefix,
746                "--format=%(refname:short)%00%(objectname)%00%(*objectname)",
747            ])
748            .unwrap_or_default();
749        let mut ids = Vec::new();
750        for line in out.lines() {
751            let mut f = line.split('\u{0}');
752            let (Some(name), Some(oid)) = (f.next(), f.next()) else {
753                continue;
754            };
755            let deref = f.next().unwrap_or("");
756            let commit = if deref.is_empty() { oid } else { deref };
757            self.note_tip(commit);
758            ids.push(self.push_node(
759                Kind::Ref {
760                    name: name.to_string(),
761                    commit: commit.to_string(),
762                },
763                Some(dir),
764            ));
765        }
766        *self.nodes.borrow()[dir.0 as usize].children.borrow_mut() = Some(ids.clone());
767        ids
768    }
769
770    /// The entries of a tree object, as child nodes of `parent`.
771    fn tree_children(&self, parent: NodeId, tree_oid: &str) -> Vec<NodeId> {
772        if let Some(c) = self.nodes.borrow()[parent.0 as usize]
773            .children
774            .borrow()
775            .as_ref()
776        {
777            return c.clone();
778        }
779        let out = self.git(&["ls-tree", "-z", tree_oid]).unwrap_or_default();
780        let mut ids = Vec::new();
781        // "<mode> <type> <oid>\t<name>" records, NUL-terminated by
782        // `-z` so names arrive raw — never C-quoted the way the
783        // newline-delimited default renders non-ASCII paths.
784        for entry in out.split('\u{0}') {
785            let Some((meta, name)) = entry.split_once('\t') else {
786                continue;
787            };
788            let mut f = meta.split(' ');
789            let (Some(mode), Some(entry_type), Some(oid)) = (f.next(), f.next(), f.next()) else {
790                continue;
791            };
792            ids.push(self.push_node(
793                Kind::Entry {
794                    name: name.to_string(),
795                    oid: oid.to_string(),
796                    entry_type: entry_type.to_string(),
797                    mode: mode.to_string(),
798                },
799                Some(parent),
800            ));
801        }
802        *self.nodes.borrow()[parent.0 as usize].children.borrow_mut() = Some(ids.clone());
803        ids
804    }
805
806    /// The paths a commit's diff touches, relative to its first
807    /// parent (the whole tree for a root commit), computed once.
808    fn changed_paths(&self, hash: &str) -> Vec<String> {
809        if let Some(c) = self.changed.borrow().get(hash) {
810            return c.clone();
811        }
812        let out = self
813            .git(&[
814                "diff-tree",
815                "--root",
816                "--no-commit-id",
817                "--name-only",
818                "-z",
819                "-r",
820                hash,
821            ])
822            .unwrap_or_default();
823        // `-z`: NUL-separated, raw paths (never C-quoted), so they
824        // compare equal to the raw names from `ls-tree -z`.
825        let paths: Vec<String> = out
826            .split('\u{0}')
827            .filter(|p| !p.is_empty())
828            .map(str::to_string)
829            .collect();
830        self.changed
831            .borrow_mut()
832            .insert(hash.to_string(), paths.clone());
833        paths
834    }
835
836    /// The commit a tree entry belongs to and the entry's path
837    /// within it.
838    fn entry_context(&self, node: NodeId) -> Option<(String, String)> {
839        let nodes = self.nodes.borrow();
840        let mut parts = Vec::new();
841        let mut cur = Some(node);
842        while let Some(n) = cur {
843            let nd = &nodes[n.0 as usize];
844            match &nd.kind {
845                Kind::Entry { name, .. } => parts.push(name.clone()),
846                Kind::Commit(h) => {
847                    parts.reverse();
848                    return Some((h.clone(), parts.join("/")));
849                }
850                Kind::Ref { commit, .. } => {
851                    parts.reverse();
852                    return Some((commit.clone(), parts.join("/")));
853                }
854                _ => return None,
855            }
856            cur = nd.parent;
857        }
858        None
859    }
860
861    /// The commit hash a node stands for (commits and ref aliases).
862    fn commit_of(&self, node: NodeId) -> Option<String> {
863        match &self.nodes.borrow()[node.0 as usize].kind {
864            Kind::Commit(h) => Some(h.clone()),
865            Kind::Ref { commit, .. } => Some(commit.clone()),
866            _ => None,
867        }
868    }
869
870    /// The nearest commit-backed ancestor, the node itself included:
871    /// a tree entry answers through the commit it was reached under.
872    fn commit_ancestor(&self, node: NodeId) -> Option<String> {
873        let mut cur = Some(node);
874        while let Some(n) = cur {
875            if let Some(h) = self.commit_of(n) {
876                return Some(h);
877            }
878            cur = self.nodes.borrow()[n.0 as usize].parent;
879        }
880        None
881    }
882}
883
884/// Split `rev-list --format=…%x1e` output into `(hash, body)`
885/// records. Each commit's format expansion is terminated by the
886/// ASCII Record Separator (`%x1e`), so a literal `commit ` line
887/// inside a message body (`%s`/`%B`) can never split a record;
888/// the leading `commit <hash>` header of each record supplies the
889/// hash.
890fn split_commit_records(out: &str) -> impl Iterator<Item = (&str, &str)> {
891    out.split('\u{1e}').filter_map(|record| {
892        let rest = record.trim_start().strip_prefix("commit ")?;
893        let (hash, body) = rest.split_once('\n')?;
894        Some((hash.trim(), body))
895    })
896}
897
898fn parse_info(body: &str) -> Option<CommitInfo> {
899    let f: Vec<&str> = body.trim_end_matches('\n').split('\u{0}').collect();
900    if f.len() < 8 {
901        return None;
902    }
903    Some(CommitInfo {
904        author: f[0].to_string(),
905        email: f[1].to_string(),
906        date: f[2].parse().unwrap_or(0),
907        date_offset: f.get(8).and_then(|iso| {
908            // `%ai` ends `±HHMM`; the offset rides the instant for
909            // display only.
910            let tail = iso.trim().rsplit(' ').next()?;
911            let sign = match tail.as_bytes().first()? {
912                b'+' => 1i16,
913                b'-' => -1i16,
914                _ => return None,
915            };
916            let h: i16 = tail.get(1..3)?.parse().ok()?;
917            let m: i16 = tail.get(3..5)?.parse().ok()?;
918            Some(sign * (h * 60 + m))
919        }),
920        committer: f[3].to_string(),
921        subject: f[4].to_string(),
922        message: f[5].trim_end().to_string(),
923        tree: f[6].to_string(),
924        parents: f[7].split_whitespace().map(str::to_string).collect(),
925    })
926}
927
928impl AstAdapter for GitAdapter {
929    fn root(&self) -> NodeId {
930        ROOT
931    }
932
933    fn refresh(&self) {
934        GitAdapter::refresh(self);
935    }
936
937    /// `/commits/* @| [..k]` before the history is enumerated walks
938    /// k commits and no more (the pushdown scanning round,
939    /// 2026-11-06).
940    fn select(&self, from: NodeId, plan: &quarb::StepPlan<'_>) -> Option<quarb::Selection> {
941        let k = plan.limit?;
942        if from != COMMITS
943            || plan.axis != quarb::PlanAxis::Child
944            || plan.name.is_some()
945            || !plan.conjuncts.is_empty()
946            || !plan.traits.is_empty()
947            || *self.enumerated.borrow()
948        {
949            return None;
950        }
951        Some(quarb::Selection {
952            nodes: self
953                .commits_prefix(k)
954                .into_iter()
955                .map(|id| (id, 1))
956                .collect(),
957            applied: Vec::new(),
958        })
959    }
960
961    fn children(&self, node: NodeId) -> Vec<NodeId> {
962        let kind = self.nodes.borrow()[node.0 as usize].kind.clone();
963        match kind {
964            Kind::Root => {
965                // branches, tags, commits — plus HEAD as a ref
966                // alias, interned once.
967                if self.nodes.borrow()[ROOT.0 as usize]
968                    .children
969                    .borrow()
970                    .is_none()
971                {
972                    let mut ids = vec![BRANCHES, TAGS, COMMITS];
973                    if let Ok(h) = self.git(&["rev-parse", "HEAD"]) {
974                        ids.push(self.push_node(
975                            Kind::Ref {
976                                name: "HEAD".to_string(),
977                                commit: h.trim().to_string(),
978                            },
979                            Some(ROOT),
980                        ));
981                    }
982                    *self.nodes.borrow()[ROOT.0 as usize].children.borrow_mut() = Some(ids);
983                }
984                self.nodes.borrow()[ROOT.0 as usize]
985                    .children
986                    .borrow()
987                    .clone()
988                    .unwrap_or_default()
989            }
990            Kind::Dir("branches") => self.refs(BRANCHES, "refs/heads"),
991            Kind::Dir("tags") => self.refs(TAGS, "refs/tags"),
992            Kind::Dir(_) => self.enumerate_commits(),
993            Kind::Ref { commit, .. } | Kind::Commit(commit) => {
994                let Some(info) = self.commit_info(&commit) else {
995                    return Vec::new();
996                };
997                self.tree_children(node, &info.tree)
998            }
999            Kind::Entry {
1000                oid, entry_type, ..
1001            } => {
1002                if entry_type == "tree" {
1003                    self.tree_children(node, &oid)
1004                } else {
1005                    Vec::new()
1006                }
1007            }
1008        }
1009    }
1010
1011    /// Literal names under `/commits` go straight through
1012    /// `rev-parse` — unique prefixes, `HEAD~2`, `v1.0^{}` — with
1013    /// no enumeration.
1014    fn children_named(&self, node: NodeId, name: &str) -> Vec<NodeId> {
1015        if node == COMMITS {
1016            // A known full hash answers from the intern map;
1017            // anything else (prefixes, HEAD~2, tag^{}) goes
1018            // through rev-parse — enumeration never required.
1019            if let Some(&id) = self.commit_nodes.borrow().get(name) {
1020                return vec![id];
1021            }
1022            let Ok(out) = self.git(&[
1023                "rev-parse",
1024                "--verify",
1025                "--quiet",
1026                &format!("{name}^{{commit}}"),
1027            ]) else {
1028                return Vec::new();
1029            };
1030            return vec![self.commit_node(out.trim())];
1031        }
1032        self.children(node)
1033            .into_iter()
1034            .filter(|&c| self.name(c).as_deref() == Some(name))
1035            .collect()
1036    }
1037
1038    fn name(&self, node: NodeId) -> Option<String> {
1039        match &self.nodes.borrow()[node.0 as usize].kind {
1040            Kind::Root => None,
1041            Kind::Dir(d) => Some(d.to_string()),
1042            Kind::Ref { name, .. } => Some(name.clone()),
1043            Kind::Commit(h) => Some(h.clone()),
1044            Kind::Entry { name, .. } => Some(name.clone()),
1045        }
1046    }
1047
1048    fn parent(&self, node: NodeId) -> Option<NodeId> {
1049        self.nodes.borrow()[node.0 as usize].parent
1050    }
1051
1052    /// The kind first (spec: Traits): `<repository>` at the root,
1053    /// `<dir>` for a listing, then `<commit>`, `<branch>`, `<tag>`,
1054    /// `<tree>`, `<blob>`.
1055    fn traits(&self, node: NodeId) -> Vec<String> {
1056        let nodes = self.nodes.borrow();
1057        let t = match &nodes[node.0 as usize].kind {
1058            Kind::Root => "repository",
1059            Kind::Dir(_) => "dir",
1060            Kind::Commit(_) => "commit",
1061            Kind::Ref { .. } => match nodes[node.0 as usize].parent {
1062                Some(TAGS) => "tag",
1063                Some(BRANCHES) => "branch",
1064                _ => "commit",
1065            },
1066            Kind::Entry { entry_type, .. } => {
1067                let base = if entry_type == "tree" { "tree" } else { "blob" };
1068                let mut out = vec![base.to_string()];
1069                drop(nodes);
1070                // <changed>: this path is in its commit's diff
1071                // (blobs by exact path, trees when any descendant
1072                // changed).
1073                if let Some((hash, path)) = self.entry_context(node) {
1074                    let prefix = format!("{path}/");
1075                    if self
1076                        .changed_paths(&hash)
1077                        .iter()
1078                        .any(|p| *p == path || p.starts_with(&prefix))
1079                    {
1080                        out.push("changed".to_string());
1081                    }
1082                }
1083                return out;
1084            }
1085        };
1086        vec![t.to_string()]
1087    }
1088
1089    /// Commit header fields (ref aliases answer for their commit).
1090    fn property(&self, node: NodeId, name: &str) -> Option<Value> {
1091        let hash = self.commit_of(node)?;
1092        let info = self.commit_info(&hash)?;
1093        Some(match name {
1094            "author" => Value::Str(info.author),
1095            "email" => Value::Str(info.email),
1096            "date" => Value::Instant {
1097                secs: info.date,
1098                nanos: 0,
1099                offset_min: info.date_offset,
1100                calendar: Default::default(),
1101            },
1102            "committer" => Value::Str(info.committer),
1103            "subject" => Value::Str(info.subject),
1104            "message" => Value::Str(info.message),
1105            "tree" => Value::Str(info.tree),
1106            "hash" => Value::Str(hash),
1107            "parent" => Value::Str(info.parents.first()?.clone()),
1108            // The paths this commit's diff touches (vs its first
1109            // parent) — deletions included, unlike the tree view.
1110            "changed" => Value::list(
1111                self.changed_paths(&hash)
1112                    .into_iter()
1113                    .map(Value::Str)
1114                    .collect(),
1115            ),
1116            _ => return None,
1117        })
1118    }
1119
1120    /// Data provenance: the repository path as the source; the
1121    /// nearest commit-backed ancestor's author date as the instant
1122    /// (a tree entry answers "this repo, as of that commit" — the
1123    /// same instant `::date` mints). The structural dirs and the
1124    /// root have no commit ancestor and answer source only. No
1125    /// dpid — the commit hash stays on `::hash` / `:::short`.
1126    fn provenance(&self, node: NodeId) -> quarb::Provenance {
1127        let instant = self
1128            .commit_ancestor(node)
1129            .and_then(|h| self.commit_info(&h))
1130            .map(|info| (info.date, 0, info.date_offset));
1131        quarb::Provenance {
1132            source: Some(self.repo.display().to_string()),
1133            path: None,
1134            instant_from: instant.map(|_| quarb::InstantFrom::Node),
1135            instant,
1136            dpid: None,
1137        }
1138    }
1139
1140    /// A blob's content (text, lossily decoded).
1141    fn default_value(&self, node: NodeId) -> Option<Value> {
1142        let (oid, is_blob) = match &self.nodes.borrow()[node.0 as usize].kind {
1143            Kind::Entry {
1144                oid, entry_type, ..
1145            } => (oid.clone(), entry_type == "blob"),
1146            _ => return None,
1147        };
1148        if !is_blob {
1149            return None;
1150        }
1151        // The blob's bytes under the mount's rule; one that decodes
1152        // under none has no text (the leaf stays a leaf).
1153        self.blob_bytes(&oid)
1154            .ok()
1155            .and_then(|bytes| self.decoding.decode(&oid, &bytes).ok())
1156            .map(|d| Value::Str(d.text))
1157    }
1158
1159    /// Commits: `:::short`, `:::n-parents`, `:::tags`,
1160    /// `:::n-tags`. Entries: `:::type`, `:::mode`, `:::size`,
1161    /// `:::hash`.
1162    /// Ruling #29: this adapter's property surface is closed — a
1163    /// commit object cannot grow fields — so its annotations
1164    /// answer at `::` too. `hash` is in the list on purpose:
1165    /// commits expose the oid as a property and tree entries as
1166    /// metadata, but it is one concept — this node's object id —
1167    /// and aliasing is what makes `::hash` answer everywhere in
1168    /// the arbor instead of falling silently null on entries.
1169    fn aliased_metadata(&self, _node: NodeId) -> &'static [&'static str] {
1170        &[
1171            "short",
1172            "hash",
1173            "n-parents",
1174            "n-changed",
1175            "tags",
1176            "n-tags",
1177            "type",
1178            "mode",
1179            "size",
1180        ]
1181    }
1182
1183    /// The `:::` keys this adapter answers (`:meta` lists the ones
1184
1185    /// a node answers).
1186
1187    fn metadata_catalogue(&self) -> &'static [&'static str] {
1188        &[
1189            "short",
1190            "n-parents",
1191            "n-changed",
1192            "tags",
1193            "n-tags",
1194            "type",
1195            "mode",
1196            "hash",
1197            "size",
1198        ]
1199    }
1200
1201    fn metadata(&self, node: NodeId, key: &str) -> Option<Value> {
1202        if let Some(hash) = self.commit_of(node) {
1203            return match key {
1204                "short" => Some(Value::Str(hash[..7.min(hash.len())].to_string())),
1205                "n-parents" => Some(Value::Int(self.commit_info(&hash)?.parents.len() as i64)),
1206                "n-changed" => Some(Value::Int(self.changed_paths(&hash).len() as i64)),
1207                "tags" => Some(Value::list(
1208                    self.tags_at(&hash).into_iter().map(Value::Str).collect(),
1209                )),
1210                "n-tags" => Some(Value::Int(self.tags_at(&hash).len() as i64)),
1211                _ => None,
1212            };
1213        }
1214        let (oid, entry_type, mode) = match &self.nodes.borrow()[node.0 as usize].kind {
1215            Kind::Entry {
1216                oid,
1217                entry_type,
1218                mode,
1219                ..
1220            } => (oid.clone(), entry_type.clone(), mode.clone()),
1221            _ => return None,
1222        };
1223        match key {
1224            "type" => Some(Value::Str(entry_type)),
1225            "mode" => Some(Value::Str(mode)),
1226            "hash" => Some(Value::Str(oid)),
1227            "size" => self.blob_size(&oid).map(|n| Value::bytes(n as i64)),
1228            _ => None,
1229        }
1230    }
1231
1232    /// `::parent-->` — the first parent (the hint is unused: the
1233    /// target is inherently a commit).
1234    fn resolve(&self, node: NodeId, property: &str, _hint: Option<&str>) -> Option<NodeId> {
1235        if property != "parent" {
1236            return None;
1237        }
1238        let hash = self.commit_of(node)?;
1239        let first = self.commit_info(&hash)?.parents.first()?.clone();
1240        Some(self.commit_node(&first))
1241    }
1242
1243    /// A history is acyclic by its nature: a commit's parents
1244    /// precede it, so a walk over `parent` never returns (spec:
1245    /// Model Files, Acyclic links — a source that knows this of its
1246    /// own links carries the promise without a declaration).
1247    fn acyclic_link(&self, label: &str) -> Option<String> {
1248        (label == "parent")
1249            .then(|| "the commit history (a commit's parents precede it)".to_string())
1250    }
1251
1252    /// Every parent is an outgoing `parent` edge (merges fan out).
1253    fn links(&self, node: NodeId) -> Vec<(String, NodeId)> {
1254        let Some(hash) = self.commit_of(node) else {
1255            return Vec::new();
1256        };
1257        let Some(info) = self.commit_info(&hash) else {
1258            return Vec::new();
1259        };
1260        info.parents
1261            .iter()
1262            .map(|p| ("parent".to_string(), self.commit_node(p)))
1263            .collect()
1264    }
1265
1266    /// A commit's reference is its parent: the bare arrows
1267    /// (`/HEAD-->`, `/HEAD<--`) read it.
1268    fn ref_property(&self, node: NodeId) -> Option<String> {
1269        self.commit_of(node).map(|_| "parent".to_string())
1270    }
1271
1272    /// `<--(::parent)` from the enumeration, with no walk: the
1273    /// commits whose `parent` resolves here — `::parent-->` follows
1274    /// the FIRST parent, so a merge counts under its first parent
1275    /// only. Any other property has no referrers; with no property
1276    /// named the question stays the engine's.
1277    fn reverse_resolve(
1278        &self,
1279        node: NodeId,
1280        property: Option<&str>,
1281        _hint: Option<&str>,
1282    ) -> Option<Vec<NodeId>> {
1283        let hash = self.commit_of(node)?;
1284        // With no property named: the commit's reference property.
1285        if property.is_some_and(|p| p != "parent") {
1286            return Some(Vec::new());
1287        }
1288        // The index lists every child; `::parent-->` follows the
1289        // first parent, so keep the children whose first parent is
1290        // here.
1291        let children: Vec<String> = self
1292            .children_of(&hash)
1293            .into_iter()
1294            .filter(|h| {
1295                self.commit_info(h)
1296                    .is_some_and(|i| i.parents.first() == Some(&hash))
1297            })
1298            .collect();
1299        Some(children.iter().map(|h| self.commit_node(h)).collect())
1300    }
1301
1302    /// The commits whose parent is here (the children — served
1303    /// from the enumeration, so this loads the commit list).
1304    fn backlinks(&self, node: NodeId) -> Vec<(String, NodeId)> {
1305        let Some(hash) = self.commit_of(node) else {
1306            return Vec::new();
1307        };
1308        self.children_of(&hash)
1309            .into_iter()
1310            .map(|h| ("parent".to_string(), self.commit_node(&h)))
1311            .collect()
1312    }
1313}
1314
1315#[cfg(test)]
1316mod tests {
1317    use super::*;
1318
1319    // Regression: a commit whose subject and body contain the word
1320    // "commit " must not corrupt enumeration. Records are delimited
1321    // by the trailing %x1e sentinel, not by "commit " in the body.
1322    #[test]
1323    fn record_split_survives_commit_word_in_body() {
1324        let out = "commit aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n\
1325Ann\u{0}ann@example\u{0}1000\u{0}Ann\u{0}\
1326Revert commit deadbeef\u{0}\
1327Revert commit deadbeef\n\nThis reverts commit deadbeef.\u{0}\
1328tttttttttttttttttttttttttttttttttttttttt\u{0}\
1329pppppppppppppppppppppppppppppppppppppppp\u{0}\
13302026-07-15 12:00:00 +0100\u{1e}\n\
1331commit bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n\
1332Bo\u{0}bo@example\u{0}2000\u{0}Bo\u{0}second\u{0}second\u{0}\
1333tttttttttttttttttttttttttttttttttttttttt\u{0}\u{0}\
13342026-07-15 13:00:00 +0100\u{1e}\n";
1335        let recs: Vec<(&str, &str)> = split_commit_records(out).collect();
1336        assert_eq!(recs.len(), 2);
1337        assert_eq!(recs[0].0, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
1338        let a = parse_info(recs[0].1).expect("first record parses");
1339        assert_eq!(a.author, "Ann");
1340        assert_eq!(a.subject, "Revert commit deadbeef");
1341        assert_eq!(
1342            a.message,
1343            "Revert commit deadbeef\n\nThis reverts commit deadbeef."
1344        );
1345        assert_eq!(recs[1].0, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
1346        let b = parse_info(recs[1].1).expect("second record parses");
1347        assert_eq!(b.subject, "second");
1348    }
1349}