diffler-core 0.19.1

Core review engine for diffler: diffs, sessions, comments, viewed marks
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
//! The agent's reading order for a review. A stop is an agent comment with a
//! title and an anchor. A walkthrough is its own review source, so every
//! comment in that source's session belongs to it.

use serde::{Deserialize, Serialize};

use crate::session::Comment;
use crate::source::ReviewSource;
use crate::syntax::registry::REGISTRY;

/// A cap against dumping the whole diff; real walkthroughs stay well under.
pub const MAX_STOPS: usize = 20;
pub const BODY_MAX_BYTES: usize = 8 * 1024;
pub const TOTAL_MAX_BYTES: usize = 64 * 1024;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Walkthrough {
    pub id: String,
    pub title: String,
    pub author: String,
    pub at: u64,
    /// The comment ids of the stops, in reading order.
    pub stops: Vec<String>,
    /// One line on what the agent left out and why.
    #[serde(default)]
    pub skipped: Option<String>,
    /// Markdown overview, shown as the sidebar's leading slide.
    #[serde(default)]
    pub summary: Option<String>,
    /// Full oid of `HEAD` at publish time, so anchors resolve against the code
    /// they describe after the checkout moves. `None` resolves against the
    /// worktree.
    #[serde(default)]
    pub rev: Option<String>,
    /// The review this walkthrough describes; its diff is what stops resolve
    /// against.
    #[serde(default)]
    pub about: ReviewSource,
}

impl Walkthrough {
    /// The note ids of each stop, in stop order. A note is a titleless comment
    /// with an `anchor_ref` inside a stop's region; it goes to the first stop
    /// that holds it.
    pub fn notes_by_stop(&self, comments: &[Comment]) -> Vec<Vec<String>> {
        let mut groups: Vec<Vec<String>> = self.stops.iter().map(|_| Vec::new()).collect();
        for comment in comments {
            if comment.title.is_some()
                || comment.anchor_ref.is_none()
                || self.stops.contains(&comment.id)
            {
                continue;
            }
            let region = self.stops.iter().position(|stop_id| {
                comments
                    .iter()
                    .find(|c| c.id == *stop_id)
                    .is_some_and(|stop| region_contains(&stop.anchor, &comment.anchor))
            });
            if let Some(group) = region.and_then(|index| groups.get_mut(index)) {
                group.push(comment.id.clone());
            }
        }
        groups
    }
}

