diffler 0.16.1

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
//! What a [`DiffRow`] points at, named by something that survives
//! [`DiffView::ensure_rows`] rebuilding the row list: a rename, a comment
//! landing above it, a hunk changing shape. Mirrors
//! [`crate::app::status::CursorAnchor`], the same idea for the status screen.

use diffler_core::model::{DiffModel, HunkId};
use diffler_core::review::Review;
use diffler_core::session::Session;

use super::{DiffRow, DiffView};

/// The identity of the thing one [`DiffRow`] displays, in a form that
/// outlives its row index: a rebuild can move, insert before, or drop any
/// row, but the thing underneath keeps its own name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum RowRef {
    Hunk(HunkId),
    /// A line by its file's path, the number it carries on whichever side it
    /// sits on, and that side: a refresh rebuilds every hunk, but the reader
    /// is still on the same line of the same file.
    Line {
        file: String,
        line: u32,
        on_old_side: bool,
    },
    /// A stop's own row, by its position in the walkthrough's own order: a
    /// revision that reissues every stop's comment id still keeps "the same
    /// stop" at the same position, which a comment id could not.
    Stop(usize),
    Comment(String),
    /// One display line of the open composer (its header is line 0): a
    /// refresh names the caret's own row, so it lands back exactly where
    /// the reader is typing.
    Composer(usize),
    Summary,
    /// A folded hunk's row, by its hunk key.
    Fold {
        key: String,
    },
}

/// The cursor, the visual selection anchor, and the banded span, each named
/// by the [`RowRef`] it currently sits on. [`DiffView::capture_positions`]
/// takes this before something rebuilds the rows out from under them;
/// [`DiffView::restore_positions`] resolves it back afterward.
#[derive(Debug)]
pub(crate) struct RowPositions {
    cursor: Option<RowRef>,
    anchor: Option<RowRef>,
    referenced: Option<(RowRef, RowRef)>,
}

impl DiffView {
    /// Name what the cursor, the visual anchor, and the banded span
    /// currently sit on, while `self.rows` and `review` still agree with
    /// each other. A caller that is about to swap the model out from under
    /// this view (a refresh) must capture before the swap and resolve with
    /// [`Self::restore_positions`] after `ensure_rows` rebuilds against the
    /// new one, since a `RowRef` read from stale rows against an already-new
    /// model would name the wrong thing. `ensure_rows` itself calls both
    /// around its own rebuild, for every other reason rows go dirty.
    pub(crate) fn capture_positions(&self, review: &Review) -> RowPositions {
        RowPositions {
            cursor: self.row_ref(review, self.cursor),
            anchor: self.visual_anchor.and_then(|row| self.row_ref(review, row)),
            referenced: self.referenced.and_then(|(start, end)| {
                Some((self.row_ref(review, start)?, self.row_ref(review, end)?))
            }),
        }
    }

    /// Resolve `positions` (from [`Self::capture_positions`]) against the
    /// rows on screen now. The cursor falls to the nearest surviving row so
    /// the reader is never thrown to the top; a selection anchor or a
    /// banded span over something that is gone is not a selection or a span,
    /// so both simply end rather than latching onto whatever now sits at the
    /// old row index.
    pub(crate) fn restore_positions(&mut self, review: &Review, positions: RowPositions) {
        self.cursor = positions
            .cursor
            .and_then(|target| self.find_row(review, &target))
            .unwrap_or_else(|| self.cursor.min(self.rows.len().saturating_sub(1)));
        self.visual_anchor = positions
            .anchor
            .and_then(|target| self.find_row(review, &target));
        self.referenced = positions.referenced.and_then(|(start, end)| {
            Some((self.find_row(review, &start)?, self.find_row(review, &end)?))
        });
    }

