declutter-diff 0.1.2

Review AI-generated diffs with comments, tests, imports, logging and formatting toggled in and out
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::ops::Range;
use std::rc::Rc;

use crate::classify::{Classified, classify};
use crate::diff::{Hunk, RowKind, diff, filter_formatting};
use crate::highlight::annotate;
use crate::lang::Lang;
use crate::project::{LayerMode, project};
use crate::store::fingerprint;
use crate::test_files::is_test_file;

/// Unchanged lines shown around each change.
pub const CONTEXT: usize = 3;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChangeStatus {
    Added,
    Deleted,
    Modified,
    Renamed,
}

impl ChangeStatus {
    pub fn letter(self) -> char {
        match self {
            ChangeStatus::Added => 'A',
            ChangeStatus::Deleted => 'D',
            ChangeStatus::Modified => 'M',
            ChangeStatus::Renamed => 'R',
        }
    }
}

/// One changed file, both versions in full.
#[derive(Debug, Clone)]
pub struct FileChange {
    pub path: String,
    pub old_path: Option<String>,
    pub status: ChangeStatus,
    pub old: Option<String>,
    pub new: Option<String>,
    pub binary: bool,
}

/// How well declutter could find the layers in a file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Detection {
    Parsed(Lang),
    /// Parsed with syntax errors; layers near the error may be missed. Holds the line of
    /// the first error, in the new version if it has one.
    Partial(Lang, usize),
    /// No grammar for this file type, so nothing but whole test files is hidden.
    Unsupported,
    Binary,
}

impl Detection {
    pub fn label(self) -> String {
        match self {
            Detection::Parsed(lang) => lang.name().to_string(),
            Detection::Partial(lang, line) => {
                format!("{}, partial parse near line {line}", lang.name())
            }
            Detection::Unsupported => "no grammar".to_string(),
            Detection::Binary => "binary".to_string(),
        }
    }
}

/// A layer made of spans inside a file, as opposed to the file-level test layer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpanLayer {
    Comments,
    Imports,
    Logging,
    /// Test code inside a source file (Rust's `#[cfg(test)]` modules); whole test files
    /// are the file-level side of the same layer.
    Tests,
}

impl SpanLayer {
    pub const ALL: [SpanLayer; 4] = [
        SpanLayer::Comments,
        SpanLayer::Imports,
        SpanLayer::Logging,
        SpanLayer::Tests,
    ];

    /// The adjective used in messages: "comment-only hunks".
    pub fn adjective(self) -> &'static str {
        match self {
            SpanLayer::Comments => "comment",
            SpanLayer::Imports => "import",
            SpanLayer::Logging => "logging",
            SpanLayer::Tests => "test",
        }
    }

    fn spans(self, classified: &Classified) -> &[Range<usize>] {
        match self {
            SpanLayer::Comments => &classified.comments,
            SpanLayer::Imports => &classified.imports,
            SpanLayer::Logging => &classified.logging,
            SpanLayer::Tests => &classified.tests,
        }
    }
}

/// The part of `Layers` that changes a file's diff: the span layers, and whether
/// formatting-only changes are shown.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DiffModes {
    pub comments: LayerMode,
    pub imports: LayerMode,
    pub logging: LayerMode,
    pub formatting: LayerMode,
    pub tests: LayerMode,
}

impl DiffModes {
    pub const SHOWN: DiffModes = DiffModes {
        comments: LayerMode::Shown,
        imports: LayerMode::Shown,
        logging: LayerMode::Shown,
        formatting: LayerMode::Shown,
        tests: LayerMode::Shown,
    };

    pub fn mode(self, layer: SpanLayer) -> LayerMode {
        match layer {
            SpanLayer::Comments => self.comments,
            SpanLayer::Imports => self.imports,
            SpanLayer::Logging => self.logging,
            SpanLayer::Tests => self.tests,
        }
    }

    /// How the file is projected: any layer set to *only* wins, and shows the union of
    /// those layers; otherwise the hidden layers are cut out.
    pub fn effective(self) -> (LayerMode, Vec<SpanLayer>) {
        for mode in [LayerMode::Only, LayerMode::Hidden] {
            let layers: Vec<SpanLayer> = SpanLayer::ALL
                .into_iter()
                .filter(|&layer| self.mode(layer) == mode)
                .collect();
            if !layers.is_empty() {
                return (mode, layers);
            }
        }
        (LayerMode::Shown, Vec::new())
    }

