1use quarb::{AstAdapter, NodeId, Value};
39use std::cell::RefCell;
40use std::collections::HashMap;
41use std::path::PathBuf;
42
43#[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#[derive(Clone)]
54struct CommitInfo {
55 author: String,
56 email: String,
57 date: i64,
58 date_offset: Option<i16>,
61 committer: String,
62 subject: String,
63 message: String,
64 tree: String,
65 parents: Vec<String>,
66}
67
68#[derive(Clone)]
70enum Kind {
71 Root,
72 Dir(&'static str),
74 Ref {
76 name: String,
77 commit: String,
78 },
79 Commit(String),
80 Entry {
82 name: String,
83 oid: String,
84 entry_type: String, mode: String,
86 },
87}
88
89struct Node {
90 kind: Kind,
91 parent: Option<NodeId>,
92 children: RefCell<Option<Vec<NodeId>>>,
93}
94
95pub struct GitAdapter {
97 repo: PathBuf,
98 decoding: quarb::source::SourceDecoding,
101 nodes: RefCell<Vec<Node>>,
102 commits: RefCell<HashMap<String, CommitInfo>>,
103 commit_nodes: RefCell<HashMap<String, NodeId>>,
105 enumerated: RefCell<bool>,
107 changed: RefCell<HashMap<String, Vec<String>>>,
109 tag_map: RefCell<Option<HashMap<String, Vec<String>>>>,
111 children_of: RefCell<Option<HashMap<String, Vec<String>>>>,
115 blobs: RefCell<Option<Batch>>,
119 sizes: RefCell<Option<Batch>>,
120}
121
122struct 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 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 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 pub fn open(path: &std::path::Path) -> Result<Self, GitError> {
191 Self::open_with_decoding(path, quarb::source::SourceDecoding::default())
192 }
193
194 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 adapter.git(&["rev-parse", "--git-dir"])?;
237 Ok(adapter)
238 }
239
240 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
620fn 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 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 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 fn children_named(&self, node: NodeId, name: &str) -> Vec<NodeId> {
723 if node == COMMITS {
724 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 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 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 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 "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 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 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 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 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 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 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 fn ref_property(&self, node: NodeId) -> Option<String> {
946 self.commit_of(node).map(|_| "parent".to_string())
947 }
948
949 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 if property.is_some_and(|p| p != "parent") {
963 return Some(Vec::new());
964 }
965 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 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 #[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}