grit-lib 0.5.30

Core library for the grit Git implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Lane-based graph layout (ASCII / Unicode) for commit history.

use std::collections::HashMap;

use crate::objects::ObjectId;

/// Character set for graph rendering.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GraphCharset {
    /// Marker on the commit's lane (`*` or `●`).
    pub commit: char,
    /// Vertical lane continuation.
    pub pipe: char,
    /// Merge rail angling toward a secondary parent.
    pub merge_right: char,
    /// Merge rail angling from a secondary parent.
    pub merge_left: char,
    /// Reserved for octopus merge junctions.
    pub merge_middle: char,
}

impl GraphCharset {
    /// Git-compatible ASCII glyphs.
    pub const ASCII: Self = Self {
        commit: '*',
        pipe: '|',
        merge_right: '\\',
        merge_left: '/',
        merge_middle: '.',
    };

    /// Unicode box-drawing glyphs (when the terminal supports UTF-8).
    pub const UNICODE: Self = Self {
        commit: '●',
        pipe: '│',
        merge_right: '╲',
        merge_left: '╱',
        merge_middle: '┼',
    };
}

/// One commit row fed into [`GraphLayout`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GraphCommitInput {
    /// Commit id for this row.
    pub id: ObjectId,
    /// Display parents (already rewritten); newest-first walk uses parents stored oldest-first.
    pub parents: Vec<ObjectId>,
}

/// Kind of graph line relative to a commit entry.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GraphLineKind {
    /// The line that carries the commit subject (contains the `*` marker).
    Commit,
    /// Extra graph padding before the next commit (merge rails).
    Padding,
}

/// A rendered graph prefix (two columns per lane: glyph + space), without commit text.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GraphRenderedLine {
    /// Graph prefix; always ends with a space when non-empty.
    pub prefix: String,
    /// Whether this line is the commit line or padding.
    pub kind: GraphLineKind,
}

/// Abstract lane topology for tests (column indices and parent edges).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GraphRowTopology {
    /// Column holding the commit marker for this row.
    pub commit_column: usize,
    /// Active lane indices after processing this row.
    pub active_lanes: Vec<usize>,
    /// Directed edges from child lane to parent lane for this commit.
    pub edges: Vec<(usize, usize)>,
}

/// Incremental graph layout state.
#[derive(Clone, Debug)]
pub struct GraphLayout {
    charset: GraphCharset,
    /// Each lane tracks the next commit id flowing through it.
    lanes: Vec<Option<ObjectId>>,
    width: usize,
    topologies: Vec<GraphRowTopology>,
    record_topology: bool,
}

impl Default for GraphLayout {
    fn default() -> Self {
        Self::new(GraphCharset::ASCII)
    }
}

impl GraphLayout {
    /// New layout using `charset`.
    #[must_use]
    pub fn new(charset: GraphCharset) -> Self {
        Self {
            charset,
            lanes: Vec::new(),
            width: 0,
            topologies: Vec::new(),
            record_topology: true,
        }
    }

    /// Like [`Self::new`], but skips per-row [`GraphRowTopology`] bookkeeping (used by `log
    /// --graph` production rendering; tests keep topology via [`Self::new`]).
    #[must_use]
    pub fn new_without_topology_recording(charset: GraphCharset) -> Self {
        Self {
            charset,
            lanes: Vec::new(),
            width: 0,
            topologies: Vec::new(),
            record_topology: false,
        }
    }

    /// Topologies recorded for each commit line (for unit tests).
    #[must_use]
    pub fn topologies(&self) -> &[GraphRowTopology] {
        &self.topologies
    }

    /// Current graph width in columns (excluding trailing space after the last lane).
    #[must_use]
    pub fn width(&self) -> usize {
        self.width
    }

