vvv-engine 0.2.0

Composes vvv plugins into refactoring pipelines
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
//! The pure line builders: answer data to [`crate::protocol::display::Line`]s, no colours.
//!
//! Each shape is a type that turns protocol data into the runs a row is made
//! of. Styling happens later, when an interface maps a [`Role`] to a colour;
//! this module never sees a palette, a writer, or a terminal.

use std::collections::BTreeSet;
use std::path::Path;

use super::Row;
use crate::Role as MatchRole;
use crate::protocol::display::{Line, Role};
use crate::protocol::vocabulary::{Ago, Files, IntentLine, Mark, Plural};
use crate::protocol::{
    Dep, FileChange, HistoryEntry, ImportSite, Importer, Notice, NoticeKind, OutlineItem, Placed,
    Respelling, Site, Skipped,
};
use crate::{Confidence, Match, Reach, ReachKind, Reason, Span, Symbol, SymbolKind};

/// A declaration as `● kind name   path:line`.
pub struct Declaration<'a> {
    m: &'a Match,
}

impl<'a> Declaration<'a> {
    pub fn new(m: &'a Match) -> Self {
        Self { m }
    }

    pub fn line(&self) -> Line {
        let m = self.m;
        let mut line = Line::mark(Mark::Declaration);
        if let Some(s) = &m.symbol {
            line = line
                .and(Role::Plain, " ")
                .and(Role::Declaration, format!("{} {}", s.kind, s.name));
        }
        line.and(Role::Plain, "   ")
            .and(Role::Path, m.path.display().to_string())
            .and(Role::Plain, ":")
            .and(Role::LineNumber, m.start.display().to_string())
    }
}

/// `● kind name   path:line` for a declaration the graph placed.
pub struct PlacedLine<'a> {
    placed: &'a Placed,
}

impl<'a> PlacedLine<'a> {
    pub fn new(placed: &'a Placed) -> Self {
        Self { placed }
    }

    pub fn line(&self) -> Line {
        let d = self.placed;
        Line::mark(Mark::Declaration)
            .and(Role::Plain, " ")
            .and(
                Role::Declaration,
                format!("{} {}", d.symbol.kind, d.symbol.name),
            )
            .and(Role::Plain, "   ")
            .and(Role::Path, d.path.display().to_string())
            .and(Role::Plain, ":")
            .and(Role::LineNumber, d.start.display().to_string())
    }
}

/// A `where` site: the declaration line, then the import to write, indented.
pub struct SiteLine<'a> {
    site: &'a Site,
}

impl<'a> SiteLine<'a> {
    pub fn new(site: &'a Site) -> Self {
        Self { site }
    }

    pub fn rows(&self) -> Vec<Row> {
        let s = self.site;
        let mut lines = vec![Row::at(
            Declaration::new(&s.declaration).line(),
            s.declaration.path.clone(),
            s.declaration.start.line,
        )];
        if let Some(import) = &s.import {
            lines.push(Row::new(
                Line::single(Role::Plain, "  ")
                    .and_line(Line::mark(Mark::Import))
                    .and(Role::Plain, " ")
                    .and(Role::Strong, import.clone()),
            ));
        }
        lines
    }
}

/// `path:line   import` for an import statement worth a look.
pub struct ImportSiteLine<'a> {
    site: &'a ImportSite,
}

impl<'a> ImportSiteLine<'a> {
    pub fn new(site: &'a ImportSite) -> Self {
        Self { site }
    }

    pub fn line(&self) -> Line {
        let s = self.site;
        Line::single(Role::Plain, "  ")
            .and(Role::Path, s.path.display().to_string())
            .and(Role::Plain, ":")
            .and(Role::LineNumber, s.start.display().to_string())
            .and(Role::Plain, "   ")
            .and(Role::Import, s.import.path.to_string())
    }
}

/// `#id  when  intent  N files`, with `↩` on the entry `undo` reverses.
pub struct HistoryLine<'a> {
    item: &'a HistoryEntry,
    now: u64,
    newest: bool,
}

impl<'a> HistoryLine<'a> {
    pub fn new(item: &'a HistoryEntry, now: u64) -> Self {
        Self {
            item,
            now,
            newest: false,
        }
    }