    /// What the reviewer sees, for messages: only some layers, some hidden, or all
    /// shown, with the adjective naming those layers ("comment", "comment/formatting").
    pub fn outcome(self) -> (LayerMode, String) {
        for mode in [LayerMode::Only, LayerMode::Hidden] {
            let mut names: Vec<&str> = SpanLayer::ALL
                .into_iter()
                .filter(|&layer| self.mode(layer) == mode)
                .map(SpanLayer::adjective)
                .collect();
            if self.formatting == mode {
                names.push("formatting");
            }
            if !names.is_empty() {
                return (mode, names.join("/"));
            }
        }
        (LayerMode::Shown, String::new())
    }

    pub fn adjective(self) -> String {
        self.outcome().1
    }
}

/// Just the comment layer set; the rest shown.
impl From<LayerMode> for DiffModes {
    fn from(comments: LayerMode) -> DiffModes {
        DiffModes {
            comments,
            ..DiffModes::SHOWN
        }
    }
}

impl From<Layers> for DiffModes {
    fn from(layers: Layers) -> DiffModes {
        DiffModes {
            comments: layers.comments,
            imports: layers.imports,
            logging: layers.logging,
            formatting: layers.formatting,
            tests: layers.tests,
        }
    }
}

#[derive(Debug, Clone, Default)]
pub struct ModeView {
    pub hunks: Vec<Hunk>,
    /// Hunks of the full diff that have no visible change in this mode.
    pub hidden_hunks: usize,
}

/// A changed file. Its diff under each choice of layers is computed on first use.
#[derive(Debug, Clone)]
pub struct FileReview {
    pub path: String,
    pub old_path: Option<String>,
    pub status: ChangeStatus,
    pub detection: Detection,
    /// The whole file is test code; the test layer is file-granular.
    pub is_test: bool,
    /// Identifies this exact change (path and both versions) for review marks.
    pub fingerprint: u64,
    old: String,
    new: String,
    old_layers: Classified,
    new_layers: Classified,
    views: RefCell<HashMap<DiffModes, Rc<ModeView>>>,
}

impl FileReview {
    pub fn new(change: FileChange) -> FileReview {
        let old = change.old.unwrap_or_default();
        let new = change.new.unwrap_or_default();

        let (detection, old_layers, new_layers) = if change.binary {
            (
                Detection::Binary,
                Classified::default(),
                Classified::default(),
            )
        } else {
            match Lang::from_path(&change.path)
                .and_then(|lang| Some((lang, classify(lang, &old)?, classify(lang, &new)?)))
            {
                Some((lang, old_c, new_c)) => {
                    let detection = match new_c.error_line.or(old_c.error_line) {
                        Some(line) => Detection::Partial(lang, line),
                        None => Detection::Parsed(lang),
                    };
                    (detection, old_c, new_c)
                }
                None => (
                    Detection::Unsupported,
                    Classified::default(),
                    Classified::default(),
                ),
            }
        };

        let is_test = is_test_file(&change.path, if new.is_empty() { &old } else { &new });
        let fingerprint = fingerprint(&[&change.path, &old, &new]);
        FileReview {
            path: change.path,
            old_path: change.old_path,
            status: change.status,
            detection,
            is_test,
            fingerprint,
            old,
            new,
            old_layers,
            new_layers,
            views: RefCell::new(HashMap::new()),
        }
    }

    pub fn view(&self, modes: impl Into<DiffModes>) -> Rc<ModeView> {
        let modes = modes.into();
        if let Some(view) = self.views.borrow().get(&modes) {
            return Rc::clone(view);
        }
        let hunks = self.hunks_for(modes);
        let hidden_hunks = if modes == DiffModes::SHOWN {
            0
        } else {
            count_hidden(&self.view(DiffModes::SHOWN).hunks, &hunks)
        };
        let view = Rc::new(ModeView {
            hunks,
            hidden_hunks,
        });
        self.views.borrow_mut().insert(modes, Rc::clone(&view));
        view
    }

