diffler 0.20.0

Standalone magit-style git TUI and code reviewer, on its own or with your coding agent
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
//! Log screen: `graph oid7 [refs] subject` rows, neogit's `l l` and `l b`
//! views.

use diffler_core::loggraph::{Cell, Lane};
use diffler_core::vcs::LogEntry;
use ratatui::Frame;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;

use crate::app::App;
use crate::app::rowsel::RowSelect;
use crate::keymap::Action;
use crate::theme::Theme;
use crate::ui::Hint;
use crate::ui::{commit_meta_spans, cursor_line, status_bar};

const HINTS: &[Hint] = &[
    Hint::Leaf(&[Action::Open], "open commit"),
    Hint::Leaf(&[Action::VisualSelect], "select range"),
    Hint::Leaf(
        &[Action::NextSection, Action::PrevSection],
        "step branch tips",
    ),
    Hint::Leaf(&[Action::Help], "help"),
];

/// Lanes past this many draw as one `…`, so a repo with dozens of open
/// branches keeps room for the subjects.
const MAX_LANES: usize = 12;

struct RowCtx<'a> {
    theme: &'a Theme,
    now: i64,
    width: u16,
    head: Option<&'a str>,
    branch: Option<&'a str>,
    remotes: &'a [String],
    /// The widest graph on screen, so every subject starts in one column.
    lanes: usize,
}

pub fn draw(frame: &mut Frame<'_>, app: &mut App) {
    let (body, bar) = super::screen_chrome(frame, app, HINTS);

    let search = app.search.as_ref();
    if let Some(log) = app.log.as_mut() {
        log.viewport = body.height;
        log.body = body;
        let height = body.height.max(1) as usize;
        log.scroll = super::scroll_to_cursor(log.cursor, log.scroll, height, log.entries.len());
        let selection = log.selection();
        let selected =
            |index: usize| selection.is_some_and(|(start, end)| index >= start && index <= end);
        let ctx = RowCtx {
            theme: &app.theme,
            now: app.now_unix,
            width: body.width,
            head: log.head.as_deref(),
            branch: app.head.branch.as_deref(),
            remotes: &log.remotes,
            lanes: log
                .graph
                .iter()
                .skip(log.scroll)
                .take(height)
                .map(Vec::len)
                .max()
                .unwrap_or(0)
                .min(MAX_LANES + 1),
        };
        let lines: Vec<Line<'static>> = log
            .entries
            .iter()
            .enumerate()
            .skip(log.scroll)
            .take(height)
            .map(|(index, entry)| {
                let ranges = search.map(|s| s.ranges_for(index)).unwrap_or_default();
                let graph = log.graph.get(index).map_or(&[][..], Vec::as_slice);
                let line = entry_line(&ctx, entry, graph, &ranges);
                if index == log.cursor || selected(index) {
                    cursor_line(line, &app.theme, body.width)
                } else {
                    line
                }
            })
            .collect();
        frame.render_widget(Paragraph::new(lines), body);
    }

    frame.render_widget(
        Paragraph::new(status_bar(app, bar.width)).style(Style::new().bg(app.theme.panel)),
        bar,
    );
}

fn entry_line(
    ctx: &RowCtx<'_>,
    entry: &LogEntry,
    graph: &[Cell],
    search: &[(std::ops::Range<usize>, bool)],
) -> Line<'static> {
    let theme = ctx.theme;
    let mut spans = vec![Span::raw(" ")];
    spans.extend(graph_spans(
        theme,
        graph,
        ctx.head == Some(entry.oid.as_str()),
    ));
    let drawn = graph.len().min(MAX_LANES + 1);
    spans.push(Span::raw("  ".repeat(ctx.lanes.saturating_sub(drawn))));
    spans.push(Span::styled(
        format!(" {} ", entry.short_id()),
        theme.dim_style(),
    ));
    spans.extend(ref_spans(ctx, entry));
    spans.extend(super::highlight_spans(
        &entry.subject,
        theme.base(),
        search,
        theme,
    ));
    let used: usize = spans.iter().map(Span::width).sum();
    spans.extend(commit_meta_spans(
        theme,
        &entry.author,
        entry.time_unix,
        ctx.now,
        used,
        ctx.width as usize,
    ));
    Line::from(spans)
}

fn lane_color(theme: &Theme, lane: Option<Lane>) -> Color {
    match lane {
        Some(Lane { head: true, .. }) => theme.accent,
        Some(Lane { id, .. }) => super::color::slot_color(theme, id + 1),
        None => theme.dim,
    }
}