    pub fn newest(mut self, newest: bool) -> Self {
        self.newest = newest;
        self
    }

    pub fn line(&self) -> Line {
        let mut line = Line::single(Role::Strong, format!("#{:<3}", self.item.id))
            .and(Role::Plain, "  ")
            .and(
                Role::Dim,
                format!("{:>12}", Ago::between(self.item.at, self.now)),
            )
            .and(Role::Plain, "  ")
            .and(Role::Plain, IntentLine(&self.item.intent).to_string())
            .and(Role::Plain, "  ")
            .and(Role::Dim, Plural(self.item.files, "file").to_string());
        if self.newest {
            line = line.and(Role::Plain, "  ").and_line(Line::mark(Mark::Undo));
        }
        line
    }
}

/// `typescript skipped: <reason>`.
pub struct SkippedLine<'a> {
    skipped: &'a Skipped,
}

impl<'a> SkippedLine<'a> {
    pub fn new(skipped: &'a Skipped) -> Self {
        Self { skipped }
    }

    pub fn line(&self) -> Line {
        Line::single(
            Role::Plain,
            format!("{} skipped: {}", self.skipped.language, self.skipped.reason),
        )
    }
}

/// A reason as a tag: its mark's glyph and word.
pub struct Tag {
    reason: Reason,
}

impl Tag {
    pub fn new(reason: Reason) -> Self {
        Self { reason }
    }

    pub fn line(&self) -> Line {
        let mark = Mark::from(self.reason);
        Line::mark(mark)
            .and(Role::Plain, " ")
            .and(Role::Dim, mark.word())
    }
}

/// The verdict glyphs: `✓` will, `?` unsure, `✗` will not.
pub struct Verdict {
    confidence: Confidence,
}

impl Verdict {
    pub fn new(confidence: Confidence) -> Self {
        Self { confidence }
    }

    pub fn line(&self) -> Line {
        Line::mark(Mark::from(self.confidence))
    }
}

/// One numbered match: `N ● line:col  source  +N`.
pub(crate) struct MatchRow<'a> {
    ordinal: usize,
    width: usize,
    m: &'a Match,
}

impl MatchRow<'_> {
    pub fn new(m: &Match, ordinal: usize, width: usize) -> MatchRow<'_> {
        MatchRow { m, ordinal, width }
    }

    /// One match as a numbered row, for a view that lists matches one at a
    /// time (the picker).
    pub fn numbered(m: &Match, ordinal: usize) -> Line {
        MatchRow {
            ordinal,
            width: ordinal.to_string().len(),
            m,
        }
        .line()
    }

    /// The glyph is the role (`●` declaration, `→` import, blank use); the
    /// source line follows, with the hit marked.
    pub fn line(&self) -> Line {
        let m = self.m;
        let mut line = Line::single(Role::Plain, "  ")
            .and(
                Role::Ordinal,
                format!("{:>w$}", self.ordinal, w = self.width),
            )
            .and(Role::Plain, " ");
        line = match m.role {
            MatchRole::Declaration => line.and_line(Line::mark(Mark::Declaration)),
            MatchRole::Import => line.and_line(Line::mark(Mark::Import)),
            MatchRole::Use => line.and(Role::Plain, " "),
        };
        line = line
            .and(Role::Plain, " ")
            .and(
                Role::LineNumber,
                format!("{:>4}:{:<3}", m.start.line + 1, m.start.column + 1),
            )
            .and(Role::Plain, "  ");
        let rest = if m.role == MatchRole::Import {
            Role::Import
        } else {
            Role::Plain
        };
        line = line.and_line(Line::hit(m, rest));
        if m.line_count() > 1 {
            line = line.and(Role::Dim, format!("  +{}", m.line_count() - 1));
        }
        line
    }
}

/// Search results as two sections — `●` declarations, then everything else
/// with `→` on imports — each grouped by file, rows numbered in the order
/// printed (the numbers `--select` takes). Headers appear only when both
/// sections are present; a single section is the whole answer.
pub struct Sections<'a> {
    matches: &'a [Match],
}

impl<'a> Sections<'a> {
    pub fn new(matches: &'a [Match]) -> Self {
        Self { matches }
    }

