1use std::collections::HashMap;
4
5use crate::objects::ObjectId;
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub struct GraphCharset {
10 pub commit: char,
12 pub pipe: char,
14 pub merge_right: char,
16 pub merge_left: char,
18 pub merge_middle: char,
20}
21
22impl GraphCharset {
23 pub const ASCII: Self = Self {
25 commit: '*',
26 pipe: '|',
27 merge_right: '\\',
28 merge_left: '/',
29 merge_middle: '.',
30 };
31
32 pub const UNICODE: Self = Self {
34 commit: '●',
35 pipe: '│',
36 merge_right: '╲',
37 merge_left: '╱',
38 merge_middle: '┼',
39 };
40}
41
42#[derive(Clone, Debug, PartialEq, Eq)]
44pub struct GraphCommitInput {
45 pub id: ObjectId,
47 pub parents: Vec<ObjectId>,
49}
50
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub enum GraphLineKind {
54 Commit,
56 Padding,
58}
59
60#[derive(Clone, Debug, PartialEq, Eq)]
62pub struct GraphRenderedLine {
63 pub prefix: String,
65 pub kind: GraphLineKind,
67}
68
69#[derive(Clone, Debug, PartialEq, Eq)]
71pub struct GraphRowTopology {
72 pub commit_column: usize,
74 pub active_lanes: Vec<usize>,
76 pub edges: Vec<(usize, usize)>,
78}
79
80#[derive(Clone, Debug)]
82pub struct GraphLayout {
83 charset: GraphCharset,
84 lanes: Vec<Option<ObjectId>>,
86 width: usize,
87 topologies: Vec<GraphRowTopology>,
88 record_topology: bool,
89}
90
91impl Default for GraphLayout {
92 fn default() -> Self {
93 Self::new(GraphCharset::ASCII)
94 }
95}
96
97impl GraphLayout {
98 #[must_use]
100 pub fn new(charset: GraphCharset) -> Self {
101 Self {
102 charset,
103 lanes: Vec::new(),
104 width: 0,
105 topologies: Vec::new(),
106 record_topology: true,
107 }
108 }
109
110 #[must_use]
113 pub fn new_without_topology_recording(charset: GraphCharset) -> Self {
114 Self {
115 charset,
116 lanes: Vec::new(),
117 width: 0,
118 topologies: Vec::new(),
119 record_topology: false,
120 }
121 }
122
123 #[must_use]
125 pub fn topologies(&self) -> &[GraphRowTopology] {
126 &self.topologies
127 }
128
129 #[must_use]
131 pub fn width(&self) -> usize {
132 self.width
133 }
134
135 #[must_use]
137 pub fn render(&mut self, commits: &[GraphCommitInput]) -> Vec<Vec<GraphRenderedLine>> {
138 let mut blocks = Vec::with_capacity(commits.len());
139 for commit in commits {
140 blocks.push(self.render_commit(commit));
141 }
142 blocks
143 }
144
145 #[must_use]
147 pub fn render_commit(&mut self, commit: &GraphCommitInput) -> Vec<GraphRenderedLine> {
148 self.render_one(commit)
149 }
150
151 fn render_one(&mut self, commit: &GraphCommitInput) -> Vec<GraphRenderedLine> {
152 let parents = &commit.parents;
153 let mut lines = Vec::new();
154
155 if self.lanes_matching(commit.id) > 1 {
156 let pad = self.format_convergence();
157 self.width = self.width.max(pad.len());
158 lines.push(GraphRenderedLine {
159 prefix: pad,
160 kind: GraphLineKind::Padding,
161 });
162 self.collapse_lanes_to(commit.id);
163 }
164
165 let commit_lane = self.find_or_open_lane(commit.id);
166 let prefix = self.format_commit_row(commit_lane, parents);
167 self.width = self.width.max(prefix.len());
168 if self.record_topology {
169 self.topologies
170 .push(self.record_topology_row(commit_lane, parents));
171 }
172 lines.push(GraphRenderedLine {
173 prefix,
174 kind: GraphLineKind::Commit,
175 });
176
177 if parents.len() > 1 {
178 let pad = self.format_post_merge(commit_lane);
179 self.width = self.width.max(pad.len());
180 lines.push(GraphRenderedLine {
181 prefix: pad,
182 kind: GraphLineKind::Padding,
183 });
184 }
185
186 self.advance_lanes(parents, commit_lane);
187 lines
188 }
189
190 fn lanes_matching(&self, id: ObjectId) -> usize {
191 self.lanes.iter().filter(|slot| **slot == Some(id)).count()
192 }
193
194 fn collapse_lanes_to(&mut self, id: ObjectId) {
195 let mut kept = false;
196 self.lanes.retain(|slot| {
197 if *slot == Some(id) {
198 if kept {
199 return false;
200 }
201 kept = true;
202 return true;
203 }
204 slot.is_some()
205 });
206 if !kept {
207 self.lanes.push(Some(id));
208 }
209 }
210
211 fn find_or_open_lane(&mut self, id: ObjectId) -> usize {
212 if let Some(idx) = self.lanes.iter().position(|slot| *slot == Some(id)) {
213 return idx;
214 }
215 self.lanes.push(Some(id));
216 self.lanes.len() - 1
217 }
218
219 fn format_commit_row(&self, commit_lane: usize, parents: &[ObjectId]) -> String {
220 let cols = self.lane_count().max(commit_lane + 1);
221 let mut out = String::with_capacity(cols.saturating_mul(4));
222 for lane in 0..cols {
223 if lane == commit_lane {
224 if parents.len() > 1 {
225 out.push(self.charset.commit);
226 out.push_str(" ");
227 } else {
228 out.push(self.charset.commit);
229 out.push(' ');
230 }
231 } else if self.lane_active(lane) {
232 out.push(self.charset.pipe);
233 out.push(' ');
234 } else {
235 out.push_str(" ");
236 }
237 }
238 out
239 }
240
241 fn format_post_merge(&self, commit_lane: usize) -> String {
242 let cols = self.lane_count().max(commit_lane + 2);
243 let mut out = String::with_capacity(cols.saturating_mul(4));
244 for lane in 0..cols {
245 if lane == commit_lane {
246 out.push(self.charset.pipe);
247 out.push(' ');
248 } else if lane == commit_lane + 1 {
249 out.push(self.charset.merge_right);
250 out.push(' ');
251 } else if self.lane_active(lane) {
252 out.push(self.charset.pipe);
253 out.push(' ');
254 } else {
255 out.push_str(" ");
256 }
257 }
258 out
259 }
260
261 fn format_convergence(&self) -> String {
262 let cols = self.lane_count();
263 let mut out = String::with_capacity(cols.saturating_mul(4));
264 for lane in 0..cols {
265 if lane == 0 {
266 out.push(self.charset.pipe);
267 out.push(self.charset.merge_left);
268 out.push(' ');
269 } else {
270 out.push_str(" ");
271 }
272 }
273 out
274 }
275
276 fn lane_count(&self) -> usize {
277 self.lanes.len()
278 }
279
280 fn lane_active(&self, lane: usize) -> bool {
281 self.lanes.get(lane).is_some_and(|s| s.is_some())
282 }
283
284 fn advance_lanes(&mut self, parents: &[ObjectId], commit_lane: usize) {
285 if parents.is_empty() {
286 if commit_lane < self.lanes.len() {
287 self.lanes[commit_lane] = None;
288 }
289 self.compact_lanes();
290 return;
291 }
292
293 let first = parents[0];
294 if commit_lane < self.lanes.len() {
295 self.lanes[commit_lane] = Some(first);
296 }
297
298 for &parent in parents.iter().skip(1) {
299 if self.lanes.contains(&Some(parent)) {
300 continue;
301 }
302 if let Some(empty) = self.lanes.iter().position(|slot| slot.is_none()) {
303 self.lanes[empty] = Some(parent);
304 } else {
305 self.lanes.push(Some(parent));
306 }
307 }
308 self.compact_lanes();
309 }
310
311 fn compact_lanes(&mut self) {
312 self.lanes.retain(|slot| slot.is_some());
313 }
314
315 fn record_topology_row(&self, commit_lane: usize, parents: &[ObjectId]) -> GraphRowTopology {
316 let mut edges = Vec::new();
317 let parent_to_lane: HashMap<ObjectId, usize> = self
318 .lanes
319 .iter()
320 .enumerate()
321 .filter_map(|(i, slot)| slot.map(|oid| (oid, i)))
322 .collect();
323 for parent in parents {
324 if let Some(&parent_lane) = parent_to_lane.get(parent) {
325 edges.push((commit_lane, parent_lane));
326 }
327 }
328 let lane_len = self.lanes.len();
329 GraphRowTopology {
330 commit_column: commit_lane,
331 active_lanes: (0..lane_len).collect(),
332 edges,
333 }
334 }
335}
336
337#[cfg(test)]
338mod tests {
339 use super::*;
340 use crate::objects::ObjectId;
341
342 fn oid(n: u8) -> ObjectId {
343 ObjectId::from_bytes(&[n; 20]).expect("test oid")
344 }
345
346 fn flat_prefixes(blocks: &[Vec<GraphRenderedLine>]) -> String {
347 blocks
348 .iter()
349 .flat_map(|b| b.iter().map(|l| l.prefix.clone()))
350 .collect::<Vec<_>>()
351 .join("\n")
352 }
353
354 #[test]
355 fn graph_layout_linear() {
356 let c2 = oid(2);
357 let c1 = oid(1);
358 let c0 = oid(0);
359 let inputs = [
360 GraphCommitInput {
361 id: c2,
362 parents: vec![c1],
363 },
364 GraphCommitInput {
365 id: c1,
366 parents: vec![c0],
367 },
368 GraphCommitInput {
369 id: c0,
370 parents: vec![],
371 },
372 ];
373 let mut layout = GraphLayout::new(GraphCharset::ASCII);
374 let blocks = layout.render(&inputs);
375 assert!(flat_prefixes(&blocks).starts_with("* "));
376 assert_eq!(layout.topologies().len(), 3);
377 }
378
379 #[test]
380 fn graph_layout_merge_fork() {
381 let root = oid(0);
382 let main = oid(1);
383 let topic = oid(2);
384 let merge = oid(3);
385 let inputs = [
386 GraphCommitInput {
387 id: merge,
388 parents: vec![main, topic],
389 },
390 GraphCommitInput {
391 id: topic,
392 parents: vec![root],
393 },
394 GraphCommitInput {
395 id: main,
396 parents: vec![root],
397 },
398 GraphCommitInput {
399 id: root,
400 parents: vec![],
401 },
402 ];
403 let mut layout = GraphLayout::new(GraphCharset::ASCII);
404 let blocks = layout.render(&inputs);
405 let art = flat_prefixes(&blocks);
406 assert!(
407 art.contains('\\'),
408 "merge should draw a backslash rail: {art}"
409 );
410 assert!(art.contains('/'), "convergence should draw slash: {art}");
411 assert!(
412 art.contains("| *"),
413 "secondary branch should use pipe column: {art}"
414 );
415 }
416}