/// Whether `other`'s line (or line end) falls inside `region`'s span, on the
/// same file and side. Two file-level anchors match.
pub(crate) fn region_contains(
    region: &crate::session::Anchor,
    other: &crate::session::Anchor,
) -> bool {
    if region.file != other.file || region.on_old_side != other.on_old_side {
        return false;
    }
    match (region.span(), other.line_end.or(other.line)) {
        (Some((start, end)), Some(at)) => start <= at && at <= end,
        (None, None) => true,
        (Some(_), None) | (None, Some(_)) => false,
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReceiptCode {
    TooManyStops,
    EmptyStops,
    BodyTooLong,
    TotalTooLong,
    AnchorUnparsed,
    /// A stop's anchor names a file neither in the diff nor on disk.
    AnchorFileMissing,
    /// No stop names a file and the diff is empty.
    NothingToAnchor,
    NoteOutsideStop,
    DuplicateId,
}

impl ReceiptCode {
    /// The serde wire name.
    pub fn name(self) -> &'static str {
        match self {
            Self::TooManyStops => "too_many_stops",
            Self::EmptyStops => "empty_stops",
            Self::BodyTooLong => "body_too_long",
            Self::TotalTooLong => "total_too_long",
            Self::AnchorUnparsed => "anchor_unparsed",
            Self::AnchorFileMissing => "anchor_file_missing",
            Self::NothingToAnchor => "nothing_to_anchor",
            Self::NoteOutsideStop => "note_outside_stop",
            Self::DuplicateId => "duplicate_id",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Receipt {
    pub stop: Option<usize>,
    pub code: ReceiptCode,
    pub detail: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Located {
    /// 1-based inclusive rows; a single line is a span of one.
    Found {
        line: u32,
        end: u32,
    },
    Whole,
    /// The file was read, but the symbol or line is gone from it.
    Lost,
    /// The file could not be read at all.
    FileMissing,
}

/// Where a figure's node or a stop's anchor points. We resolve it at draw
/// time so it follows the code after an edit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Target {
    /// `path#symbol`, resolved through the file's definition spans.
    Symbol {
        path: String,
        symbol: String,
    },
    /// `path:line` or `path:start-end`, 1-based and inclusive.
    Line {
        path: String,
        line: u32,
        end: u32,
    },
    File {
        path: String,
    },
}

impl Target {
    /// `#` wins over `:`, and both win over a bare path, so a file whose name
    /// contains either is unaddressable.
    pub fn parse(raw: &str) -> Self {
        let raw = raw.trim();
        if let Some((path, symbol)) = raw.split_once('#')
            && !symbol.is_empty()
        {
            return Self::Symbol {
                path: path.to_owned(),
                symbol: symbol.to_owned(),
            };
        }
        if let Some((path, rows)) = raw.rsplit_once(':')
            && let Some((line, end)) = parse_rows(rows)
        {
            return Self::Line {
                path: path.to_owned(),
                line,
                end,
            };
        }
        Self::File {
            path: raw.to_owned(),
        }
    }

    pub fn path(&self) -> &str {
        match self {
            Self::Symbol { path, .. } | Self::Line { path, .. } | Self::File { path } => path,
        }
    }

    pub fn locate(&self, content: &str) -> Located {
        let rows = content.lines().count();
        match self {
            Self::File { .. } => Located::Whole,
            Self::Line { line, end, .. } => {
                if (*line as usize) <= rows {
                    Located::Found {
                        line: *line,
                        end: (*end).min(u32::try_from(rows).unwrap_or(*end)).max(*line),
                    }
                } else {
                    Located::Lost
                }
            }
            Self::Symbol { path, symbol } => REGISTRY
                .scope_index(path, content)
                .def_span(symbol)
                .and_then(|(start, end)| {
                    Some(Located::Found {
                        line: u32::try_from(start + 1).ok()?,
                        end: u32::try_from(end + 1).ok()?,
                    })
                })
                .unwrap_or(Located::Lost),
        }
    }
}

/// `12` or `12-40`, 1-based and inclusive. A reversed end collapses to the
/// start.
fn parse_rows(raw: &str) -> Option<(u32, u32)> {
    let (start, end) = raw.split_once('-').unwrap_or((raw, raw));
    let start = start.parse::<u32>().ok().filter(|line| *line > 0)?;
    let end = end.parse::<u32>().ok().filter(|line| *line > 0)?;
    Some((start, end.max(start)))
}

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

    #[test]
    fn receipt_code_name_matches_its_wire_name() {
        for code in [
            ReceiptCode::TooManyStops,
            ReceiptCode::EmptyStops,
            ReceiptCode::BodyTooLong,
            ReceiptCode::TotalTooLong,
            ReceiptCode::AnchorUnparsed,
            ReceiptCode::AnchorFileMissing,
            ReceiptCode::NothingToAnchor,
            ReceiptCode::NoteOutsideStop,
            ReceiptCode::DuplicateId,
        ] {
            let wire = serde_json::to_value(code).expect("a unit enum always serializes");
            assert_eq!(wire, serde_json::json!(code.name()));
        }
    }

    #[test]
    fn walkthrough_serializes_round_trip() {
        let w = Walkthrough {
            id: "w1".to_owned(),
            title: "tour".to_owned(),
            author: "agent".to_owned(),
            at: 1,
            stops: vec!["c1".to_owned(), "c2".to_owned()],
            skipped: Some("the tests".to_owned()),
            summary: Some("what changed".to_owned()),
            rev: Some("deadbeef".to_owned()),
            about: ReviewSource::pr(7),
        };
        let json = serde_json::to_string(&w).expect("serialize");
        let back: Walkthrough = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(w, back);
    }

    #[test]
    fn a_walkthrough_with_no_rev_field_deserializes_to_none() {
        let json = r#"{"id":"w1","title":"tour","author":"agent","at":1,"stops":["c1"]}"#;
        let w: Walkthrough = serde_json::from_str(json).expect("deserialize");
        assert_eq!(w.rev, None);
    }

    #[test]
    fn a_walkthrough_with_no_about_field_deserializes_to_the_working_tree() {
        let json = r#"{"id":"w1","title":"tour","author":"agent","at":1,"stops":["c1"]}"#;
        let w: Walkthrough = serde_json::from_str(json).expect("deserialize");
        assert_eq!(w.about, ReviewSource::WorkingTree);
    }

    fn stop(id: &str, file: &str, line: u32) -> Comment {
        use crate::session::{Anchor, CommentStatus};
        Comment {
            id: id.to_owned(),
            author: "agent".to_owned(),
            remote_id: None,
            thread_id: None,
            anchor: Anchor {
                file: file.to_owned(),
                line: Some(line),
                line_end: None,
                on_old_side: false,
                line_text: None,
            },
            title: Some(id.to_owned()),
            anchor_ref: Some(format!("{file}:{line}")),
            body: "why".to_owned(),
            status: CommentStatus::Open,
            replies: Vec::new(),
            at: 1,
        }
    }

    fn note(id: &str, file: &str, line: u32) -> Comment {
        Comment {
            title: None,
            ..stop(id, file, line)
        }
    }

    #[test]
    fn notes_group_under_the_stop_whose_region_holds_them() {
        let w = Walkthrough {
            id: "w1".to_owned(),
            title: "tour".to_owned(),
            author: "agent".to_owned(),
            at: 1,
            stops: vec!["c1".to_owned(), "c2".to_owned()],
            skipped: None,
            summary: None,
            rev: None,
            about: ReviewSource::WorkingTree,
        };
        let comments = vec![
            stop("c1", "a.txt", 1),
            note("n1", "a.txt", 1),
            note("n2", "a.txt", 1),
            stop("c2", "b.txt", 1),
        ];
        assert_eq!(
            w.notes_by_stop(&comments),
            vec![vec!["n1".to_owned(), "n2".to_owned()], Vec::new()]
        );
    }

    #[test]
    fn a_human_comment_in_a_stops_region_is_never_counted_as_a_note() {
        let w = Walkthrough {
            id: "w1".to_owned(),
            title: "tour".to_owned(),
            author: "agent".to_owned(),
            at: 1,
            stops: vec!["c1".to_owned()],
            skipped: None,
            summary: None,
            rev: None,
            about: ReviewSource::WorkingTree,
        };
        let human = Comment {
            anchor_ref: None,
            ..note("human-1", "a.txt", 1)
        };
        let comments = vec![stop("c1", "a.txt", 1), human];
        assert_eq!(w.notes_by_stop(&comments), vec![Vec::<String>::new()]);
    }

    #[test]
    fn every_target_form_parses() {
        assert_eq!(
            Target::parse("src/config.rs#merge"),
            Target::Symbol {
                path: "src/config.rs".to_owned(),
                symbol: "merge".to_owned()
            }
        );
        assert_eq!(
            Target::parse("src/config.rs:88"),
            Target::Line {
                path: "src/config.rs".to_owned(),
                line: 88,
                end: 88
            }
        );
        assert_eq!(
            Target::parse("src/config.rs"),
            Target::File {
                path: "src/config.rs".to_owned()
            }
        );
    }

    #[test]
    fn a_colon_that_is_not_a_line_number_stays_in_the_path() {
        assert_eq!(
            Target::parse("src/config.rs:"),
            Target::File {
                path: "src/config.rs:".to_owned()
            }
        );
        assert_eq!(
            Target::parse("src/config.rs:0"),
            Target::File {
                path: "src/config.rs:0".to_owned()
            }
        );
    }

    #[test]
    fn a_line_range_parses_and_clamps_to_the_file() {
        assert_eq!(
            Target::parse("src/config.rs:10-20"),
            Target::Line {
                path: "src/config.rs".to_owned(),
                line: 10,
                end: 20
            }
        );
        assert_eq!(
            Target::parse("src/config.rs:20-10"),
            Target::Line {
                path: "src/config.rs".to_owned(),
                line: 20,
                end: 20
            }
        );
        let content = "a\nb\nc\n";
        assert_eq!(
            Target::parse("lib.rs:2-99").locate(content),
            Located::Found { line: 2, end: 3 },
            "a range past the end clamps instead of going Lost"
        );
    }

    #[test]
    fn a_symbol_resolves_to_the_line_that_defines_it() {
        let content = "fn first() {}\n\nfn merge(a: u8) -> u8 {\n    a\n}\n";
        assert_eq!(
            Target::parse("lib.rs#merge").locate(content),
            Located::Found { line: 3, end: 5 }
        );
    }

    #[test]
    fn a_symbol_survives_an_edit_above_it() {
        let before = "fn merge() {}\n";
        let after = "use std::fmt;\n\nfn helper() {}\n\nfn merge() {}\n";
        let target = Target::parse("lib.rs#merge");
        assert_eq!(target.locate(before), Located::Found { line: 1, end: 1 });
        assert_eq!(target.locate(after), Located::Found { line: 5, end: 5 });
    }

    #[test]
    fn a_symbol_the_file_lost_stops_resolving() {
        assert_eq!(
            Target::parse("lib.rs#gone").locate("fn merge() {}\n"),
            Located::Lost
        );
    }

    #[test]
    fn a_line_past_the_end_stops_resolving() {
        assert_eq!(
            Target::parse("lib.rs:400").locate("fn merge() {}\n"),
            Located::Lost
        );
        assert_eq!(
            Target::parse("lib.rs:1").locate("fn merge() {}\n"),
            Located::Found { line: 1, end: 1 }
        );
    }

    #[test]
    fn a_whole_file_target_locates_the_file_and_no_line() {
        assert_eq!(
            Target::parse("lib.rs").locate("fn merge() {}\n"),
            Located::Whole
        );
    }
}