    /// The `●` rows and the rest, in the engine's order.
    pub fn split(matches: &[Match]) -> (&[Match], &[Match]) {
        let n = matches
            .iter()
            .take_while(|m| m.role == MatchRole::Declaration)
            .count();
        matches.split_at(n)
    }

    pub fn lines(&self) -> Vec<Row> {
        let (declarations, uses) = Self::split(self.matches);
        let both = !declarations.is_empty() && !uses.is_empty();
        let width = self.matches.len().to_string().len();
        let mut rows = Vec::new();
        if !declarations.is_empty() {
            if both {
                rows.push(Row::new(Self::header(
                    Some(Mark::Declaration),
                    declarations,
                )));
            }
            Self::rows(&mut rows, declarations, 1, width);
        }
        if !uses.is_empty() {
            if both {
                rows.push(Row::new(Line::new()));
                rows.push(Row::new(Self::header(None, uses)));
            }
            Self::rows(&mut rows, uses, declarations.len() + 1, width);
        }
        rows
    }

    /// `● 1` / `○ 59  13 files`: a glyph (`○`, uses, is not a mark of its own),
    /// a count, the files.
    fn header(mark: Option<Mark>, matches: &[Match]) -> Line {
        let line = match mark {
            Some(mark) => Line::mark(mark),
            None => Line::single(Role::Dim, "○".to_string()),
        };
        line.and(Role::Plain, " ")
            .and(Role::Strong, matches.len().to_string())
            .and(Role::Plain, "  ")
            .and(
                Role::Dim,
                Files::among(matches.iter().map(|m| m.path.as_path())).to_string(),
            )
    }

    fn rows(out: &mut Vec<Row>, matches: &[Match], first: usize, width: usize) {
        let mut current: Option<&Path> = None;
        for (i, m) in matches.iter().enumerate() {
            if current != Some(m.path.as_path()) {
                if current.is_some() {
                    out.push(Row::new(Line::new()));
                }
                out.push(Row::new(Line::single(
                    Role::Path,
                    m.path.display().to_string(),
                )));
                current = Some(&m.path);
            }
            out.push(Row::at(
                MatchRow {
                    ordinal: first + i,
                    width,
                    m,
                }
                .line(),
                m.path.clone(),
                m.start.line,
            ));
        }
    }
}

/// A file's declarations as a tree: nesting by span containment, the name
/// column aligned, the modifier after it. With `reach`, who may name each
/// item follows.
pub struct OutlineTree<'a> {
    items: &'a [OutlineItem],
}

impl<'a> OutlineTree<'a> {
    pub fn new(items: &'a [OutlineItem]) -> Self {
        Self { items }
    }

    pub fn lines(&self) -> Vec<Line> {
        let depths = Self::depths(self.items);
        let labels: Vec<String> = self
            .items
            .iter()
            .zip(&depths)
            .map(|(item, depth)| format!("{}{}", "  ".repeat(*depth), Self::label(&item.symbol)))
            .collect();
        let width = labels.iter().map(String::len).max().unwrap_or(0);
        self.items
            .iter()
            .zip(&labels)
            .map(|(item, label)| {
                let mut line =
                    Line::single(Role::LineNumber, format!("{:>4}", item.start.line + 1))
                        .and(Role::Plain, "  ");
                if item.symbol.kind == SymbolKind::Impl {
                    line = line.and(Role::Declaration, label.clone());
                } else {
                    let (role, text) = Self::modifier(item);
                    line = line
                        .and(Role::Declaration, format!("{label:<width$}"))
                        .and(Role::Plain, "   ")
                        .and(role, text);
                }
                line
            })
            .collect()
    }

    fn label(symbol: &Symbol) -> String {
        match symbol.kind {
            SymbolKind::Function | SymbolKind::Method => format!("{}()", symbol.name),
            SymbolKind::Field | SymbolKind::Variant => symbol.name.clone(),
            kind => format!("{kind} {}", symbol.name),
        }
    }

    /// Each item's depth: how many earlier items' spans enclose it.
    fn depths(items: &[OutlineItem]) -> Vec<usize> {
        let mut stack: Vec<Span> = Vec::new();
        items
            .iter()
            .map(|item| {
                let span = item.symbol.span;
                while stack
                    .last()
                    .is_some_and(|open| !(span.start >= open.start && span.end <= open.end))
                {
                    stack.pop();
                }
                let depth = stack.len();
                stack.push(span);
                depth
            })
            .collect()
    }