    fn hunks_for(&self, modes: DiffModes) -> Vec<Hunk> {
        // A test file is test code from top to bottom: the test layer decides whether it
        // is listed at all, never which of its lines are shown.
        let modes = if self.is_test {
            DiffModes {
                tests: LayerMode::Shown,
                ..modes
            }
        } else {
            modes
        };
        let (mode, layers) = modes.effective();
        let lang = match self.detection {
            Detection::Parsed(lang) | Detection::Partial(lang, _) => Some(lang),
            _ => None,
        };
        let side = |src: &str, classified: &Classified| {
            let mut projection = project(src, &union(classified, &layers), mode);
            if let Some(lang) = lang {
                annotate(&mut projection, lang);
            }
            projection
        };
        let mut hunks = diff(
            &side(&self.old, &self.old_layers),
            &side(&self.new, &self.new_layers),
            CONTEXT,
        );
        // Indentation is syntax in Python, and in files without a grammar it may be too.
        let indentation_matters = !matches!(
            lang,
            Some(
                Lang::Swift
                    | Lang::TypeScript
                    | Lang::Tsx
                    | Lang::JavaScript
                    | Lang::Go
                    | Lang::Rust
                    | Lang::Kotlin
            )
        );
        filter_formatting(&mut hunks, modes.formatting, indentation_matters);
        if mode == LayerMode::Hidden {
            // Added or removed blank lines are layout: they mostly travel with whatever
            // was hidden, and they never change what the code does.
            for hunk in &mut hunks {
                hunk.rows
                    .retain(|row| row.kind == RowKind::Context || !row.text.trim().is_empty());
            }
            hunks.retain(|hunk| hunk.changed().next().is_some());
        }
        hunks
    }

    pub fn total_hunks(&self) -> usize {
        self.view(DiffModes::SHOWN).hunks.len()
    }

    /// Whether the file is listed at all under this test-layer mode. A source file with
    /// test blocks in it stays listed either way: hiding tests cuts the blocks out, and
    /// showing only tests keeps just them.
    pub fn is_visible(&self, tests: LayerMode) -> bool {
        match tests {
            LayerMode::Shown => true,
            LayerMode::Hidden => !self.is_test,
            LayerMode::Only => self.is_test || self.has_test_blocks(),
        }
    }

    /// Test code inside the file, in either version โ€” Rust's `#[cfg(test)]` modules.
    pub fn has_test_blocks(&self) -> bool {
        !self.old_layers.tests.is_empty() || !self.new_layers.tests.is_empty()
    }

    /// The bracketed tag after the file name: language or detection problem, and `test`.
    pub fn tag(&self) -> String {
        let detection = self.detection.label();
        if self.is_test {
            format!("{detection}, test")
        } else {
            detection
        }
    }
}

/// The spans of `layers`, merged into one sorted, non-overlapping list.
fn union(classified: &Classified, layers: &[SpanLayer]) -> Vec<Range<usize>> {
    let mut spans: Vec<Range<usize>> = layers
        .iter()
        .flat_map(|layer| layer.spans(classified).iter().cloned())
        .collect();
    spans.sort_by_key(|span| span.start);
    let mut merged: Vec<Range<usize>> = Vec::with_capacity(spans.len());
    for span in spans {
        match merged.last_mut() {
            Some(last) if span.start <= last.end => last.end = last.end.max(span.end),
            _ => merged.push(span),
        }
    }
    merged
}

/// Counts hunks of the full diff none of whose changed lines are still changed in `visible`.
fn count_hidden(full: &[Hunk], visible: &[Hunk]) -> usize {
    let key = |kind: RowKind, old: Option<usize>, new: Option<usize>| match kind {
        RowKind::Removed => old.map(|line| (false, line)),
        _ => new.map(|line| (true, line)),
    };
    let still_changed: HashSet<(bool, usize)> = visible
        .iter()
        .flat_map(Hunk::changed)
        .filter_map(|row| key(row.kind, row.old_line, row.new_line))
        .collect();
    full.iter()
        .filter(|hunk| {
            !hunk.changed().any(|row| {
                key(row.kind, row.old_line, row.new_line)
                    .is_some_and(|k| still_changed.contains(&k))
            })
        })
        .count()
}

/// What the reviewer has chosen to see of each layer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Layers {
    pub comments: LayerMode,
    pub tests: LayerMode,
    pub imports: LayerMode,
    pub logging: LayerMode,
    pub formatting: LayerMode,
}

impl Default for Layers {
    fn default() -> Layers {
        Layers {
            comments: LayerMode::Hidden,
            tests: LayerMode::Shown,
            imports: LayerMode::Shown,
            logging: LayerMode::Shown,
            formatting: LayerMode::Shown,
        }
    }
}