    /// The identity of the thing row `row` displays, or `None` when `row` is
    /// out of range or the model can no longer answer for it.
    pub(crate) fn row_ref(&self, review: &Review, row: usize) -> Option<RowRef> {
        let session = review.session_for(&self.source);
        let model = self.model_for_rows(review);
        match *self.rows.get(row)? {
            DiffRow::Hunk { file, hunk } => Some(RowRef::Hunk(
                model.files.get(file)?.hunks.get(hunk)?.id.clone(),
            )),
            DiffRow::Line { file, hunk, line } => {
                let file = model.files.get(file)?;
                let diff_line = file.hunks.get(hunk)?.lines.get(line)?;
                let (line, on_old_side) = match diff_line.new_no {
                    Some(no) => (no, false),
                    None => (diff_line.old_no?, true),
                };
                Some(RowRef::Line {
                    file: file.path.clone(),
                    line,
                    on_old_side,
                })
            }
            DiffRow::Comment { comment, .. } => {
                let comment = session.comments.get(comment)?;
                match self.active_walkthrough(session).and_then(|walkthrough| {
                    walkthrough.stops.iter().position(|id| *id == comment.id)
                }) {
                    Some(index) => Some(RowRef::Stop(index)),
                    None => Some(RowRef::Comment(comment.id.clone())),
                }
            }
            DiffRow::Composer { line } => Some(RowRef::Composer(line)),
            DiffRow::Summary { .. } => Some(RowRef::Summary),
            DiffRow::Fold { group, .. } => Some(RowRef::Fold {
                key: self.fold_groups.get(group)?.keys.first()?.clone(),
            }),
        }
    }

    fn fold_row_leads_with(&self, row: &DiffRow, key: &str) -> bool {
        matches!(row, DiffRow::Fold { group, .. }
            if self.fold_groups.get(*group).and_then(|g| g.keys.first()).is_some_and(|k| k == key))
    }

    /// The fold row hiding line `line` of `file` on the given side.
    fn fold_row_hiding(
        &self,
        model: &DiffModel,
        file: &str,
        line: u32,
        on_old_side: bool,
    ) -> Option<usize> {
        self.rows.iter().position(|row| {
            let DiffRow::Fold { file: index, group } = *row else {
                return false;
            };
            let (Some(found), Some(fold)) = (model.files.get(index), self.fold_groups.get(group))
            else {
                return false;
            };
            found.path == file
                && fold.lines.iter().any(|&(hunk, at)| {
                    found
                        .hunks
                        .get(hunk)
                        .and_then(|hunk| hunk.lines.get(at))
                        .is_some_and(|diff_line| diff_line.number_on(on_old_side) == Some(line))
                })
        })
    }

    /// The row now holding `target`, or `None` when the thing it names is
    /// gone: a deleted comment, a hunk the model no longer carries.
    pub(crate) fn find_row(&self, review: &Review, target: &RowRef) -> Option<usize> {
        let session = review.session_for(&self.source);
        let model = self.model_for_rows(review);
        let header_of = |id: &HunkId| {
            self.rows.iter().position(|row| {
                let DiffRow::Hunk { file, hunk } = row else {
                    return false;
                };
                model
                    .files
                    .get(*file)
                    .and_then(|file| file.hunks.get(*hunk))
                    .is_some_and(|found| found.id == *id)
            })
        };
        let fold_of = |key: &str| {
            self.rows
                .iter()
                .position(|row| self.fold_row_leads_with(row, key))
        };
        // folding a hunk turns its header into its fold row and opening it
        // turns it back, so each name finds the other form of the same hunk
        match target {
            RowRef::Hunk(id) => header_of(id).or_else(|| fold_of(&id.0)),
            // a line a fold now hides is found as that fold's row, so closing
            // a fold under the cursor leaves the cursor on it
            RowRef::Line {
                file,
                line,
                on_old_side,
            } => self
                .rows
                .iter()
                .position(|row| {
                    let DiffRow::Line {
                        file: file_index,
                        hunk,
                        line: line_index,
                    } = row
                    else {
                        return false;
                    };
                    model
                        .files
                        .get(*file_index)
                        .filter(|found| found.path == *file)
                        .and_then(|found| found.hunks.get(*hunk))
                        .and_then(|hunk| hunk.lines.get(*line_index))
                        .is_some_and(|diff_line| diff_line.number_on(*on_old_side) == Some(*line))
                })
                .or_else(|| self.fold_row_hiding(&model, file, *line, *on_old_side)),
            RowRef::Stop(index) => {
                let id = self.active_walkthrough(session)?.stops.get(*index)?;
                Self::find_comment_row(&self.rows, session, id)
            }
            RowRef::Comment(id) => Self::find_comment_row(&self.rows, session, id),
            RowRef::Composer(line) => self
                .rows
                .iter()
                .position(|row| matches!(row, DiffRow::Composer { line: l } if l == line)),
            RowRef::Summary => self
                .rows
                .iter()
                .position(|row| matches!(row, DiffRow::Summary { line: 0 })),
            RowRef::Fold { key, .. } => fold_of(key).or_else(|| header_of(&HunkId(key.clone()))),
        }
    }

