1use quarb::{AstAdapter, NodeId, Value};
44use std::cell::RefCell;
45use std::collections::HashMap;
46use std::path::PathBuf;
47
48#[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#[derive(Clone)]
59struct CommitInfo {
60 author: String,
61 email: String,
62 date: i64,
63 date_offset: Option<i16>,
66 committer: String,
67 subject: String,
68 message: String,
69 tree: String,
70 parents: Vec<String>,
71}
72
73#[derive(Clone)]
75enum Kind {
76 Root,
77 Dir(&'static str),
79 Ref {
81 name: String,
82 commit: String,
83 },
84 Commit(String),
85 Entry {
87 name: String,
88 oid: String,
89 entry_type: String, mode: String,
91 },
92}
93
94struct Node {
95 kind: Kind,
96 parent: Option<NodeId>,
97 children: RefCell<Option<Vec<NodeId>>>,
98}
99
100pub struct GitAdapter {
102 repo: PathBuf,
103 decoding: quarb::source::SourceDecoding,
106 nodes: RefCell<Vec<Node>>,
107 commits: RefCell<HashMap<String, CommitInfo>>,
108 frontier: RefCell<std::collections::HashSet<String>>,
111 ahead: std::cell::Cell<usize>,
113 tips: RefCell<Vec<String>>,
117 tip_at: RefCell<HashMap<String, usize>>,
118 tips_ahead: std::cell::Cell<usize>,
120 header_reads: std::cell::Cell<usize>,
123 commit_nodes: RefCell<HashMap<String, NodeId>>,
125 enumerated: RefCell<bool>,
127 changed: RefCell<HashMap<String, Vec<String>>>,
129 tag_map: RefCell<Option<HashMap<String, Vec<String>>>>,
131 children_of: RefCell<Option<HashMap<String, Vec<String>>>>,
135 blobs: RefCell<Option<Batch>>,
139 sizes: RefCell<Option<Batch>>,
140 refs_seen: RefCell<Option<String>>,
144}
145
146struct 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 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 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);
208const AHEAD_MOST: usize = 1024;
210const BRANCHES: NodeId = NodeId(1);
211const TAGS: NodeId = NodeId(2);
212const COMMITS: NodeId = NodeId(3);
213
214impl GitAdapter {
215 pub fn open(path: &std::path::Path) -> Result<Self, GitError> {
217 Self::open_with_decoding(path, quarb::source::SourceDecoding::default())
218 }
219
220 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 adapter.git(&["rev-parse", "--git-dir"])?;
270 Ok(adapter)
271 }
272
273 pub fn refresh(&self) -> bool {
296 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 _ => {
305 let moved = last.is_some();
306 *last = Some(seen);
307 drop(last);
308 self.forget_refs();
309 moved
310 }
311 }
312 }
313
314 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 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 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 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 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 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 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 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 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 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 #[doc(hidden)]
508 pub fn header_reads(&self) -> usize {
509 self.header_reads.get()
510 }
511
512 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
884fn 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 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 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 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 fn children_named(&self, node: NodeId, name: &str) -> Vec<NodeId> {
1015 if node == COMMITS {
1016 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 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 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 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 "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 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 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 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 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 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 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 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 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 fn ref_property(&self, node: NodeId) -> Option<String> {
1269 self.commit_of(node).map(|_| "parent".to_string())
1270 }
1271
1272 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 if property.is_some_and(|p| p != "parent") {
1286 return Some(Vec::new());
1287 }
1288 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 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 #[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}