/// Totals across the files visible under one choice of layers.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Summary {
    pub files: usize,
    pub total_hunks: usize,
    pub visible_hunks: usize,
    pub hidden_hunks: usize,
    /// Files with changes, none of them visible under these layers.
    pub fully_hidden_files: usize,
    /// Files left out by the test layer: test files when hidden, the rest when only.
    pub filtered_files: usize,
    pub unsupported_files: usize,
    pub partial_files: usize,
    /// Listed files with test blocks inside them (Rust's `#[cfg(test)]` modules).
    pub test_block_files: usize,
}

impl Summary {
    pub fn new(files: &[FileReview], layers: Layers) -> Summary {
        let mut summary = Summary::default();
        for file in files {
            if !file.is_visible(layers.tests) {
                summary.filtered_files += 1;
                continue;
            }
            let view = file.view(layers);
            summary.files += 1;
            summary.total_hunks += file.total_hunks();
            summary.visible_hunks += view.hunks.len();
            summary.hidden_hunks += view.hidden_hunks;
            if file.total_hunks() > 0 && view.hunks.is_empty() {
                summary.fully_hidden_files += 1;
            }
            if file.has_test_blocks() {
                summary.test_block_files += 1;
            }
            match file.detection {
                Detection::Unsupported => summary.unsupported_files += 1,
                Detection::Partial(..) => summary.partial_files += 1,
                _ => {}
            }
        }
        summary
    }

    pub fn status_line(&self, layers: Layers) -> String {
        let states: Vec<String> = [
            ("comments", layers.comments),
            ("tests", layers.tests),
            ("imports", layers.imports),
            ("logging", layers.logging),
            ("formatting", layers.formatting),
        ]
        .into_iter()
        .filter(|(_, mode)| *mode != LayerMode::Shown)
        .map(|(name, mode)| format!("{name}: {}", mode.label()))
        .collect();
        let mut parts = if states.is_empty() {
            vec!["all layers shown".to_string()]
        } else {
            states
        };

        let mut modes = DiffModes::from(layers);
        // With no test blocks inside the listed files, the test layer only filters files,
        // which is reported on its own below; it hides no hunks.
        if self.test_block_files == 0 {
            modes.tests = LayerMode::Shown;
        }
        let adjective = modes.adjective();
        match modes.outcome().0 {
            LayerMode::Shown => parts.push(format!(
                "{} {} in {} {}",
                self.total_hunks,
                plural(self.total_hunks, "hunk"),
                self.files,
                plural(self.files, "file")
            )),
            LayerMode::Hidden => {
                parts.push(format!(
                    "showing {} of {} hunks",
                    self.visible_hunks, self.total_hunks
                ));
                parts.push(format!(
                    "{} {adjective}-only {} hidden",
                    self.hidden_hunks,
                    plural(self.hidden_hunks, "hunk")
                ));
                if self.fully_hidden_files > 0 {
                    parts.push(format!(
                        "{} {adjective}-only {}",
                        self.fully_hidden_files,
                        plural(self.fully_hidden_files, "file")
                    ));
                }
            }
            LayerMode::Only => {
                parts.push(format!(
                    "{} {} with {adjective} changes",
                    self.visible_hunks,
                    plural(self.visible_hunks, "hunk")
                ));
                parts.push(format!(
                    "{} other {} hidden",
                    self.hidden_hunks,
                    plural(self.hidden_hunks, "hunk")
                ));
            }
        }
        match layers.tests {
            LayerMode::Shown => {}
            LayerMode::Hidden => parts.push(format!(
                "{} test {} hidden",
                self.filtered_files,
                plural(self.filtered_files, "file")
            )),
            LayerMode::Only => parts.push(format!(
                "{} non-test {} hidden",
                self.filtered_files,
                plural(self.filtered_files, "file")
            )),
        }
        if self.unsupported_files > 0 {
            parts.push(format!(
                "no grammar for {} {}",
                self.unsupported_files,
                plural(self.unsupported_files, "file")
            ));
        }
        if self.partial_files > 0 {
            parts.push(format!(
                "{} {} partially parsed",
                self.partial_files,
                plural(self.partial_files, "file")
            ));
        }
        parts.join(" ยท ")
    }
}

fn plural(count: usize, word: &str) -> String {
    if count == 1 {
        word.to_string()
    } else {
        format!("{word}s")
    }
}