    /// The modifier as written, by how far it reaches; `·` when there is none.
    fn modifier(item: &OutlineItem) -> (Role, String) {
        let text = item.symbol.modifier().unwrap_or("·").to_owned();
        let role = match (&item.reach, item.symbol.modifier()) {
            (Some(Reach::Everyone), _) => Role::Added,
            (Some(Reach::Package(_)), _) => Role::Warning,
            (Some(Reach::Within(_)), Some(_)) => Role::Warning,
            (None, Some(_)) => Role::Symbol,
            _ => Role::Dim,
        };
        (role, text)
    }
}

/// A file's imports grouped by the package they lead into, one row per
/// statement: `line  path{a, b}   → file`. The file's own package comes
/// first, unresolved (`?`) last.
pub struct DepGroups<'a> {
    path: &'a vvv_core::RelPath,
    deps: &'a [Dep],
    own: Option<&'a str>,
}

impl<'a> DepGroups<'a> {
    pub fn new(path: &'a vvv_core::RelPath, deps: &'a [Dep], own: Option<&'a str>) -> Self {
        Self { path, deps, own }
    }

    /// How many import statements the entries come from.
    pub fn statements(deps: &[Dep]) -> usize {
        deps.iter()
            .map(|d| Self::statement_of(deps, d))
            .collect::<BTreeSet<Span>>()
            .len()
    }

    pub fn rows(&self) -> Vec<Row> {
        let deps = self.deps;
        let mut lines = Vec::new();
        // Statements in source order, each its entries.
        let mut statements: Vec<(Span, Vec<&Dep>)> = Vec::new();
        for dep in deps {
            let key = Self::statement_of(deps, dep);
            match statements.iter_mut().find(|(k, _)| *k == key) {
                Some((_, entries)) => entries.push(dep),
                None => statements.push((key, vec![dep])),
            }
        }
        // Grouped by package: own, then the others by name, `?` last.
        let package = |entries: &[&Dep]| {
            entries
                .iter()
                .find_map(|d| d.address.as_ref())
                .map(|a| a.package().as_str().to_owned())
        };
        let mut packages: Vec<Option<String>> = statements
            .iter()
            .map(|(_, entries)| package(entries))
            .collect();
        packages.sort_by_key(|k| (k.is_none(), k.as_deref() != self.own, k.clone()));
        packages.dedup();
        // One very long statement should not push every arrow off-screen.
        let width = statements
            .iter()
            .map(|(_, e)| Self::one_line(e).len())
            .filter(|w| *w <= 60)
            .max()
            .unwrap_or(0);
        for key in &packages {
            let head = key.as_deref().unwrap_or("?");
            if !head.is_empty() {
                lines.push(Row::new(
                    Line::single(Role::Plain, "  ").and(Role::Strong, head.to_owned()),
                ));
            }
            for (_, entries) in statements.iter().filter(|(_, e)| package(e) == *key) {
                // A group's prefix is not an import of its own.
                let grouped = entries.iter().any(|d| d.import.group.is_some());
                let mut files: Vec<&Path> = entries
                    .iter()
                    .filter(|d| !grouped || d.import.group.is_some())
                    .filter_map(|d| d.file.as_deref())
                    .collect();
                files.sort();
                files.dedup();
                let mut line = Line::single(Role::Plain, "  ")
                    .and(
                        Role::LineNumber,
                        format!("{:>4}", entries[0].start.line + 1),
                    )
                    .and(Role::Plain, "  ");
                if files.is_empty() {
                    line = line.and(Role::Plain, Self::one_line(entries));
                } else {
                    line = line
                        .and(Role::Dim, format!("{:<width$}", Self::one_line(entries)))
                        .and(Role::Plain, "   ")
                        .and_line(Line::mark(Mark::Import))
                        .and(Role::Plain, " ")
                        .and(
                            Role::Path,
                            files
                                .iter()
                                .map(|f| f.display().to_string())
                                .collect::<Vec<_>>()
                                .join(", "),
                        );
                }
                lines.push(Row::at(line, self.path.clone(), entries[0].start.line));
            }
        }
        lines
    }