    /// Consume commits in display order (newest first) and return graph lines grouped per commit.
    #[must_use]
    pub fn render(&mut self, commits: &[GraphCommitInput]) -> Vec<Vec<GraphRenderedLine>> {
        let mut blocks = Vec::with_capacity(commits.len());
        for commit in commits {
            blocks.push(self.render_commit(commit));
        }
        blocks
    }

    /// Render the next commit while preserving lane state across calls (full `log --graph` walk).
    #[must_use]
    pub fn render_commit(&mut self, commit: &GraphCommitInput) -> Vec<GraphRenderedLine> {
        self.render_one(commit)
    }

    fn render_one(&mut self, commit: &GraphCommitInput) -> Vec<GraphRenderedLine> {
        let parents = &commit.parents;
        let mut lines = Vec::new();

        if self.lanes_matching(commit.id) > 1 {
            let pad = self.format_convergence();
            self.width = self.width.max(pad.len());
            lines.push(GraphRenderedLine {
                prefix: pad,
                kind: GraphLineKind::Padding,
            });
            self.collapse_lanes_to(commit.id);
        }

        let commit_lane = self.find_or_open_lane(commit.id);
        let prefix = self.format_commit_row(commit_lane, parents);
        self.width = self.width.max(prefix.len());
        if self.record_topology {
            self.topologies
                .push(self.record_topology_row(commit_lane, parents));
        }
        lines.push(GraphRenderedLine {
            prefix,
            kind: GraphLineKind::Commit,
        });

        if parents.len() > 1 {
            let pad = self.format_post_merge(commit_lane);
            self.width = self.width.max(pad.len());
            lines.push(GraphRenderedLine {
                prefix: pad,
                kind: GraphLineKind::Padding,
            });
        }

        self.advance_lanes(parents, commit_lane);
        lines
    }

    fn lanes_matching(&self, id: ObjectId) -> usize {
        self.lanes.iter().filter(|slot| **slot == Some(id)).count()
    }

    fn collapse_lanes_to(&mut self, id: ObjectId) {
        let mut kept = false;
        self.lanes.retain(|slot| {
            if *slot == Some(id) {
                if kept {
                    return false;
                }
                kept = true;
                return true;
            }
            slot.is_some()
        });
        if !kept {
            self.lanes.push(Some(id));
        }
    }

    fn find_or_open_lane(&mut self, id: ObjectId) -> usize {
        if let Some(idx) = self.lanes.iter().position(|slot| *slot == Some(id)) {
            return idx;
        }
        self.lanes.push(Some(id));
        self.lanes.len() - 1
    }

    fn format_commit_row(&self, commit_lane: usize, parents: &[ObjectId]) -> String {
        let cols = self.lane_count().max(commit_lane + 1);
        let mut out = String::with_capacity(cols.saturating_mul(4));
        for lane in 0..cols {
            if lane == commit_lane {
                if parents.len() > 1 {
                    out.push(self.charset.commit);
                    out.push_str("   ");
                } else {
                    out.push(self.charset.commit);
                    out.push(' ');
                }
            } else if self.lane_active(lane) {
                out.push(self.charset.pipe);
                out.push(' ');
            } else {
                out.push_str("  ");
            }
        }
        out
    }

    fn format_post_merge(&self, commit_lane: usize) -> String {
        let cols = self.lane_count().max(commit_lane + 2);
        let mut out = String::with_capacity(cols.saturating_mul(4));
        for lane in 0..cols {
            if lane == commit_lane {
                out.push(self.charset.pipe);
                out.push(' ');
            } else if lane == commit_lane + 1 {
                out.push(self.charset.merge_right);
                out.push(' ');
            } else if self.lane_active(lane) {
                out.push(self.charset.pipe);
                out.push(' ');
            } else {
                out.push_str("  ");
            }
        }
        out
    }

    fn format_convergence(&self) -> String {
        let cols = self.lane_count();
        let mut out = String::with_capacity(cols.saturating_mul(4));
        for lane in 0..cols {
            if lane == 0 {
                out.push(self.charset.pipe);
                out.push(self.charset.merge_left);
                out.push(' ');
            } else {
                out.push_str("  ");
            }
        }
        out
    }

