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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! Hunk folds in the diff pane. A folded hunk shows as its header row naming
//! what it hides, so `]`/`[` land on it folded or open. A fold is keyed by the
//! hunk's id, so a hunk the agent edits comes back open.

use std::collections::HashSet;

use diffler_core::model::{DiffLine, DiffModel, FileDiff, Hunk, LineKind};

use diffler_core::review::Review;

use super::rows::{line_row_text, thread_folds};
use super::{DiffRow, DiffView, RowCopy, SplitRow};

/// What one `DiffRow::Fold` row stands for: one folded hunk.
#[derive(Debug, Clone)]
pub(crate) struct FoldGroup {
    /// The folded hunk's key, one entry, kept as a list for the lookups that
    /// read fold identity (`RowRef::Fold`, yank, search).
    pub keys: Vec<String>,
    pub hunk: usize,
    /// Every line the row hides, in order.
    pub lines: Vec<(usize, usize)>,
    pub label: String,
}

/// The key a hunk folds under.
pub(crate) fn hunk_key(hunk: &Hunk) -> String {
    hunk.id.0.clone()
}

/// The hunk header's own text plus what folding it hides, e.g.
/// `@@ -19,7 +19,7 @@ fn helper_4() {  ⋯ 7 lines +1 -1 · 1 comment`.
pub(crate) fn fold_label(hunk: &Hunk, comments: usize) -> String {
    let added = hunk
        .lines
        .iter()
        .filter(|l| l.kind == LineKind::Added)
        .count();
    let deleted = hunk
        .lines
        .iter()
        .filter(|l| l.kind == LineKind::Deleted)
        .count();
    let ranges = format!(
        "@@ -{},{} +{},{} @@",
        hunk.old_start, hunk.old_lines, hunk.new_start, hunk.new_lines
    );
    let heading = if hunk.context.is_empty() {
        ranges
    } else {
        format!("{ranges} {}", hunk.context)
    };
    let noted = match comments {
        0 => String::new(),
        1 => " · 1 comment".to_owned(),
        n => format!(" · {n} comments"),
    };
    format!(
        "{heading}  ⋯ {} lines +{added} -{deleted}{noted}",
        hunk.lines.len()
    )
}

/// The `DiffLine`s a fold row's own `(hunk, line)` pairs point to, paired
/// with their position, for yank and search.
pub(crate) fn resolve_hidden<'a>(
    file: &'a FileDiff,
    lines: &[(usize, usize)],
) -> Vec<((usize, usize), &'a DiffLine)> {
    lines
        .iter()
        .filter_map(|&(hunk, line)| Some(((hunk, line), file.hunks.get(hunk)?.lines.get(line)?)))
        .collect()
}