    /// The statement each entry belongs to: its group's, or, for an entry
    /// without a group of its own, the statement whose span holds it.
    fn statement_of(deps: &[Dep], dep: &Dep) -> Span {
        dep.import.group.as_ref().map_or_else(
            || {
                deps.iter()
                    .filter_map(|d| d.import.group.as_ref())
                    .map(|g| g.statement)
                    .find(|st| st.contains(&dep.import.span))
                    .unwrap_or(dep.import.span)
            },
            |g| g.statement,
        )
    }

    /// The entries of one statement as one path: the shared group prefix with
    /// the tails braced, or the single path.
    fn one_line(entries: &[&Dep]) -> String {
        let [only] = entries else {
            let Some(prefix) = entries
                .iter()
                .filter_map(|d| d.import.group.as_ref())
                .map(|g| &g.prefix)
                .next()
            else {
                return entries
                    .iter()
                    .map(|d| d.import.path.to_string())
                    .collect::<Vec<_>>()
                    .join(", ");
            };
            let same_prefix = entries
                .iter()
                .all(|d| d.import.group.as_ref().is_none_or(|g| &g.prefix == prefix));
            if !same_prefix {
                return entries
                    .iter()
                    .map(|d| d.import.path.to_string())
                    .collect::<Vec<_>>()
                    .join(", ");
            }
            let list = entries
                .iter()
                .filter_map(|d| d.import.group.as_ref())
                .map(|g| g.list)
                .next();
            let tails: Vec<String> = entries
                .iter()
                .filter_map(|d| match d.import.path.strip_prefix(prefix) {
                    Some(tail) if !tail.is_empty() => Some(d.import.path.spell_segments(tail)),
                    _ if list.is_some_and(|l| l.contains(&d.import.span)) => {
                        Some("self".to_owned())
                    }
                    _ if d.import.group.is_some() => Some(d.import.path.to_string()),
                    _ => None,
                })
                .collect();
            let separator = prefix.syntax().separator();
            return format!("{prefix}{separator}{{{}}}", tails.join(", "));
        };
        only.import.path.to_string()
    }
}

/// `path:line   Name Name` for each file that imports the one asked about.
pub struct ImporterRows<'a> {
    importers: &'a [Importer],
}

impl<'a> ImporterRows<'a> {
    pub fn new(importers: &'a [Importer]) -> Self {
        Self { importers }
    }

    /// Distinct statements: one per `(path, line)`.
    pub fn sites(importers: &[Importer]) -> Vec<(&Path, u32, Vec<&str>)> {
        let mut rows: Vec<(&Path, u32, Vec<&str>)> = Vec::new();
        // A group's prefix is listed as an entry too; it names nothing.
        let is_prefix = |i: &Importer| {
            importers.iter().any(|o| {
                o.path == i.path
                    && o.start.line == i.start.line
                    && o.import.path.continues(&i.import.path)
            })
        };
        for i in importers.iter().filter(|i| !is_prefix(i)) {
            let name = i.import.path.last().map_or("", |n| n.as_str());
            match rows
                .iter_mut()
                .find(|(p, l, _)| *p == i.path.as_path() && *l == i.start.line)
            {
                Some((_, _, names)) => names.push(name),
                None => rows.push((i.path.as_path(), i.start.line, vec![name])),
            }
        }
        rows
    }

    pub fn rows(&self) -> Vec<Row> {
        let rows = Self::sites(self.importers);
        let width = rows
            .iter()
            .map(|(path, line, _)| Respellings::site(path, *line).len())
            .max()
            .unwrap_or(0);
        rows.into_iter()
            .map(|(path, line, names)| {
                Row::at(
                    Line::single(Role::Plain, "  ")
                        .and(
                            Role::Path,
                            format!("{:<width$}", Respellings::site(path, line)),
                        )
                        .and(Role::Plain, "   ")
                        .and(Role::Plain, names.join(" ")),
                    path.into(),
                    line,
                )
            })
            .collect()
    }
}

/// `→ path:line   from → to` for each reference a move re-spelled.
pub struct Respellings<'a> {
    rows: &'a [Respelling],
    width: usize,
}

impl<'a> Respellings<'a> {
    pub fn new(rows: &'a [Respelling], width: usize) -> Self {
        Self { rows, width }
    }