    fn lane_count(&self) -> usize {
        self.lanes.len()
    }

    fn lane_active(&self, lane: usize) -> bool {
        self.lanes.get(lane).is_some_and(|s| s.is_some())
    }

    fn advance_lanes(&mut self, parents: &[ObjectId], commit_lane: usize) {
        if parents.is_empty() {
            if commit_lane < self.lanes.len() {
                self.lanes[commit_lane] = None;
            }
            self.compact_lanes();
            return;
        }

        let first = parents[0];
        if commit_lane < self.lanes.len() {
            self.lanes[commit_lane] = Some(first);
        }

        for &parent in parents.iter().skip(1) {
            if self.lanes.contains(&Some(parent)) {
                continue;
            }
            if let Some(empty) = self.lanes.iter().position(|slot| slot.is_none()) {
                self.lanes[empty] = Some(parent);
            } else {
                self.lanes.push(Some(parent));
            }
        }
        self.compact_lanes();
    }

    fn compact_lanes(&mut self) {
        self.lanes.retain(|slot| slot.is_some());
    }

    fn record_topology_row(&self, commit_lane: usize, parents: &[ObjectId]) -> GraphRowTopology {
        let mut edges = Vec::new();
        let parent_to_lane: HashMap<ObjectId, usize> = self
            .lanes
            .iter()
            .enumerate()
            .filter_map(|(i, slot)| slot.map(|oid| (oid, i)))
            .collect();
        for parent in parents {
            if let Some(&parent_lane) = parent_to_lane.get(parent) {
                edges.push((commit_lane, parent_lane));
            }
        }
        let lane_len = self.lanes.len();
        GraphRowTopology {
            commit_column: commit_lane,
            active_lanes: (0..lane_len).collect(),
            edges,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::objects::ObjectId;

    fn oid(n: u8) -> ObjectId {
        ObjectId::from_bytes(&[n; 20]).expect("test oid")
    }

    fn flat_prefixes(blocks: &[Vec<GraphRenderedLine>]) -> String {
        blocks
            .iter()
            .flat_map(|b| b.iter().map(|l| l.prefix.clone()))
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn graph_layout_linear() {
        let c2 = oid(2);
        let c1 = oid(1);
        let c0 = oid(0);
        let inputs = [
            GraphCommitInput {
                id: c2,
                parents: vec![c1],
            },
            GraphCommitInput {
                id: c1,
                parents: vec![c0],
            },
            GraphCommitInput {
                id: c0,
                parents: vec![],
            },
        ];
        let mut layout = GraphLayout::new(GraphCharset::ASCII);
        let blocks = layout.render(&inputs);
        assert!(flat_prefixes(&blocks).starts_with("* "));
        assert_eq!(layout.topologies().len(), 3);
    }

    #[test]
    fn graph_layout_merge_fork() {
        let root = oid(0);
        let main = oid(1);
        let topic = oid(2);
        let merge = oid(3);
        let inputs = [
            GraphCommitInput {
                id: merge,
                parents: vec![main, topic],
            },
            GraphCommitInput {
                id: topic,
                parents: vec![root],
            },
            GraphCommitInput {
                id: main,
                parents: vec![root],
            },
            GraphCommitInput {
                id: root,
                parents: vec![],
            },
        ];
        let mut layout = GraphLayout::new(GraphCharset::ASCII);
        let blocks = layout.render(&inputs);
        let art = flat_prefixes(&blocks);
        assert!(
            art.contains('\\'),
            "merge should draw a backslash rail: {art}"
        );
        assert!(art.contains('/'), "convergence should draw slash: {art}");
        assert!(
            art.contains("| *"),
            "secondary branch should use pipe column: {art}"
        );
    }
}