/// The hidden lines as a plain-text buffer holds them, so a yank over a fold
/// row copies the code it stands for.
fn hidden_copy(file: &FileDiff, lines: &[(usize, usize)]) -> String {
    resolve_hidden(file, lines)
        .iter()
        .map(|(_, diff_line)| line_row_text(diff_line))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Replace every folded hunk of `rows` (its header and everything under it
/// up to the next header) with one `DiffRow::Fold`. An open composer's rows
/// stay on screen.
pub(crate) fn apply(
    rows: &[DiffRow],
    copy: &[RowCopy],
    model: &DiffModel,
    folded: &HashSet<String>,
) -> (Vec<DiffRow>, Vec<RowCopy>, Vec<FoldGroup>) {
    let mut out_rows = Vec::with_capacity(rows.len());
    let mut out_copy = Vec::with_capacity(copy.len());
    let mut groups = Vec::new();
    let mut i = 0;
    while i < rows.len() {
        let (Some(row), Some(text)) = (rows.get(i), copy.get(i)) else {
            break;
        };
        let folded_hunk = match *row {
            DiffRow::Hunk { file, hunk } => model
                .files
                .get(file)
                .and_then(|f| Some((f, f.hunks.get(hunk)?)))
                .filter(|(_, h)| folded.contains(&hunk_key(h)))
                .map(|(f, h)| (file, hunk, f, h)),
            _ => None,
        };
        let Some((file_index, hunk_index, file, hunk)) = folded_hunk else {
            out_rows.push(*row);
            out_copy.push(text.clone());
            i += 1;
            continue;
        };
        let end = (i + 1..rows.len())
            .find(|&j| matches!(rows.get(j), Some(DiffRow::Hunk { .. })))
            .unwrap_or(rows.len());
        let body = rows.get(i + 1..end).unwrap_or_default();
        let lines: Vec<(usize, usize)> = body
            .iter()
            .filter_map(|row| match *row {
                DiffRow::Line { hunk, line, .. } => Some((hunk, line)),
                _ => None,
            })
            .collect();
        let comments = body
            .iter()
            .filter(|row| matches!(row, DiffRow::Comment { line: 0, .. }))
            .count();
        out_rows.push(DiffRow::Fold {
            file: file_index,
            group: groups.len(),
        });
        out_copy.push(RowCopy::Text(hidden_copy(file, &lines)));
        groups.push(FoldGroup {
            keys: vec![hunk_key(hunk)],
            hunk: hunk_index,
            lines,
            label: fold_label(hunk, comments),
        });
        for j in i + 1..end {
            if let (Some(row @ DiffRow::Composer { .. }), Some(text)) = (rows.get(j), copy.get(j)) {
                out_rows.push(*row);
                out_copy.push(text.clone());
            }
        }
        i = end;
    }
    (out_rows, out_copy, groups)
}

/// The side-by-side counterpart of [`apply`]: a folded hunk's header and
/// pairs become one `SplitRow::Fold` naming that hunk.
pub(crate) fn apply_split(
    split: Vec<SplitRow>,
    file: Option<&FileDiff>,
    folded: &HashSet<String>,
) -> Vec<SplitRow> {
    let is_folded = |hunk: usize| {
        file.and_then(|f| f.hunks.get(hunk))
            .is_some_and(|h| folded.contains(&hunk_key(h)))
    };
    let mut out = Vec::with_capacity(split.len());
    let mut skipping = false;
    for row in split {
        match row {
            SplitRow::Hunk { hunk } if is_folded(hunk) => {
                skipping = true;
                out.push(SplitRow::Fold { hunk });
            }
            SplitRow::Hunk { .. } => {
                skipping = false;
                out.push(row);
            }
            SplitRow::Composer { .. } => out.push(row),
            _ if skipping => {}
            _ => out.push(row),
        }
    }
    out
}

impl DiffView {
    /// Open the hunk the fold row `group` stands for.
    pub(super) fn open_fold_group(&mut self, group: usize) -> bool {
        let Some(keys) = self.fold_groups.get(group).map(|g| g.keys.clone()) else {
            return false;
        };
        if let Some(folded) = self.folded.get_mut(&self.rows_path) {
            for key in &keys {
                folded.remove(key);
            }
        }
        self.mark_rows_dirty();
        true
    }

    /// The hunk row `row` belongs to: its own for a header or a line, and for
    /// a comment or composer row, the hunk of the line above it.
    fn hunk_of_row(&self, row: usize) -> Option<usize> {
        self.rows
            .get(..=row)?
            .iter()
            .rev()
            .find_map(|row| match *row {
                DiffRow::Hunk { hunk, .. } | DiffRow::Line { hunk, .. } => Some(hunk),
                _ => None,
            })
    }

    /// Open or close the thread of the comment under the cursor, when closing
    /// it hides something.
    pub(crate) fn toggle_thread_at_cursor(&mut self, review: &Review) -> bool {
        let Some(DiffRow::Comment { comment, .. }) = self.rows.get(self.cursor).copied() else {
            return false;
        };
        let session = review.session_for(&self.source);
        let Some(card) = session
            .comments
            .get(comment)
            .filter(|card| thread_folds(card))
        else {
            return false;
        };
        let id = card.id.clone();
        if !self.open_threads.remove(&id) {
            self.open_threads.insert(id);
        }
        self.mark_rows_dirty();
        true
    }

    /// The lines the fold row `group` hides, with their own model data.
    pub(crate) fn fold_lines<'a>(
        &self,
        file: &'a FileDiff,
        group: usize,
    ) -> Vec<((usize, usize), &'a DiffLine)> {
        let lines = self
            .fold_groups
            .get(group)
            .map_or(&[][..], |g| g.lines.as_slice());
        resolve_hidden(file, lines)
    }

    /// The code a fold row hides, one line per line and bare (no diff
    /// marker), for search to match.
    pub(crate) fn fold_text(&self, file: &FileDiff, group: usize) -> String {
        self.fold_lines(file, group)
            .iter()
            .map(|(_, diff_line)| diff_line.text.as_str())
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// `za`/`<tab>`: open the folded hunk under the cursor, or fold the hunk
    /// the cursor sits in. `false` when the cursor is in no hunk.
    pub(crate) fn toggle_fold_at_cursor(&mut self, review: &Review) -> bool {
        if let Some(DiffRow::Fold { group, .. }) = self.rows.get(self.cursor).copied() {
            return self.open_fold_group(group);
        }
        let Some(hunk) = self.hunk_of_row(self.cursor) else {
            return false;
        };
        let Some(key) = self
            .model_for_rows(review)
            .files
            .get(self.selected)
            .and_then(|file| file.hunks.get(hunk))
            .map(hunk_key)
        else {
            return false;
        };
        // the cursor goes to the header first, so the rebuild seats it on
        // the fold row that replaces it
        if let Some(header) = self
            .rows
            .iter()
            .position(|row| matches!(*row, DiffRow::Hunk { hunk: h, .. } if h == hunk))
        {
            self.cursor = header;
        }
        self.folded
            .entry(self.rows_path.clone())
            .or_default()
            .insert(key);
        self.mark_rows_dirty();
        true
    }

    /// `zR`: open every folded hunk of the file on screen. `false` when none
    /// is folded.
    pub(crate) fn open_all_folds(&mut self) -> bool {
        let opened = self
            .folded
            .remove(&self.rows_path)
            .is_some_and(|folded| !folded.is_empty());
        if opened {
            self.mark_rows_dirty();
        }
        opened
    }

    /// `zM`: fold every hunk of the file on screen. `false` when it has none.
    pub(crate) fn fold_all(&mut self, review: &Review) -> bool {
        let keys: HashSet<String> = self
            .model_for_rows(review)
            .files
            .get(self.selected)
            .map(|file| file.hunks.iter().map(hunk_key).collect())
            .unwrap_or_default();
        if keys.is_empty() {
            return false;
        }
        self.folded.insert(self.rows_path.clone(), keys);
        self.mark_rows_dirty();
        true
    }
}

#[cfg(test)]
mod tests {
    use crossterm::event::KeyCode;

    use crate::app::App;
    use crate::app::diff::{DiffRow, SplitRow};
    use crate::config::LoadedConfig;
    use crate::test_support::{Fixture, code_key, key};

    /// 30 numbered lines with `changed` edited, three hunks for 5, 15, 25.
    fn fixture(changed: &[usize]) -> Fixture {
        let content = |edited: &[usize]| -> String {
            (1..=30)
                .map(|i| {
                    if edited.contains(&i) {
                        format!("LINE {i}\n")
                    } else {
                        format!("line {i}\n")
                    }
                })
                .collect()
        };
        let fixture = Fixture::new();
        fixture.write("a.txt", &content(&[]));
        fixture.commit_all("base");
        fixture.write("a.txt", &content(changed));
        fixture
    }

    fn open(fixture: &Fixture) -> App {
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.author = "reviewer".to_owned();
        app.open_working_tree_file("a.txt");
        let diff = app.diff.as_mut().expect("diff");
        diff.focus = crate::app::diff::Pane::Diff;
        diff.ensure_rows(&app.review);
        app
    }

    fn rows(app: &App) -> Vec<DiffRow> {
        app.diff.as_ref().expect("diff").rows().to_vec()
    }

    fn cursor_row(app: &App) -> Option<DiffRow> {
        let diff = app.diff.as_ref().expect("diff");
        diff.rows().get(diff.cursor).copied()
    }

    fn headers(app: &App) -> Vec<&'static str> {
        rows(app)
            .iter()
            .filter_map(|row| match row {
                DiffRow::Hunk { .. } => Some("open"),
                DiffRow::Fold { .. } => Some("folded"),
                _ => None,
            })
            .collect()
    }

    fn labels(app: &App) -> Vec<String> {
        let diff = app.diff.as_ref().expect("diff");
        diff.fold_groups.iter().map(|g| g.label.clone()).collect()
    }

    fn press(app: &mut App, keys: &str) {
        for c in keys.chars() {
            app.handle(key(c));
        }
    }

    fn message(app: &App) -> String {
        app.message
            .as_ref()
            .map(|m| m.text.clone())
            .unwrap_or_default()
    }

    #[test]
    fn nothing_starts_folded() {
        let app = open(&fixture(&[5, 15, 25]));
        assert_eq!(headers(&app), ["open", "open", "open"]);
    }

    #[test]
    fn za_on_any_row_of_a_hunk_folds_it_to_its_header_and_opens_it_again() {
        let mut app = open(&fixture(&[5, 15, 25]));
        press(&mut app, "]j");
        assert!(matches!(cursor_row(&app), Some(DiffRow::Line { .. })));
        press(&mut app, "za");
        assert_eq!(headers(&app), ["open", "folded", "open"]);
        assert!(
            matches!(cursor_row(&app), Some(DiffRow::Fold { .. })),
            "the cursor lands on the folded header"
        );
        assert_eq!(labels(&app), ["@@ -12,7 +12,7 @@ line 11  ⋯ 8 lines +1 -1"]);

        press(&mut app, "za");
        assert_eq!(headers(&app), ["open", "open", "open"]);
        assert!(matches!(cursor_row(&app), Some(DiffRow::Hunk { .. })));
    }

    #[test]
    fn brackets_step_over_folded_and_open_hunks_alike() {
        let mut app = open(&fixture(&[5, 15, 25]));
        press(&mut app, "zM");
        assert_eq!(headers(&app), ["folded", "folded", "folded"]);
        app.diff.as_mut().expect("diff").cursor = 0;
        press(&mut app, "]");
        let diff = app.diff.as_ref().expect("diff");
        assert_eq!(diff.cursor, 1, "{:?}", rows(&app));
        press(&mut app, "]za");
        assert_eq!(headers(&app), ["folded", "folded", "open"]);
    }

    #[test]
    fn z_m_folds_every_hunk_and_z_r_opens_them() {
        let mut app = open(&fixture(&[5, 15, 25]));
        press(&mut app, "zM");
        assert_eq!(headers(&app), ["folded", "folded", "folded"]);
        assert_eq!(message(&app), "folded every hunk");
        press(&mut app, "zR");
        assert_eq!(headers(&app), ["open", "open", "open"]);
        assert_eq!(message(&app), "opened every hunk");
        press(&mut app, "zR");
        assert_eq!(message(&app), "no hunk is folded");
    }

    #[test]
    fn a_folded_hunk_counts_the_comments_it_hides() {
        let fixture = fixture(&[5]);
        let mut app = open(&fixture);
        let anchor = diffler_core::session::Anchor {
            file: "a.txt".to_owned(),
            line: Some(5),
            line_end: None,
            on_old_side: false,
            line_text: None,
        };
        app.review.session.add_comment(anchor, "reviewer", "why?");
        let diff = app.diff.as_mut().expect("diff");
        diff.mark_rows_dirty();
        diff.ensure_rows(&app.review);
        diff.cursor = 0;
        press(&mut app, "za");
        assert_eq!(
            labels(&app),
            ["@@ -2,7 +2,7 @@ line 1  ⋯ 8 lines +1 -1 · 1 comment"]
        );
    }

    #[test]
    fn a_search_opens_the_folded_hunk_holding_its_match() {
        let mut app = open(&fixture(&[5, 15, 25]));
        press(&mut app, "zM");
        app.diff.as_mut().expect("diff").cursor = 0;
        press(&mut app, "/LINE 15");
        app.handle(code_key(KeyCode::Enter));
        assert_eq!(headers(&app), ["folded", "open", "folded"]);
    }

    #[test]
    fn a_hunk_edited_after_folding_comes_back_open() {
        let fixture = fixture(&[5, 15]);
        let mut app = open(&fixture);
        press(&mut app, "zM");
        fixture.write(
            "a.txt",
            &(1..=30)
                .map(|i| match i {
                    5 | 15 => format!("LINE {i}\n"),
                    14 => "edited 14\n".to_owned(),
                    _ => format!("line {i}\n"),
                })
                .collect::<String>(),
        );
        app.handle(crate::event::AppEvent::RepoChanged);
        app.settle_refresh();
        app.diff.as_mut().expect("diff").ensure_rows(&app.review);
        assert_eq!(headers(&app), ["folded", "open"]);
    }

    #[test]
    fn side_by_side_folds_the_same_hunks() {
        let mut app = open(&fixture(&[5, 15]));
        press(&mut app, "]za");
        app.handle(key('|'));
        let diff = app.diff.as_ref().expect("diff");
        let kinds: Vec<&str> = diff
            .split_rows
            .iter()
            .filter_map(|row| match row {
                SplitRow::Hunk { .. } => Some("open"),
                SplitRow::Fold { .. } => Some("folded"),
                _ => None,
            })
            .collect();
        assert_eq!(kinds, ["open", "folded"]);
    }
}