    /// `path:line`, as the row prints it — for sizing the column.
    pub fn site(path: &Path, line: u32) -> String {
        format!("{}:{}", path.display(), line + 1)
    }

    pub fn rows(&self) -> Vec<Row> {
        self.rows
            .iter()
            .map(|r| Row::at(Self::row(r, self.width), r.path.clone(), r.start.line))
            .collect()
    }

    /// One re-spelling as a row: `→ path:line   from → to`.
    pub fn row(r: &Respelling, width: usize) -> Line {
        Line::mark(Mark::Import)
            .and(Role::Plain, " ")
            .and(
                Role::Path,
                format!("{:<width$}", Self::site(&r.path, r.start.line)),
            )
            .and(Role::Plain, "   ")
            .and(Role::Dim, r.from.clone())
            .and(Role::Plain, " ")
            .and_line(Line::mark(Mark::Import))
            .and(Role::Plain, " ")
            .and_line(Self::changed(&r.from, &r.to))
    }

    /// `to` with the segment that differs from `from` in bold.
    fn changed(from: &str, to: &str) -> Line {
        let from: Vec<char> = from.chars().collect();
        let to: Vec<char> = to.chars().collect();
        let prefix = from.iter().zip(&to).take_while(|(a, b)| a == b).count();
        let suffix = from
            .iter()
            .rev()
            .zip(to.iter().rev())
            .take_while(|(a, b)| a == b)
            .count()
            .min(to.len() - prefix)
            .min(from.len() - prefix);
        let head: String = to[..prefix].iter().collect();
        let mid: String = to[prefix..to.len() - suffix].iter().collect();
        let tail: String = to[to.len() - suffix..].iter().collect();
        Line::single(Role::Plain, head)
            .and(Role::Strong, mid)
            .and(Role::Plain, tail)
    }
}

/// A notice as a `!` row: `! path:line   what, and what to do`.
pub struct NoticeRow<'a> {
    notice: &'a Notice,
    width: usize,
}

impl<'a> NoticeRow<'a> {
    pub fn new(notice: &'a Notice, width: usize) -> Self {
        Self { notice, width }
    }

    pub fn line(&self) -> Line {
        let (n, width) = (self.notice, self.width);
        let line = Line::mark(Mark::ByHand)
            .and(Role::Plain, " ")
            .and(
                Role::Path,
                format!("{:<width$}", Respellings::site(&n.path, n.start.line)),
            )
            .and(Role::Plain, "   ");
        match &n.kind {
            NoticeKind::UnrewritableImport {
                import,
                replacement,
            } => line
                .and(Role::Dim, import.clone())
                .and(Role::Plain, " ")
                .and_line(Line::mark(Mark::Import))
                .and(Role::Plain, " ")
                .and(Role::Plain, replacement.clone())
                .and(Role::Plain, "   ")
                .and(Role::Dim, "grouped import, by hand"),
            NoticeKind::RedundantImport { import } => line
                .and(Role::Dim, import.clone())
                .and(Role::Plain, "   ")
                .and(Role::Dim, "now declared here, remove by hand"),
            NoticeKind::Unreachable { item, from, needs } => line
                .and(Role::Plain, item.clone())
                .and(Role::Plain, "   ")
                .and(
                    Role::Dim,
                    match needs {
                        ReachKind::Everyone => {
                            format!("used from {from}, another package; `pub` is your call")
                        }
                        needs => format!("used from {from}, needs {needs:?}; by hand"),
                    },
                ),
        }
    }
}

/// A source line with a caret under a span.
pub struct Caret {
    line: u32,
    text: String,
    column: usize,
    len: usize,
}

impl Caret {
    pub fn new(line: u32, text: &str, column: usize, len: usize) -> Self {
        Self {
            line,
            text: text.to_owned(),
            column,
            len,
        }
    }

