//! Turning a repository's history into rows that can be drawn. //! //! The engine emits *instructions*, never pixels and never colours: a row //! index, a column, a lane number, and the line segments that cross the row. //! Choosing what a lane looks like is the frontend's business. //! //! Rows come out one at a time and only as far as they are asked for, so the //! first screenful of a very large repository is ready almost immediately. See //! [`order`] for how that is possible without walking the whole history first. mod layout; mod order; use std::collections::HashMap; use gix::ObjectId; use serde::Serialize; use crate::{Error, RefKind, Result}; use layout::ColumnLayout; use order::{CommitOrder, CommitSource, LoadedCommit}; pub use layout::{DotKind, Edge, EdgeKind}; /// A ref pointing at a commit, ready to be drawn as a badge. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct RefBadge { /// The name as a human would write it, e.g. `main` or `origin/main`. pub shorthand: String, pub kind: RefKind, /// Whether HEAD is currently on this ref. pub is_head: bool, } /// Everything needed to draw one row of the graph. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct GraphRow { pub id: String, /// Position from the top, starting at zero. pub row: u32, pub column: u16, /// An index into the frontend's lane palette, not a colour. pub lane: u16, pub dot: DotKind, /// Line segments crossing this row. pub edges: Vec, /// How many columns this row spans. pub width: u16, /// First line of the commit message. pub summary: String, pub author: String, /// Committer time, seconds since the epoch. pub time: i64, pub refs: Vec, } /// The parts of a commit that only the row needs, kept until it is emitted. #[derive(Debug, Clone)] struct Details { summary: String, author: String, } /// Reads commits and remembers the parts the row will need. /// /// Borrows only the two fields it uses so that the order, which is borrowed /// mutably at the same time, stays disjoint from it. struct Source<'a> { repository: &'a gix::Repository, details: &'a mut HashMap, } impl CommitSource for Source<'_> { type Error = Error; fn load(&mut self, id: &ObjectId) -> Result { let commit = self .repository .find_commit(*id) .map_err(|source| Error::Graph(Box::new(source)))?; let time = commit .time() .map_err(|source| Error::Graph(Box::new(source)))? .seconds; let parents: Vec = commit.parent_ids().map(|parent| parent.detach()).collect(); let summary = commit .message() .map_err(|source| Error::Graph(Box::new(source)))? .summary() .to_string(); let author = commit .author() .map_err(|source| Error::Graph(Box::new(source)))? .name .to_string(); self.details.insert(*id, Details { summary, author }); Ok(LoadedCommit { time, parents }) } } /// A lazy walk over a repository's history, producing drawable rows. pub struct GraphWalk { // Owned rather than borrowed so a walk can outlive the call that made it — // the actor holds one across many requests for more rows. Cloning a gix // repository shares the object database rather than reopening it. repository: gix::Repository, order: CommitOrder, layout: ColumnLayout, details: HashMap, refs: HashMap>, row: u32, exhausted: bool, } impl GraphWalk { pub(crate) fn new(repository: gix::Repository) -> Result { let mut walk = Self { repository, order: CommitOrder::new(), layout: ColumnLayout::new(), details: HashMap::new(), refs: HashMap::new(), row: 0, exhausted: false, }; walk.collect_refs()?; walk.seed()?; Ok(walk) } /// Whether every commit has been emitted. pub fn is_exhausted(&self) -> bool { self.exhausted } /// Whether the walk had to give up on perfect ordering. /// /// Only happens in a history skewed far beyond ordinary clock drift; the /// graph is still drawable, but some commits may sit a row or two off. pub fn is_degraded(&self) -> bool { self.order.is_degraded() } /// Take up to `limit` more rows. /// /// Returns fewer than asked for only at the end of the history. pub fn next_chunk(&mut self, limit: usize) -> Result> { let mut rows = Vec::with_capacity(limit); for _ in 0..limit { match self.next_row()? { Some(row) => rows.push(row), None => break, } } Ok(rows) } fn next_row(&mut self) -> Result> { let mut source = Source { repository: &self.repository, details: &mut self.details, }; let Some(emitted) = self.order.next(&mut source)? else { self.exhausted = true; return Ok(None); }; let placement = self.layout.place(&emitted.id, &emitted.parents); let details = self.details.remove(&emitted.id).unwrap_or_else(|| Details { summary: String::new(), author: String::new(), }); let row = GraphRow { id: emitted.id.to_string(), row: self.row, column: placement.column, lane: placement.lane, dot: placement.dot, edges: placement.edges, width: placement.width, summary: details.summary, author: details.author, time: emitted.time, refs: self.refs.get(&emitted.id).cloned().unwrap_or_default(), }; self.row += 1; Ok(Some(row)) } /// Index every ref by the commit it ultimately points at. /// /// Annotated tags are peeled here — a tag object is not a commit, and the /// badge belongs on the commit the tag wraps. fn collect_refs(&mut self) -> Result<()> { let head = self.repository.head_name().ok().flatten(); let platform = self .repository .references() .map_err(|source| Error::References(Box::new(source)))?; let iter = platform .all() .map_err(|source| Error::References(Box::new(source)))?; for reference in iter { let reference = reference.map_err(Error::References)?; let name = reference.name().as_bstr().to_string(); let shorthand = reference.name().shorten().to_string(); let is_head = head .as_ref() .is_some_and(|head| head.as_bstr() == name.as_bytes()); // A ref that will not peel to an object — a dangling symbolic ref, // say — simply gets no badge rather than failing the whole walk. let Ok(target) = reference.into_fully_peeled_id() else { continue; }; self.refs .entry(target.detach()) .or_default() .push(RefBadge { shorthand, kind: RefKind::from_full_name(&name), is_head, }); } Ok(()) } /// Start the walk from every ref, plus HEAD in case it is detached. fn seed(&mut self) -> Result<()> { let mut tips: Vec = self.refs.keys().copied().collect(); // Sorted so a repository always produces the same graph, rather than // one that depends on hash map iteration order. tips.sort_unstable(); if let Ok(head) = self.repository.head_id() { let head = head.detach(); if !tips.contains(&head) { tips.insert(0, head); } } for tip in tips { // A ref can point at a tree or a blob; those are not part of the // commit graph and are skipped rather than treated as an error. if self.repository.find_commit(tip).is_err() { continue; } let mut source = Source { repository: &self.repository, details: &mut self.details, }; self.order.seed(tip, &mut source)?; } Ok(()) } }