/// The graph's cells, the checked-out commit's dot drawn hollow and bold.
fn graph_spans(theme: &Theme, graph: &[Cell], is_head: bool) -> Vec<Span<'static>> {
    let mut spans: Vec<Span<'static>> = Vec::new();
    for cell in graph.iter().take(MAX_LANES) {
        let mut style = Style::new()
            .fg(lane_color(theme, cell.glyph_lane))
            .bg(theme.bg);
        let glyph = if cell.glyph == '●' && is_head {
            style = style.add_modifier(Modifier::BOLD);
            '◉'
        } else {
            cell.glyph
        };
        spans.push(Span::styled(glyph.to_string(), style));
        spans.push(Span::styled(
            cell.fill.to_string(),
            Style::new()
                .fg(lane_color(theme, cell.fill_lane))
                .bg(theme.bg),
        ));
    }
    if graph.len() > MAX_LANES {
        spans.push(Span::styled("… ", theme.dim_style()));
    }
    spans
}

/// The branch checked out leads as `HEAD → name` in the accent, local
/// branches and tags follow in purple, remote branches dimmed.
fn ref_spans(ctx: &RowCtx<'_>, entry: &LogEntry) -> Vec<Span<'static>> {
    if entry.refs.is_empty() && ctx.head != Some(entry.oid.as_str()) {
        return Vec::new();
    }
    let theme = ctx.theme;
    let bracket = theme.dim_style();
    let mut names: Vec<Span<'static>> = Vec::new();
    if ctx.head == Some(entry.oid.as_str()) {
        let label = match ctx.branch.filter(|b| entry.refs.iter().any(|r| r == b)) {
            Some(branch) => format!("HEAD → {branch}"),
            None => "HEAD".to_owned(),
        };
        names.push(Span::styled(
            label,
            Style::new()
                .fg(theme.accent)
                .bg(theme.bg)
                .add_modifier(Modifier::BOLD),
        ));
    }
    for name in &entry.refs {
        if Some(name.as_str()) == ctx.branch && ctx.head == Some(entry.oid.as_str()) {
            continue;
        }
        let remote = ctx.remotes.iter().any(|remote| {
            name.strip_prefix(remote.as_str())
                .is_some_and(|rest| rest.starts_with('/'))
        });
        let style = if remote {
            theme.dim_style()
        } else {
            super::status::branch_name_style(theme)
        };
        names.push(Span::styled(name.clone(), style));
    }
    let mut spans = vec![Span::styled("[", bracket)];
    for (index, name) in names.into_iter().enumerate() {
        if index > 0 {
            spans.push(Span::styled(" ", bracket));
        }
        spans.push(name);
    }
    spans.push(Span::styled("] ", bracket));
    spans
}

#[cfg(test)]
mod tests {
    use crate::app::rowsel::RowSelect;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    use crate::app::App;
    use crate::config::LoadedConfig;
    use crate::test_support::{jj_fixture, key, mouse_click, standard_fixture};

    fn render(app: &mut App) -> Terminal<TestBackend> {
        let backend = TestBackend::new(120, 40);
        let mut terminal = Terminal::new(backend).expect("terminal");
        terminal
            .draw(|frame| crate::ui::draw(frame, app))
            .expect("draw");
        terminal
    }

    fn newest_commit(app: &App) -> i64 {
        app.log
            .as_ref()
            .unwrap()
            .entries
            .iter()
            .map(|e| e.time_unix)
            .max()
            .unwrap_or(0)
    }

    #[test]
    fn clicking_a_log_row_selects_it() {
        let fixture = standard_fixture();
        fixture.write("notes.txt", "a\n");
        fixture.commit_all("second");
        fixture.write("notes.txt", "a\nb\n");
        fixture.commit_all("third");
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.handle(key('l'));
        app.handle(key('l'));
        render(&mut app);
        assert!(app.log.as_ref().unwrap().entries.len() >= 2);
        let (body, scroll) = {
            let log = app.log.as_ref().unwrap();
            (log.body, log.scroll as u16)
        };
        app.handle(mouse_click(body.x + 1, body.y + 1 - scroll));
        assert_eq!(app.log.as_ref().unwrap().cursor, 1);
    }

    #[test]
    fn log_screen_renders_rows_with_refs_and_cursor() {
        let fixture = standard_fixture();
        fixture.write("notes.txt", "alpha\nbeta\n");
        fixture.commit_all("add beta note");
        fixture.branch("feat/topic");
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.handle(key('l'));
        app.handle(key('l'));
        app.handle(key('j'));
        app.now_unix = newest_commit(&app) + 3661;
        let terminal = render(&mut app);
        let content = terminal.backend().to_string();
        assert!(content.contains("feat/topic"), "refs decorate: {content}");
        assert!(content.contains("1h"), "commit age renders: {content}");
        insta::assert_snapshot!(terminal.backend());
    }

    #[test]
    fn a_jj_log_names_commits_by_change_id() {
        let fixture = jj_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.handle(key('l'));
        app.handle(key('l'));
        let entries = &mut app.log.as_mut().unwrap().entries;
        assert!(entries.iter().all(|e| e.change_id.is_some()));
        // jj picks random change ids, so we seat ones that snapshots can hold
        for (entry, id) in entries.iter_mut().zip(["kkmpptxz", "qpvuntsm"]) {
            entry.change_id = Some(id.to_owned());
            entry.time_unix = 1_700_000_000;
        }
        entries[0].subject = "(no description set)".to_owned();
        app.now_unix = 1_700_000_000 + 3661;
        insta::assert_snapshot!(render(&mut app).backend());
    }

    #[test]
    fn every_branch_log_draws_the_fork_and_marks_head() {
        let fixture = standard_fixture();
        fixture.branch("feature");
        fixture.checkout("feature");
        fixture.write("feature.txt", "side\n");
        fixture.commit_all_at("work on the feature", 1_700_000_100);
        fixture.checkout("main");
        fixture.write("main.txt", "trunk\n");
        fixture.commit_all_at("work on main", 1_700_000_200);
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.handle(key('l'));
        app.handle(key('b'));
        app.now_unix = newest_commit(&app) + 3661;
        let terminal = render(&mut app);
        let content = terminal.backend().to_string();
        assert!(content.contains("◉"), "HEAD's dot: {content}");
        assert!(content.contains("HEAD → main"), "{content}");
        assert!(content.contains("●─╯"), "the fork closes: {content}");
        insta::assert_snapshot!(terminal.backend());

        app.handle(key('q'));
        app.handle(key('l'));
        app.handle(key('l'));
        let current = app.log.as_ref().unwrap();
        assert!(
            current
                .entries
                .iter()
                .all(|e| e.subject != "work on the feature"),
            "l l walks HEAD's history alone"
        );
    }

    #[test]
    fn brackets_step_between_decorated_commits() {
        let fixture = standard_fixture();
        fixture.branch("old");
        fixture.write("notes.txt", "a\n");
        fixture.commit_all("second");
        fixture.write("notes.txt", "a\nb\n");
        fixture.commit_all("third");
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.handle(key('l'));
        app.handle(key('l'));
        app.handle(key(']'));
        let log = app.log.as_ref().unwrap();
        assert_eq!(log.entries[log.cursor].refs, ["old"]);
        app.handle(key('['));
        assert_eq!(app.log.as_ref().unwrap().cursor, 0);
    }

    #[test]
    fn log_visual_selection_highlights_the_range() {
        let fixture = standard_fixture();
        fixture.write("notes.txt", "alpha\nbeta\n");
        fixture.commit_all("add beta note");
        fixture.write("notes.txt", "alpha\nbeta\ngamma\n");
        fixture.commit_all("add gamma note");
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.handle(key('l'));
        app.handle(key('l'));
        // V at the top commit, then j extends the selection over two rows
        app.handle(key('V'));
        app.handle(key('j'));
        assert_eq!(app.log.as_ref().unwrap().selection(), Some((0, 1)));
        app.now_unix = newest_commit(&app) + 3661;
        let terminal = render(&mut app);
        // the two-row selection tints more cells than a bare cursor row does
        let bg = format!("{:?}", app.theme.cursor_line);
        let selected = format!("{:?}", terminal.backend().buffer())
            .matches(&bg)
            .count();
        app.log.as_mut().unwrap().visual_anchor = None;
        let unselected = format!("{:?}", render(&mut app).backend().buffer())
            .matches(&bg)
            .count();
        assert!(
            selected > unselected,
            "selection must paint extra rows: {selected} vs {unselected}"
        );
        insta::assert_snapshot!(terminal.backend());
    }

    #[test]
    fn log_scrolls_to_keep_the_cursor_visible() {
        let fixture = standard_fixture();
        for index in 0..30 {
            fixture.write("notes.txt", &format!("rev {index}\n"));
            fixture.commit_all(&format!("commit number {index}"));
        }
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.handle(key('l'));
        app.handle(key('l'));
        app.handle(key('G'));
        let backend = TestBackend::new(120, 10);
        let mut terminal = ratatui::Terminal::new(backend).expect("terminal");
        terminal
            .draw(|frame| crate::ui::draw(frame, &mut app))
            .expect("draw");
        let content = terminal.backend().to_string();
        assert!(
            content.contains("initial commit"),
            "view follows the cursor to the oldest commit: {content}"
        );
    }
}