    /// The header row (line 0) of the comment carrying `id`, if it is on
    /// screen: the same row `seat_stop`/`focus_comment` seat the cursor on.
    fn find_comment_row(rows: &[DiffRow], session: &Session, id: &str) -> Option<usize> {
        rows.iter().position(|row| {
            matches!(row, DiffRow::Comment { comment, line: 0, .. }
                if session.comments.get(*comment).is_some_and(|c| c.id == id))
        })
    }
}

#[cfg(test)]
mod tests {
    use diffler_core::session::Anchor;

    use super::*;
    use crate::app::App;
    use crate::config::LoadedConfig;
    use crate::test_support::{key, seat_walkthrough, set_walkthrough_summary, two_hunk_fixture};

    fn unanchored(file: &str) -> Anchor {
        Anchor {
            file: file.to_owned(),
            line: None,
            line_end: None,
            on_old_side: false,
            line_text: None,
        }
    }

    fn first_row(app: &App, matches: impl Fn(&DiffRow) -> bool) -> usize {
        app.diff
            .as_ref()
            .expect("diff")
            .rows()
            .iter()
            .position(matches)
            .expect("a matching row")
    }

    #[test]
    fn row_ref_names_every_diff_row_variant_by_something_stable() {
        let fixture = two_hunk_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.author = "reviewer".to_owned();
        let comment_id = app
            .review
            .session
            .add_comment(unanchored("data.txt"), "reviewer", "why?")
            .id
            .clone();
        app.open_working_tree_file("data.txt");

        let hunk_row = first_row(&app, |row| matches!(row, DiffRow::Hunk { .. }));
        let line_row = first_row(&app, |row| matches!(row, DiffRow::Line { .. }));
        let comment_row = first_row(&app, |row| matches!(row, DiffRow::Comment { line: 0, .. }));
        app.diff.as_mut().expect("diff").cursor = line_row;
        app.handle(key('c'));
        assert!(app.composer_open(), "composer stayed open");
        let composer_row = first_row(&app, |row| matches!(row, DiffRow::Composer { .. }));

        let diff = app.diff.as_ref().expect("diff");
        let model = diff.model(&app.review);
        let file = &model.files[0];

        assert_eq!(
            diff.row_ref(&app.review, hunk_row),
            Some(RowRef::Hunk(file.hunks[0].id.clone()))
        );
        let DiffRow::Line { hunk, line, .. } = diff.rows()[line_row] else {
            panic!("line_row is a DiffRow::Line");
        };
        let diff_line = &file.hunks[hunk].lines[line];
        let expected_line = RowRef::Line {
            file: file.path.clone(),
            line: diff_line.new_no.or(diff_line.old_no).expect("a number"),
            on_old_side: diff_line.new_no.is_none(),
        };
        assert_eq!(diff.row_ref(&app.review, line_row), Some(expected_line));
        assert_eq!(
            diff.row_ref(&app.review, comment_row),
            Some(RowRef::Comment(comment_id))
        );
        let DiffRow::Composer {
            line: composer_line,
        } = diff.rows()[composer_row]
        else {
            panic!("composer_row is a DiffRow::Composer");
        };
        assert_eq!(
            diff.row_ref(&app.review, composer_row),
            Some(RowRef::Composer(composer_line))
        );
    }

