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, cached for the adapter's lifetime. The adapter never
36//! writes.
37
38use quarb::{AstAdapter, NodeId, Value};
39use std::cell::RefCell;
40use std::collections::HashMap;
41use std::path::PathBuf;
42
43/// An error opening or reading a repository.
44#[derive(Debug, thiserror::Error)]
45pub enum GitError {
46    #[error("git: {0}")]
47    Git(String),
48    #[error("git: running git: {0}")]
49    Spawn(#[from] std::io::Error),
50}
51
52/// A commit's parsed header.
53#[derive(Clone)]
54struct CommitInfo {
55    author: String,
56    email: String,
57    date: i64,
58    /// The author date's UTC offset in minutes (from `%ai`),
59    /// preserved for display on the minted instant.
60    date_offset: Option<i16>,
61    committer: String,
62    subject: String,
63    message: String,
64    tree: String,
65    parents: Vec<String>,
66}
67
68/// What a node is.
69#[derive(Clone)]
70enum Kind {
71    Root,
72    /// `branches`, `tags`, or `commits`.
73    Dir(&'static str),
74    /// A ref (branch, tag, or HEAD): an alias for its commit.
75    Ref {
76        name: String,
77        commit: String,
78    },
79    Commit(String),
80    /// A tree entry: a subtree or a blob.
81    Entry {
82        name: String,
83        oid: String,
84        entry_type: String, // "tree" | "blob"
85        mode: String,
86    },
87}
88
89struct Node {
90    kind: Kind,
91    parent: Option<NodeId>,
92    children: RefCell<Option<Vec<NodeId>>>,
93}
94
95/// A git repository, exposed as an arbor.
96pub struct GitAdapter {
97    repo: PathBuf,
98    /// The mount's rule at the source boundary: a blob's text
99    /// decodes under it (`?encoding=`, else strict UTF-8).
100    decoding: quarb::source::SourceDecoding,
101    nodes: RefCell<Vec<Node>>,
102    commits: RefCell<HashMap<String, CommitInfo>>,
103    /// hash → its `/commits/<hash>` node.
104    commit_nodes: RefCell<HashMap<String, NodeId>>,
105    /// Whether `/commits` has been enumerated (rev-list --all).
106    enumerated: RefCell<bool>,
107    /// hash → the paths its diff (vs first parent) touches.
108    changed: RefCell<HashMap<String, Vec<String>>>,
109    /// commit hash → the tag names pointing at it (lazy).
110    tag_map: RefCell<Option<HashMap<String, Vec<String>>>>,
111    /// commit hash → the commits that list it as a parent (built
112    /// once from the enumeration; `<--` over every commit is one
113    /// pass, not one scan of the list per commit).
114    children_of: RefCell<Option<HashMap<String, Vec<String>>>>,
115    /// One `git cat-file --batch` (contents) and one `--batch-check`
116    /// (sizes) kept open: a blob per request on a pipe, not a git
117    /// process per blob.
118    blobs: RefCell<Option<Batch>>,
119    sizes: RefCell<Option<Batch>>,
120}
121
122/// A `git cat-file --batch[-check]` child on a pipe.
123struct Batch {
124    child: std::process::Child,
125    stdin: std::process::ChildStdin,
126    out: std::io::BufReader<std::process::ChildStdout>,
127}
128
129impl Batch {
130    fn spawn(repo: &std::path::Path, check: bool) -> std::io::Result<Batch> {
131        let mut child = std::process::Command::new("git")
132            .arg("-C")
133            .arg(repo)
134            .args(["cat-file", if check { "--batch-check" } else { "--batch" }])
135            .stdin(std::process::Stdio::piped())
136            .stdout(std::process::Stdio::piped())
137            .stderr(std::process::Stdio::null())
138            .spawn()?;
139        let stdin = child.stdin.take().expect("piped");
140        let out = std::io::BufReader::new(child.stdout.take().expect("piped"));
141        Ok(Batch { child, stdin, out })
142    }
143
144    /// Ask for `oid`: the header line (`<oid> <type> <size>`), or
145    /// `None` when the object is missing.
146    fn header(&mut self, oid: &str) -> std::io::Result<Option<u64>> {
147        use std::io::{BufRead, Write};
148        writeln!(self.stdin, "{oid}")?;
149        self.stdin.flush()?;
150        let mut line = String::new();
151        self.out.read_line(&mut line)?;
152        let mut parts = line.split_whitespace();
153        let _oid = parts.next();
154        match (parts.next(), parts.next()) {
155            (Some("missing"), _) | (None, _) => Ok(None),
156            (Some(_), Some(size)) => Ok(size.parse().ok()),
157            _ => Ok(None),
158        }
159    }
160
161    /// The object's bytes (after `header`, on a `--batch` child).
162    fn body(&mut self, size: u64) -> std::io::Result<Vec<u8>> {
163        use std::io::Read;
164        let mut buf = vec![0u8; size as usize];
165        self.out.read_exact(&mut buf)?;
166        let mut nl = [0u8; 1];
167        self.out.read_exact(&mut nl)?;
168        Ok(buf)
169    }
170}
171
172impl Drop for GitAdapter {
173    fn drop(&mut self) {
174        for b in [self.blobs.get_mut(), self.sizes.get_mut()] {
175            if let Some(b) = b {
176                let _ = b.child.kill();
177                let _ = b.child.wait();
178            }
179        }
180    }
181}
182
183const ROOT: NodeId = NodeId(0);
184const BRANCHES: NodeId = NodeId(1);
185const TAGS: NodeId = NodeId(2);
186const COMMITS: NodeId = NodeId(3);
187
188impl GitAdapter {
189    /// Open the repository at `path` (any directory inside it).
190    pub fn open(path: &std::path::Path) -> Result<Self, GitError> {
191        Self::open_with_decoding(path, quarb::source::SourceDecoding::default())
192    }
193
194    /// [`open`](Self::open) under a mount's source-boundary rule:
195    /// blobs decode by `?encoding=`, a byte-order mark, else strict
196    /// UTF-8 (a blob that decodes under none has no text).
197    pub fn open_with_decoding(
198        path: &std::path::Path,
199        decoding: quarb::source::SourceDecoding,
200    ) -> Result<Self, GitError> {
201        let adapter = GitAdapter {
202            repo: path.to_path_buf(),
203            decoding,
204            nodes: RefCell::new(vec![
205                Node {
206                    kind: Kind::Root,
207                    parent: None,
208                    children: RefCell::new(None),
209                },
210                Node {
211                    kind: Kind::Dir("branches"),
212                    parent: Some(ROOT),
213                    children: RefCell::new(None),
214                },
215                Node {
216                    kind: Kind::Dir("tags"),
217                    parent: Some(ROOT),
218                    children: RefCell::new(None),
219                },
220                Node {
221                    kind: Kind::Dir("commits"),
222                    parent: Some(ROOT),
223                    children: RefCell::new(None),
224                },
225            ]),
226            commits: RefCell::new(HashMap::new()),
227            commit_nodes: RefCell::new(HashMap::new()),
228            enumerated: RefCell::new(false),
229            changed: RefCell::new(HashMap::new()),
230            tag_map: RefCell::new(None),
231            children_of: RefCell::new(None),
232            blobs: RefCell::new(None),
233            sizes: RefCell::new(None),
234        };
235        // Probe: is this a repository at all?
236        adapter.git(&["rev-parse", "--git-dir"])?;
237        Ok(adapter)
238    }
239
240    /// A human-readable locator: `/commits/<short>/path`,
241    /// `/branches/<name>/path`, ...
242    pub fn locator(&self, node: NodeId) -> String {
243        let nodes = self.nodes.borrow();
244        let mut parts = Vec::new();
245        let mut cur = Some(node);
246        while let Some(n) = cur {
247            let nd = &nodes[n.0 as usize];
248            match &nd.kind {
249                Kind::Root => {}
250                Kind::Dir(d) => parts.push(d.to_string()),
251                Kind::Ref { name, .. } => parts.push(name.clone()),
252                Kind::Commit(h) => parts.push(h[..7.min(h.len())].to_string()),
253                Kind::Entry { name, .. } => parts.push(name.clone()),
254            }
255            cur = nd.parent;
256        }
257        parts.reverse();
258        format!("/{}", parts.join("/"))
259    }
260
261    /// Run git for structured output (headers, trees, refs): paths
262    /// come unquoted (`core.quotepath=off`) and the output must be
263    /// UTF-8 — the commands that print messages take
264    /// `--encoding=UTF-8`, so git transcodes a commit written in
265    /// another declared encoding. Output that still is not UTF-8
266    /// is an error, never replaced.
267    fn git(&self, args: &[&str]) -> Result<String, GitError> {
268        let out = self.git_bytes(args)?;
269        String::from_utf8(out).map_err(|e| {
270            GitError::Git(format!(
271                "git {}: output is not UTF-8 at byte {}",
272                args.first().unwrap_or(&""),
273                e.utf8_error().valid_up_to()
274            ))
275        })
276    }
277
278    /// A blob's bytes through the open `cat-file --batch` pipe; a
279    /// pipe that fails is dropped and the one-shot command answers.
280    fn blob_bytes(&self, oid: &str) -> Result<Vec<u8>, GitError> {
281        let batched = (|| -> std::io::Result<Option<Vec<u8>>> {
282            let mut slot = self.blobs.borrow_mut();
283            if slot.is_none() {
284                *slot = Some(Batch::spawn(&self.repo, false)?);
285            }
286            let b = slot.as_mut().expect("spawned");
287            match b.header(oid)? {
288                Some(size) => b.body(size).map(Some),
289                None => Ok(None),
290            }
291        })();
292        match batched {
293            Ok(Some(bytes)) => Ok(bytes),
294            Ok(None) => Err(GitError::Git(format!("blob {oid}: missing"))),
295            Err(_) => {
296                *self.blobs.borrow_mut() = None;
297                self.git_bytes(&["cat-file", "blob", oid])
298            }
299        }
300    }
301
302    /// A blob's size through the open `cat-file --batch-check` pipe,
303    /// with the same fallback.
304    fn blob_size(&self, oid: &str) -> Option<u64> {
305        let batched = (|| -> std::io::Result<Option<u64>> {
306            let mut slot = self.sizes.borrow_mut();
307            if slot.is_none() {
308                *slot = Some(Batch::spawn(&self.repo, true)?);
309            }
310            slot.as_mut().expect("spawned").header(oid)
311        })();
312        match batched {
313            Ok(size) => size,
314            Err(_) => {
315                *self.sizes.borrow_mut() = None;
316                self.git(&["cat-file", "-s", oid])
317                    .ok()
318                    .and_then(|s| s.trim().parse().ok())
319            }
320        }
321    }
322
323    /// The commits that list `hash` as a parent, from an index
324    /// built once over the enumeration.
325    fn children_of(&self, hash: &str) -> Vec<String> {
326        self.enumerate_commits();
327        if self.children_of.borrow().is_none() {
328            let mut index: HashMap<String, Vec<String>> = HashMap::new();
329            for (h, info) in self.commits.borrow().iter() {
330                for p in &info.parents {
331                    index.entry(p.clone()).or_default().push(h.clone());
332                }
333            }
334            for v in index.values_mut() {
335                v.sort();
336            }
337            *self.children_of.borrow_mut() = Some(index);
338        }
339        self.children_of
340            .borrow()
341            .as_ref()
342            .and_then(|i| i.get(hash).cloned())
343            .unwrap_or_default()
344    }
345
346    /// Run git for raw bytes (a blob): the caller decodes.
347    fn git_bytes(&self, args: &[&str]) -> Result<Vec<u8>, GitError> {
348        let out = std::process::Command::new("git")
349            .arg("-C")
350            .arg(&self.repo)
351            .args(["-c", "core.quotepath=off"])
352            .args(args)
353            .output()?;
354        if !out.status.success() {
355            return Err(GitError::Git(
356                String::from_utf8(out.stderr)
357                    .map(|s| s.trim().to_string())
358                    .unwrap_or_else(|_| "(git's message is not UTF-8)".to_string()),
359            ));
360        }
361        Ok(out.stdout)
362    }
363
364    fn push_node(&self, kind: Kind, parent: Option<NodeId>) -> NodeId {
365        let mut nodes = self.nodes.borrow_mut();
366        let id = NodeId(nodes.len() as u64);
367        nodes.push(Node {
368            kind,
369            parent,
370            children: RefCell::new(None),
371        });
372        id
373    }
374
375    /// The `/commits/<hash>` node for a full hash, interning it.
376    fn commit_node(&self, hash: &str) -> NodeId {
377        if let Some(&id) = self.commit_nodes.borrow().get(hash) {
378            return id;
379        }
380        let id = self.push_node(Kind::Commit(hash.to_string()), Some(COMMITS));
381        self.commit_nodes.borrow_mut().insert(hash.to_string(), id);
382        id
383    }
384
385    /// A commit's parsed header, fetched on first touch.
386    fn commit_info(&self, hash: &str) -> Option<CommitInfo> {
387        if let Some(i) = self.commits.borrow().get(hash) {
388            return Some(i.clone());
389        }
390        let out = self
391            .git(&[
392                "show",
393                "-s",
394                "--encoding=UTF-8",
395                "--format=%an%x00%ae%x00%at%x00%cn%x00%s%x00%B%x00%T%x00%P%x00%ai",
396                hash,
397            ])
398            .ok()?;
399        let info = parse_info(&out)?;
400        self.commits
401            .borrow_mut()
402            .insert(hash.to_string(), info.clone());
403        Some(info)
404    }
405
406    /// Enumerate every commit reachable from any ref: one
407    /// `rev-list --all` with the header format, parsed in bulk.
408    fn enumerate_commits(&self) -> Vec<NodeId> {
409        if let Some(c) = self.nodes.borrow()[COMMITS.0 as usize]
410            .children
411            .borrow()
412            .as_ref()
413        {
414            return c.clone();
415        }
416        let out = self
417            .git(&[
418                "rev-list",
419                "--encoding=UTF-8",
420                "--all",
421                "--format=%an%x00%ae%x00%at%x00%cn%x00%s%x00%B%x00%T%x00%P%x00%ai%x1e",
422            ])
423            .unwrap_or_default();
424        let mut ids = Vec::new();
425        for (hash, body) in split_commit_records(&out) {
426            if let Some(info) = parse_info(body) {
427                self.commits.borrow_mut().insert(hash.to_string(), info);
428            }
429            ids.push(self.commit_node(hash));
430        }
431        *self.enumerated.borrow_mut() = true;
432        *self.nodes.borrow()[COMMITS.0 as usize]
433            .children
434            .borrow_mut() = Some(ids.clone());
435        ids
436    }
437
438    /// The tag names pointing at `hash` (annotated tags
439    /// dereferenced), from one cached `for-each-ref` sweep.
440    fn tags_at(&self, hash: &str) -> Vec<String> {
441        if self.tag_map.borrow().is_none() {
442            let out = self
443                .git(&[
444                    "for-each-ref",
445                    "refs/tags",
446                    "--format=%(refname:short)%00%(objectname)%00%(*objectname)",
447                ])
448                .unwrap_or_default();
449            let mut map: HashMap<String, Vec<String>> = HashMap::new();
450            for line in out.lines() {
451                let mut f = line.split('\u{0}');
452                let (Some(name), Some(oid)) = (f.next(), f.next()) else {
453                    continue;
454                };
455                let peeled = f.next().filter(|p| !p.is_empty()).unwrap_or(oid);
456                map.entry(peeled.to_string())
457                    .or_default()
458                    .push(name.to_string());
459            }
460            *self.tag_map.borrow_mut() = Some(map);
461        }
462        self.tag_map
463            .borrow()
464            .as_ref()
465            .and_then(|m| m.get(hash).cloned())
466            .unwrap_or_default()
467    }
468
469    /// The refs under `refs/heads` or `refs/tags` (tags
470    /// dereferenced to their commits).
471    fn refs(&self, dir: NodeId, prefix: &str) -> Vec<NodeId> {
472        if let Some(c) = self.nodes.borrow()[dir.0 as usize]
473            .children
474            .borrow()
475            .as_ref()
476        {
477            return c.clone();
478        }
479        let out = self
480            .git(&[
481                "for-each-ref",
482                prefix,
483                "--format=%(refname:short)%00%(objectname)%00%(*objectname)",
484            ])
485            .unwrap_or_default();
486        let mut ids = Vec::new();
487        for line in out.lines() {
488            let mut f = line.split('\u{0}');
489            let (Some(name), Some(oid)) = (f.next(), f.next()) else {
490                continue;
491            };
492            let deref = f.next().unwrap_or("");
493            let commit = if deref.is_empty() { oid } else { deref };
494            ids.push(self.push_node(
495                Kind::Ref {
496                    name: name.to_string(),
497                    commit: commit.to_string(),
498                },
499                Some(dir),
500            ));
501        }
502        *self.nodes.borrow()[dir.0 as usize].children.borrow_mut() = Some(ids.clone());
503        ids
504    }
505
506    /// The entries of a tree object, as child nodes of `parent`.
507    fn tree_children(&self, parent: NodeId, tree_oid: &str) -> Vec<NodeId> {
508        if let Some(c) = self.nodes.borrow()[parent.0 as usize]
509            .children
510            .borrow()
511            .as_ref()
512        {
513            return c.clone();
514        }
515        let out = self.git(&["ls-tree", "-z", tree_oid]).unwrap_or_default();
516        let mut ids = Vec::new();
517        // "<mode> <type> <oid>\t<name>" records, NUL-terminated by
518        // `-z` so names arrive raw — never C-quoted the way the
519        // newline-delimited default renders non-ASCII paths.
520        for entry in out.split('\u{0}') {
521            let Some((meta, name)) = entry.split_once('\t') else {
522                continue;
523            };
524            let mut f = meta.split(' ');
525            let (Some(mode), Some(entry_type), Some(oid)) = (f.next(), f.next(), f.next()) else {
526                continue;
527            };
528            ids.push(self.push_node(
529                Kind::Entry {
530                    name: name.to_string(),
531                    oid: oid.to_string(),
532                    entry_type: entry_type.to_string(),
533                    mode: mode.to_string(),
534                },
535                Some(parent),
536            ));
537        }
538        *self.nodes.borrow()[parent.0 as usize].children.borrow_mut() = Some(ids.clone());
539        ids
540    }
541
542    /// The paths a commit's diff touches, relative to its first
543    /// parent (the whole tree for a root commit), computed once.
544    fn changed_paths(&self, hash: &str) -> Vec<String> {
545        if let Some(c) = self.changed.borrow().get(hash) {
546            return c.clone();
547        }
548        let out = self
549            .git(&[
550                "diff-tree",
551                "--root",
552                "--no-commit-id",
553                "--name-only",
554                "-z",
555                "-r",
556                hash,
557            ])
558            .unwrap_or_default();
559        // `-z`: NUL-separated, raw paths (never C-quoted), so they
560        // compare equal to the raw names from `ls-tree -z`.
561        let paths: Vec<String> = out
562            .split('\u{0}')
563            .filter(|p| !p.is_empty())
564            .map(str::to_string)
565            .collect();
566        self.changed
567            .borrow_mut()
568            .insert(hash.to_string(), paths.clone());
569        paths
570    }
571
572    /// The commit a tree entry belongs to and the entry's path
573    /// within it.
574    fn entry_context(&self, node: NodeId) -> Option<(String, String)> {
575        let nodes = self.nodes.borrow();
576        let mut parts = Vec::new();
577        let mut cur = Some(node);
578        while let Some(n) = cur {
579            let nd = &nodes[n.0 as usize];
580            match &nd.kind {
581                Kind::Entry { name, .. } => parts.push(name.clone()),
582                Kind::Commit(h) => {
583                    parts.reverse();
584                    return Some((h.clone(), parts.join("/")));
585                }
586                Kind::Ref { commit, .. } => {
587                    parts.reverse();
588                    return Some((commit.clone(), parts.join("/")));
589                }
590                _ => return None,
591            }
592            cur = nd.parent;
593        }
594        None
595    }
596
597    /// The commit hash a node stands for (commits and ref aliases).
598    fn commit_of(&self, node: NodeId) -> Option<String> {
599        match &self.nodes.borrow()[node.0 as usize].kind {
600            Kind::Commit(h) => Some(h.clone()),
601            Kind::Ref { commit, .. } => Some(commit.clone()),
602            _ => None,
603        }
604    }
605
606    /// The nearest commit-backed ancestor, the node itself included:
607    /// a tree entry answers through the commit it was reached under.
608    fn commit_ancestor(&self, node: NodeId) -> Option<String> {
609        let mut cur = Some(node);
610        while let Some(n) = cur {
611            if let Some(h) = self.commit_of(n) {
612                return Some(h);
613            }
614            cur = self.nodes.borrow()[n.0 as usize].parent;
615        }
616        None
617    }
618}
619
620/// Split `rev-list --format=…%x1e` output into `(hash, body)`
621/// records. Each commit's format expansion is terminated by the
622/// ASCII Record Separator (`%x1e`), so a literal `commit ` line
623/// inside a message body (`%s`/`%B`) can never split a record;
624/// the leading `commit <hash>` header of each record supplies the
625/// hash.
626fn split_commit_records(out: &str) -> impl Iterator<Item = (&str, &str)> {
627    out.split('\u{1e}').filter_map(|record| {
628        let rest = record.trim_start().strip_prefix("commit ")?;
629        let (hash, body) = rest.split_once('\n')?;
630        Some((hash.trim(), body))
631    })
632}
633
634fn parse_info(body: &str) -> Option<CommitInfo> {
635    let f: Vec<&str> = body.trim_end_matches('\n').split('\u{0}').collect();
636    if f.len() < 8 {
637        return None;
638    }
639    Some(CommitInfo {
640        author: f[0].to_string(),
641        email: f[1].to_string(),
642        date: f[2].parse().unwrap_or(0),
643        date_offset: f.get(8).and_then(|iso| {
644            // `%ai` ends `±HHMM`; the offset rides the instant for
645            // display only.
646            let tail = iso.trim().rsplit(' ').next()?;
647            let sign = match tail.as_bytes().first()? {
648                b'+' => 1i16,
649                b'-' => -1i16,
650                _ => return None,
651            };
652            let h: i16 = tail.get(1..3)?.parse().ok()?;
653            let m: i16 = tail.get(3..5)?.parse().ok()?;
654            Some(sign * (h * 60 + m))
655        }),
656        committer: f[3].to_string(),
657        subject: f[4].to_string(),
658        message: f[5].trim_end().to_string(),
659        tree: f[6].to_string(),
660        parents: f[7].split_whitespace().map(str::to_string).collect(),
661    })
662}
663
664impl AstAdapter for GitAdapter {
665    fn root(&self) -> NodeId {
666        ROOT
667    }
668
669    fn children(&self, node: NodeId) -> Vec<NodeId> {
670        let kind = self.nodes.borrow()[node.0 as usize].kind.clone();
671        match kind {
672            Kind::Root => {
673                // branches, tags, commits — plus HEAD as a ref
674                // alias, interned once.
675                if self.nodes.borrow()[ROOT.0 as usize]
676                    .children
677                    .borrow()
678                    .is_none()
679                {
680                    let mut ids = vec![BRANCHES, TAGS, COMMITS];
681                    if let Ok(h) = self.git(&["rev-parse", "HEAD"]) {
682                        ids.push(self.push_node(
683                            Kind::Ref {
684                                name: "HEAD".to_string(),
685                                commit: h.trim().to_string(),
686                            },
687                            Some(ROOT),
688                        ));
689                    }
690                    *self.nodes.borrow()[ROOT.0 as usize].children.borrow_mut() = Some(ids);
691                }
692                self.nodes.borrow()[ROOT.0 as usize]
693                    .children
694                    .borrow()
695                    .clone()
696                    .unwrap_or_default()
697            }
698            Kind::Dir("branches") => self.refs(BRANCHES, "refs/heads"),
699            Kind::Dir("tags") => self.refs(TAGS, "refs/tags"),
700            Kind::Dir(_) => self.enumerate_commits(),
701            Kind::Ref { commit, .. } | Kind::Commit(commit) => {
702                let Some(info) = self.commit_info(&commit) else {
703                    return Vec::new();
704                };
705                self.tree_children(node, &info.tree)
706            }
707            Kind::Entry {
708                oid, entry_type, ..
709            } => {
710                if entry_type == "tree" {
711                    self.tree_children(node, &oid)
712                } else {
713                    Vec::new()
714                }
715            }
716        }
717    }
718
719    /// Literal names under `/commits` go straight through
720    /// `rev-parse` — unique prefixes, `HEAD~2`, `v1.0^{}` — with
721    /// no enumeration.
722    fn children_named(&self, node: NodeId, name: &str) -> Vec<NodeId> {
723        if node == COMMITS {
724            // A known full hash answers from the intern map;
725            // anything else (prefixes, HEAD~2, tag^{}) goes
726            // through rev-parse — enumeration never required.
727            if let Some(&id) = self.commit_nodes.borrow().get(name) {
728                return vec![id];
729            }
730            let Ok(out) = self.git(&[
731                "rev-parse",
732                "--verify",
733                "--quiet",
734                &format!("{name}^{{commit}}"),
735            ]) else {
736                return Vec::new();
737            };
738            return vec![self.commit_node(out.trim())];
739        }
740        self.children(node)
741            .into_iter()
742            .filter(|&c| self.name(c).as_deref() == Some(name))
743            .collect()
744    }
745
746    fn name(&self, node: NodeId) -> Option<String> {
747        match &self.nodes.borrow()[node.0 as usize].kind {
748            Kind::Root => None,
749            Kind::Dir(d) => Some(d.to_string()),
750            Kind::Ref { name, .. } => Some(name.clone()),
751            Kind::Commit(h) => Some(h.clone()),
752            Kind::Entry { name, .. } => Some(name.clone()),
753        }
754    }
755
756    fn parent(&self, node: NodeId) -> Option<NodeId> {
757        self.nodes.borrow()[node.0 as usize].parent
758    }
759
760    /// `<commit>`, `<branch>`, `<tag>`, `<tree>`, `<blob>`.
761    fn traits(&self, node: NodeId) -> Vec<String> {
762        let nodes = self.nodes.borrow();
763        let t = match &nodes[node.0 as usize].kind {
764            Kind::Root | Kind::Dir(_) => return Vec::new(),
765            Kind::Commit(_) => "commit",
766            Kind::Ref { .. } => match nodes[node.0 as usize].parent {
767                Some(TAGS) => "tag",
768                Some(BRANCHES) => "branch",
769                _ => "commit",
770            },
771            Kind::Entry { entry_type, .. } => {
772                let base = if entry_type == "tree" { "tree" } else { "blob" };
773                let mut out = vec![base.to_string()];
774                drop(nodes);
775                // <changed>: this path is in its commit's diff
776                // (blobs by exact path, trees when any descendant
777                // changed).
778                if let Some((hash, path)) = self.entry_context(node) {
779                    let prefix = format!("{path}/");
780                    if self
781                        .changed_paths(&hash)
782                        .iter()
783                        .any(|p| *p == path || p.starts_with(&prefix))
784                    {
785                        out.push("changed".to_string());
786                    }
787                }
788                return out;
789            }
790        };
791        vec![t.to_string()]
792    }
793
794    /// Commit header fields (ref aliases answer for their commit).
795    fn property(&self, node: NodeId, name: &str) -> Option<Value> {
796        let hash = self.commit_of(node)?;
797        let info = self.commit_info(&hash)?;
798        Some(match name {
799            "author" => Value::Str(info.author),
800            "email" => Value::Str(info.email),
801            "date" => Value::Instant {
802                secs: info.date,
803                nanos: 0,
804                offset_min: info.date_offset,
805            },
806            "committer" => Value::Str(info.committer),
807            "subject" => Value::Str(info.subject),
808            "message" => Value::Str(info.message),
809            "tree" => Value::Str(info.tree),
810            "hash" => Value::Str(hash),
811            "parent" => Value::Str(info.parents.first()?.clone()),
812            // The paths this commit's diff touches (vs its first
813            // parent) — deletions included, unlike the tree view.
814            "changed" => Value::list(
815                self.changed_paths(&hash)
816                    .into_iter()
817                    .map(Value::Str)
818                    .collect(),
819            ),
820            _ => return None,
821        })
822    }
823
824    /// Data provenance: the repository path as the source; the
825    /// nearest commit-backed ancestor's author date as the instant
826    /// (a tree entry answers "this repo, as of that commit" — the
827    /// same instant `::date` mints). The structural dirs and the
828    /// root have no commit ancestor and answer source only. No
829    /// dpid — the commit hash stays on `::hash` / `::::short`.
830    fn provenance(&self, node: NodeId) -> quarb::Provenance {
831        let instant = self
832            .commit_ancestor(node)
833            .and_then(|h| self.commit_info(&h))
834            .map(|info| (info.date, 0, info.date_offset));
835        quarb::Provenance {
836            source: Some(self.repo.display().to_string()),
837            path: None,
838            instant_from: instant.map(|_| quarb::InstantFrom::Node),
839            instant,
840            dpid: None,
841        }
842    }
843
844    /// A blob's content (text, lossily decoded).
845    fn default_value(&self, node: NodeId) -> Option<Value> {
846        let (oid, is_blob) = match &self.nodes.borrow()[node.0 as usize].kind {
847            Kind::Entry {
848                oid, entry_type, ..
849            } => (oid.clone(), entry_type == "blob"),
850            _ => return None,
851        };
852        if !is_blob {
853            return None;
854        }
855        // The blob's bytes under the mount's rule; one that decodes
856        // under none has no text (the leaf stays a leaf).
857        self.blob_bytes(&oid)
858            .ok()
859            .and_then(|bytes| self.decoding.decode(&oid, &bytes).ok())
860            .map(|d| Value::Str(d.text))
861    }
862
863    /// Commits: `;;;short`, `;;;n-parents`, `;;;tags`,
864    /// `;;;n-tags`. Entries: `;;;type`, `;;;mode`, `;;;size`,
865    /// `;;;hash`.
866    /// Ruling #29: this adapter's property surface is closed — a
867    /// commit object cannot grow fields — so its annotations
868    /// answer at `::` too. `hash` is in the list on purpose:
869    /// commits expose the oid as a property and tree entries as
870    /// metadata, but it is one concept — this node's object id —
871    /// and aliasing is what makes `::hash` answer everywhere in
872    /// the arbor instead of falling silently null on entries.
873    fn aliased_metadata(&self, _node: NodeId) -> &'static [&'static str] {
874        &[
875            "short",
876            "hash",
877            "n-parents",
878            "n-changed",
879            "tags",
880            "n-tags",
881            "type",
882            "mode",
883            "size",
884        ]
885    }
886
887    fn metadata(&self, node: NodeId, key: &str) -> Option<Value> {
888        if let Some(hash) = self.commit_of(node) {
889            return match key {
890                "short" => Some(Value::Str(hash[..7.min(hash.len())].to_string())),
891                "n-parents" => Some(Value::Int(self.commit_info(&hash)?.parents.len() as i64)),
892                "n-changed" => Some(Value::Int(self.changed_paths(&hash).len() as i64)),
893                "tags" => Some(Value::list(
894                    self.tags_at(&hash).into_iter().map(Value::Str).collect(),
895                )),
896                "n-tags" => Some(Value::Int(self.tags_at(&hash).len() as i64)),
897                _ => None,
898            };
899        }
900        let (oid, entry_type, mode) = match &self.nodes.borrow()[node.0 as usize].kind {
901            Kind::Entry {
902                oid,
903                entry_type,
904                mode,
905                ..
906            } => (oid.clone(), entry_type.clone(), mode.clone()),
907            _ => return None,
908        };
909        match key {
910            "type" => Some(Value::Str(entry_type)),
911            "mode" => Some(Value::Str(mode)),
912            "hash" => Some(Value::Str(oid)),
913            "size" => self.blob_size(&oid).map(|n| Value::bytes(n as i64)),
914            _ => None,
915        }
916    }
917
918    /// `::parent-->` — the first parent (the hint is unused: the
919    /// target is inherently a commit).
920    fn resolve(&self, node: NodeId, property: &str, _hint: Option<&str>) -> Option<NodeId> {
921        if property != "parent" {
922            return None;
923        }
924        let hash = self.commit_of(node)?;
925        let first = self.commit_info(&hash)?.parents.first()?.clone();
926        Some(self.commit_node(&first))
927    }
928
929    /// Every parent is an outgoing `parent` edge (merges fan out).
930    fn links(&self, node: NodeId) -> Vec<(String, NodeId)> {
931        let Some(hash) = self.commit_of(node) else {
932            return Vec::new();
933        };
934        let Some(info) = self.commit_info(&hash) else {
935            return Vec::new();
936        };
937        info.parents
938            .iter()
939            .map(|p| ("parent".to_string(), self.commit_node(p)))
940            .collect()
941    }
942
943    /// A commit's reference is its parent: the bare arrows
944    /// (`/HEAD-->`, `/HEAD<--`) read it.
945    fn ref_property(&self, node: NodeId) -> Option<String> {
946        self.commit_of(node).map(|_| "parent".to_string())
947    }
948
949    /// `<--(::parent)` from the enumeration, with no walk: the
950    /// commits whose `parent` resolves here — `::parent-->` follows
951    /// the FIRST parent, so a merge counts under its first parent
952    /// only. Any other property has no referrers; with no property
953    /// named the question stays the engine's.
954    fn reverse_resolve(
955        &self,
956        node: NodeId,
957        property: Option<&str>,
958        _hint: Option<&str>,
959    ) -> Option<Vec<NodeId>> {
960        let hash = self.commit_of(node)?;
961        // With no property named: the commit's reference property.
962        if property.is_some_and(|p| p != "parent") {
963            return Some(Vec::new());
964        }
965        // The index lists every child; `::parent-->` follows the
966        // first parent, so keep the children whose first parent is
967        // here.
968        let children: Vec<String> = self
969            .children_of(&hash)
970            .into_iter()
971            .filter(|h| {
972                self.commit_info(h)
973                    .is_some_and(|i| i.parents.first() == Some(&hash))
974            })
975            .collect();
976        Some(children.iter().map(|h| self.commit_node(h)).collect())
977    }
978
979    /// The commits whose parent is here (the children — served
980    /// from the enumeration, so this loads the commit list).
981    fn backlinks(&self, node: NodeId) -> Vec<(String, NodeId)> {
982        let Some(hash) = self.commit_of(node) else {
983            return Vec::new();
984        };
985        self.children_of(&hash)
986            .into_iter()
987            .map(|h| ("parent".to_string(), self.commit_node(&h)))
988            .collect()
989    }
990}
991
992#[cfg(test)]
993mod tests {
994    use super::*;
995
996    // Regression: a commit whose subject and body contain the word
997    // "commit " must not corrupt enumeration. Records are delimited
998    // by the trailing %x1e sentinel, not by "commit " in the body.
999    #[test]
1000    fn record_split_survives_commit_word_in_body() {
1001        let out = "commit aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n\
1002Ann\u{0}ann@example\u{0}1000\u{0}Ann\u{0}\
1003Revert commit deadbeef\u{0}\
1004Revert commit deadbeef\n\nThis reverts commit deadbeef.\u{0}\
1005tttttttttttttttttttttttttttttttttttttttt\u{0}\
1006pppppppppppppppppppppppppppppppppppppppp\u{0}\
10072026-07-15 12:00:00 +0100\u{1e}\n\
1008commit bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n\
1009Bo\u{0}bo@example\u{0}2000\u{0}Bo\u{0}second\u{0}second\u{0}\
1010tttttttttttttttttttttttttttttttttttttttt\u{0}\u{0}\
10112026-07-15 13:00:00 +0100\u{1e}\n";
1012        let recs: Vec<(&str, &str)> = split_commit_records(out).collect();
1013        assert_eq!(recs.len(), 2);
1014        assert_eq!(recs[0].0, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
1015        let a = parse_info(recs[0].1).expect("first record parses");
1016        assert_eq!(a.author, "Ann");
1017        assert_eq!(a.subject, "Revert commit deadbeef");
1018        assert_eq!(
1019            a.message,
1020            "Revert commit deadbeef\n\nThis reverts commit deadbeef."
1021        );
1022        assert_eq!(recs[1].0, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
1023        let b = parse_info(recs[1].1).expect("second record parses");
1024        assert_eq!(b.subject, "second");
1025    }
1026}