    pub fn lines(&self) -> Vec<Line> {
        let indent = self.text.len() - self.text.trim_start().len();
        let column = self.column.saturating_sub(indent);
        vec![
            Line::single(Role::Plain, "  ")
                .and(Role::LineNumber, format!("{:>4}", self.line + 1))
                .and(Role::Plain, " ")
                .and(Role::Dim, "│".to_string())
                .and(Role::Plain, " ")
                .and(Role::Plain, self.text.trim_start().to_string()),
            Line::single(Role::Plain, format!("  {:>4} ", ""))
                .and(Role::Dim, "│".to_string())
                .and(Role::Plain, " ")
                .and(Role::Plain, " ".repeat(column))
                .and(Role::Hit, "^".repeat(self.len.max(1))),
        ]
    }
}

/// One file's change: a path header (`from → to` for moves) and its unified
/// diff, the `±` on the header when the hunks are structural edits.
pub struct Diff<'a> {
    file: &'a FileChange,
    structural: bool,
}

impl<'a> Diff<'a> {
    pub fn new(file: &'a FileChange, structural: bool) -> Self {
        Self { file, structural }
    }

    /// Whether a file's edits are more than re-spelled paths: what a move calls
    /// structural, so a view can mark it (`±`) and the composition can count it.
    pub fn is_structural(file: &FileChange, respellings: &[Respelling]) -> bool {
        !(file.moved_to.is_none()
            && !file.edits.is_empty()
            && file.edits.iter().all(|e| {
                respellings
                    .iter()
                    .any(|r| r.path == file.path && r.span == e.span)
            }))
    }

    fn header(&self) -> Line {
        let file = self.file;
        let header = match &file.moved_to {
            Some(to) => format!("{} → {}", file.path.display(), to.display()),
            None => file.path.display().to_string(),
        };
        let mut head = if self.structural {
            Line::mark(Mark::Structure).and(Role::Plain, " ")
        } else {
            Line::new()
        };
        head = head.and(Role::Path, header);
        head
    }

    pub fn rows(&self, state: crate::MutationState) -> Vec<Row> {
        let file = self.file;
        let path = if state.is_applied() {
            file.moved_to.as_ref().unwrap_or(&file.path)
        } else {
            &file.path
        };
        let mut rows = vec![Row::new(self.header())];
        for hunk in file.diff.hunks() {
            rows.push(Row::new(Line::single(Role::Hunk, hunk.header())));
            let (mut old, mut new) = (
                hunk.old.start.saturating_sub(1),
                hunk.new.start.saturating_sub(1),
            );
            for changed in &hunk.lines {
                let role = match changed.kind {
                    crate::protocol::DiffKind::Context => Role::Plain,
                    crate::protocol::DiffKind::Added => Role::Added,
                    crate::protocol::DiffKind::Removed => Role::Removed,
                };
                let line = Line::single(role, format!("{}{}", changed.kind.marker(), changed.text));
                let at = match (state.is_applied(), changed.kind) {
                    (_, crate::protocol::DiffKind::Context) => {
                        Some(if state.is_applied() { new } else { old })
                    }
                    (false, crate::protocol::DiffKind::Removed) => Some(old),
                    (true, crate::protocol::DiffKind::Added) => Some(new),
                    _ => None,
                };
                rows.push(match at {
                    Some(at) => Row::at(line, path.clone(), at),
                    None => Row::new(line),
                });
                if changed.kind != crate::protocol::DiffKind::Added {
                    old += 1;
                }
                if changed.kind != crate::protocol::DiffKind::Removed {
                    new += 1;
                }
            }
        }
        rows
    }
}

#[cfg(test)]
mod snapshots {
    use std::path::Path;

    use crate::protocol::Diff as ProtocolDiff;
    use crate::{Edit, Span};
    use vvv_core::RelPath;

    use super::*;

    #[test]
    fn diff_drops_file_headers_and_shows_moves() {
        let moved = FileChange {
            path: RelPath::from("a.rs"),
            moved_to: Some(RelPath::from("b/a.rs")),
            edits: vec![Edit::replace(Span::new(0, 1), "x")],
            diff: ProtocolDiff::between(Path::new("a.rs"), Path::new("b/a.rs"), "x\n", "y\n"),
        };
        let rendered: String = Diff::new(&moved, false)
            .rows(crate::MutationState::Preview)
            .iter()
            .map(|row| {
                let text: String = row.line.pieces().iter().map(|p| p.text.as_str()).collect();
                format!("{text}\n")
            })
            .collect();
        insta::assert_snapshot!(rendered);
    }
}