    #[test]
    fn row_ref_names_a_walkthrough_stop_and_its_summary() {
        let fixture = two_hunk_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        seat_walkthrough(
            &mut app,
            "how it works",
            &[("first stop", Some("data.txt"), "look here")],
        );
        set_walkthrough_summary(&mut app, "w1", "the shape of it");
        app.open_walkthrough("w1", crate::app::diff::Slide::Summary);

        let summary_row = first_row(&app, |row| matches!(row, DiffRow::Summary { line: 0 }));
        assert_eq!(
            app.diff
                .as_ref()
                .expect("diff")
                .row_ref(&app.review, summary_row),
            Some(RowRef::Summary)
        );

        app.diff.as_mut().expect("diff").slide = Some(crate::app::diff::Slide::Stop(0));
        app.diff.as_mut().expect("diff").mark_rows_dirty();
        app.diff.as_mut().expect("diff").ensure_rows(&app.review);
        let stop_row = first_row(&app, |row| matches!(row, DiffRow::Comment { line: 0, .. }));
        assert_eq!(
            app.diff
                .as_ref()
                .expect("diff")
                .row_ref(&app.review, stop_row),
            Some(RowRef::Stop(0))
        );
    }

    #[test]
    fn round_trip_through_row_ref_and_find_row_returns_the_same_row() {
        let fixture = two_hunk_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.author = "reviewer".to_owned();
        app.review
            .session
            .add_comment(unanchored("data.txt"), "reviewer", "why?");
        app.open_working_tree_diff(None);

        let diff = app.diff.as_ref().expect("diff");
        for (row, kind) in diff.rows().iter().enumerate() {
            // a card (comment, composer, summary) is one thing across several
            // rows, so only its header round-trips to itself; the rest name
            // the same card and land back on that header, by design
            if matches!(kind, DiffRow::Comment { line, .. } if *line != 0) {
                continue;
            }
            let Some(target) = diff.row_ref(&app.review, row) else {
                continue;
            };
            assert_eq!(
                diff.find_row(&app.review, &target),
                Some(row),
                "row {row} round-trips through {target:?}"
            );
        }
    }

    /// A `RowRef` still finds the row it named after an unrelated comment
    /// lands above it and pushes every row below down.
    #[test]
    fn round_trip_still_finds_the_row_after_a_comment_lands_above_it() {
        let fixture = two_hunk_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.author = "reviewer".to_owned();
        app.open_working_tree_diff(None);

        let diff = app.diff.as_ref().expect("diff");
        let hunk_row = first_row(&app, |row| matches!(row, DiffRow::Hunk { .. }));
        let target = diff.row_ref(&app.review, hunk_row).expect("a hunk row");
        let original = diff.rows()[hunk_row];

        app.review
            .session
            .add_comment(unanchored("data.txt"), "reviewer", "look here first");
        let diff = app.diff.as_mut().expect("diff");
        diff.mark_rows_dirty();
        diff.ensure_rows(&app.review);

        let diff = app.diff.as_ref().expect("diff");
        let new_row = diff
            .find_row(&app.review, &target)
            .expect("the hunk row is still there");
        assert_ne!(new_row, hunk_row, "the new comment pushed it down");
        assert_eq!(
            diff.rows()[new_row],
            original,
            "and it's still the same row"
        );
    }

    #[test]
    fn find_row_returns_none_once_the_comment_is_gone() {
        let fixture = two_hunk_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.author = "reviewer".to_owned();
        let comment_id = app
            .review
            .session
            .add_comment(unanchored("data.txt"), "reviewer", "why?")
            .id
            .clone();
        app.open_working_tree_diff(None);
        let target = RowRef::Comment(comment_id.clone());
        assert!(
            app.diff
                .as_ref()
                .expect("diff")
                .find_row(&app.review, &target)
                .is_some(),
            "the comment starts out on screen"
        );

        app.review.session.comments.retain(|c| c.id != comment_id);
        let diff = app.diff.as_mut().expect("diff");
        diff.mark_rows_dirty();
        diff.ensure_rows(&app.review);

        assert_eq!(
            app.diff
                .as_ref()
                .expect("diff")
                .find_row(&app.review, &target),
            None
        );
    }
}