Skip to main content

vvv_engine/report/
mod.rs

1//! A command's output as data: a list of [`Block`]s per stream, which a
2//! [`View`] lays out. The vocabulary is deliberately small; the richness
3//! lives in the [`Line`]s a block carries.
4//!
5//! The composition lives on [`Document`] itself — `Document::search`,
6//! `Document::rename`, `Document::moved` — so nothing here is a free function.
7
8pub(crate) mod lines;
9mod view;
10
11pub use view::{Detailed, Presentation, View};
12
13use vvv_core::RelPath;
14
15use crate::SymbolKind;
16use crate::protocol::display::{Line, Role};
17use crate::protocol::vocabulary::{Files, IntentLine, Mark, Plural};
18use crate::protocol::{
19    Answer, Batch, BatchIntent, Consumer, Dead, Dep, Deps, Explanation, Exposed, Failure, History,
20    Impact, ImportSite, Importer, ImportsReport, Intent, Locations, Move, MoveIntent, MoveSymbol,
21    Outline, OutlineItem, References, Rename, Rewrite, Site, Skipped, Surface, Undo, Unreferenced,
22};
23use crate::{Address, Confidence, FileChange, HistoryEntry, Match, Notice, Occurrence, Respelling};
24
25use lines as l;
26
27/// The flags a view needs beyond the answer.
28#[derive(Debug, Clone, Copy, Default)]
29pub struct Options {
30    /// Expand what is collapsed by default (`-v`).
31    pub verbose: bool,
32    /// Print every file's full patch, not only structural edits (`--diff`).
33    pub diff: bool,
34}
35
36/// A command's output, one sequence of blocks per stream: results, then
37/// notes (summaries, hints, warnings).
38#[derive(Debug, Default, Clone)]
39pub struct Document {
40    body: Vec<Block>,
41    notes: Vec<Block>,
42}
43
44impl Document {
45    pub fn new() -> Self {
46        Self::default()
47    }
48
49    /// Append bare lines to the result stream.
50    pub fn body(&mut self, lines: impl IntoIterator<Item = Line>) {
51        self.body.extend(lines.into_iter().map(Block::Line));
52    }
53
54    /// Append bare lines to the note stream.
55    pub fn notes(&mut self, lines: impl IntoIterator<Item = Line>) {
56        self.notes.extend(lines.into_iter().map(Block::Line));
57    }
58
59    /// Append one structured block to the result stream.
60    pub fn block_body(&mut self, block: Block) {
61        self.body.push(block);
62    }
63
64    /// Append one structured block to the note stream.
65    pub fn block_note(&mut self, block: Block) {
66        self.notes.push(block);
67    }
68
69    /// Both streams, for the view.
70    pub fn parts(&self) -> (&[Block], &[Block]) {
71        (&self.body, &self.notes)
72    }
73
74    // ------------------------------------------------------------------ entry
75
76    /// Compose one answer into the blocks its command prints.
77    pub fn of(answer: &Answer, options: Options) -> Self {
78        match answer {
79            Answer::Search(r) => Self::search(&r.matches, &r.skipped),
80            Answer::Outline(r) => Self::outline(r),
81            Answer::References(r) => Self::references(r),
82            Answer::Where(r) => Self::locations(r),
83            Answer::Deps(r) => Self::deps(r),
84            Answer::Explain(r) => Self::explain(r),
85            Answer::Surface(r) => Self::surface(r),
86            Answer::Impact(r) => Self::impact(r),
87            Answer::Dead(r) => Self::dead(r),
88            Answer::Imports(r) => Self::imports(r),
89            // The file answer is the picker's; no CLI command asks for one.
90            Answer::File(_) => Self::new(),
91            Answer::Rewrite(r) => Self::rewrite(r),
92            Answer::Rename(r) => Self::rename(r, options),
93            Answer::Move(r) => Self::move_file(r, options),
94            Answer::MoveSymbol(r) => Self::move_symbol(r, options),
95            Answer::Batch(r) => Self::batch(r, options),
96            Answer::Undo(r) => Self::undo(r),
97            Answer::History(r) => Self::history(r),
98        }
99    }
100
101    /// Compose a failure: `✗ message`, then each hint line.
102    pub fn error(failure: &Failure) -> Self {
103        let mut report = Self::new();
104        report.notes([Line::of(Role::Error, "✗ ").and(Role::Plain, failure.message.clone())]);
105        for line in failure.hint.iter().flat_map(|h| h.lines()) {
106            report.hint(line);
107        }
108        report
109    }
110
111    // ---------------------------------------------------------------- helpers
112
113    /// A title line, then a blank.
114    fn title(&mut self, text: impl std::fmt::Display) {
115        self.block_body(Block::Title(text.to_string()));
116    }
117
118    /// `hint: …` on the note stream.
119    fn hint(&mut self, text: impl std::fmt::Display) {
120        self.block_note(Block::Note(Note::Hint(text.to_string())));
121    }
122
123    /// `warning: …` on the note stream.
124    fn warning(&mut self, line: Line) {
125        self.block_note(Block::Note(Note::Warning(line)));
126    }
127
128    /// `◆ module   path`, or the path alone when the language has no addresses.
129    fn module_header(&mut self, module: Option<&Address>, path: &std::path::Path) {
130        match module.filter(|m| !m.package().as_str().is_empty()) {
131            Some(module) => self.body([Line::mark(Mark::Address)
132                .and(Role::Plain, " ")
133                .and(Role::Address, module.to_string())
134                .and(Role::Plain, "   ")
135                .and(Role::Path, path.display().to_string())]),
136            None => self.body([Line::of(Role::Path, path.display().to_string())]),
137        }
138    }
139
140    /// The body of a move preview: counts, the `→` rows, the `!` rows, and a
141    /// `±` hunk for every file whose edits are more than re-spelled paths (or
142    /// every file, with `--diff`). Answers how many are structural.
143    fn moved(
144        &mut self,
145        files: &[FileChange],
146        respellings: &[Respelling],
147        notices: &[Notice],
148    ) -> usize {
149        let structural = files
150            .iter()
151            .filter(|f| l::Diff::is_structural(f, respellings))
152            .count();
153        self.block_body(Block::Moved {
154            files: files.to_vec(),
155            respellings: respellings.to_vec(),
156            notices: notices.to_vec(),
157        });
158        structural
159    }
160
161    /// `→ 12  ± 2  ! 1   12 files` on the note stream, then the verdict.
162    fn moved_summary(
163        &mut self,
164        applied: bool,
165        history_id: Option<u64>,
166        counts: MoveCounts,
167        diff: bool,
168    ) {
169        let MoveCounts {
170            respellings,
171            structural,
172            notices,
173            files,
174        } = counts;
175        let mut counts: Vec<Line> = Vec::new();
176        if respellings > 0 {
177            counts.push(
178                Line::mark(Mark::Import)
179                    .and(Role::Plain, " ")
180                    .and(Role::Plain, respellings.to_string()),
181            );
182        }
183        if structural > 0 {
184            counts.push(
185                Line::mark(Mark::Structure)
186                    .and(Role::Plain, " ")
187                    .and(Role::Plain, structural.to_string()),
188            );
189        }
190        if notices > 0 {
191            counts.push(
192                Line::mark(Mark::ByHand)
193                    .and(Role::Plain, " ")
194                    .and(Role::Plain, notices.to_string()),
195            );
196        }
197        let counts = Self::join(counts, "  ")
198            .and(Role::Plain, "   ")
199            .and(Role::Dim, Plural(files, "file").to_string());
200        if applied {
201            self.receipt(true, history_id, counts);
202            return;
203        }
204        self.notes([counts]);
205        let mut flags = vec!["--apply to write"];
206        if !diff {
207            flags.push("--diff for the full patch");
208        }
209        self.hint(flags.join(" · "));
210    }
211
212    /// The last line of a mutating command: `counts` then, applied, the
213    /// history entry it made (`✓ #3`); otherwise the flag to go on with.
214    fn receipt(&mut self, applied: bool, history_id: Option<u64>, counts: Line) {
215        match (applied, history_id) {
216            (true, Some(id)) => self.notes([Line::mark(Mark::Safe)
217                .and(Role::Plain, " ")
218                .and(Role::Strong, format!("#{id}"))
219                .and(Role::Plain, "   ")
220                .and_line(counts)]),
221            (true, None) => self.notes([Line::mark(Mark::Safe)
222                .and(Role::Plain, "   ")
223                .and_line(counts)]),
224            (false, _) => {
225                self.notes([counts]);
226                self.hint("--apply to write");
227            }
228        }
229    }
230
231    /// `◆ old → new`, skipped for a nameless package.
232    fn addresses(&mut self, from: &Address, to: &Address) {
233        if from.package().as_str().is_empty() {
234            return;
235        }
236        self.body([Line::mark(Mark::Address)
237            .and(Role::Plain, " ")
238            .and(Role::Address, from.to_string())
239            .and(Role::Plain, " ")
240            .and_line(Line::mark(Mark::Import))
241            .and(Role::Plain, " ")
242            .and(Role::Address, to.to_string())]);
243    }
244
245    /// The `●` lines a rename or references answer opens with.
246    fn declarations(&mut self, declarations: &[Match]) {
247        self.body(declarations.iter().map(|m| l::Declaration::new(m).line()));
248        self.block_body(Block::Blank);
249    }
250
251    /// `✓ 26  ? 7  ✗ 0   4 files`, for a caller to end or continue.
252    fn verdict_counts(occurrences: &[Occurrence]) -> Line {
253        let count = |c: Confidence| occurrences.iter().filter(|o| o.confidence == c).count();
254        Line::counts(&[
255            (
256                Mark::from(Confidence::Resolved),
257                count(Confidence::Resolved),
258            ),
259            (
260                Mark::from(Confidence::Unresolved),
261                count(Confidence::Unresolved),
262            ),
263            (Mark::from(Confidence::Other), count(Confidence::Other)),
264        ])
265        .and(
266            Role::Dim,
267            format!(
268                "   {}",
269                Files::among(occurrences.iter().map(|o| o.m.path.as_path()))
270            ),
271        )
272    }
273
274    fn edits_in(files: &[FileChange]) -> usize {
275        files.iter().map(|f| f.edits.len()).sum()
276    }
277
278    /// Lines joined by `separator`.
279    fn join(parts: Vec<Line>, separator: &str) -> Line {
280        let mut line = Line::new();
281        for (i, part) in parts.into_iter().enumerate() {
282            if i > 0 {
283                line = line.and(Role::Plain, separator.to_owned());
284            }
285            line = line.and_line(part);
286        }
287        line
288    }
289
290    // ---------------------------------------------------------------- search
291
292    pub fn search(matches: &[Match], skipped: &[Skipped]) -> Self {
293        let mut report = Self::new();
294        report.block_body(Block::Matches(matches.to_vec()));
295        if matches.is_empty() {
296            report.block_note(Block::Summary(
297                Line::mark(Mark::Nothing).and(Role::Plain, " no matches"),
298            ));
299        } else {
300            report.block_note(Block::Summary(Self::search_summary(matches)));
301        }
302        for skipped in skipped {
303            report.warning(l::SkippedLine::new(skipped).line());
304        }
305        if !skipped.is_empty() {
306            report.hint(
307                "a pattern is written in one language; pass --lang to search that one only (the matches above are complete for the others)",
308            );
309        }
310        report
311    }
312
313    /// `● 1  ○ 59   13 files`: what the search found.
314    fn search_summary(matches: &[Match]) -> Line {
315        let (declarations, uses) = l::Sections::split(matches);
316        let mut counts: Vec<Line> = Vec::new();
317        if !declarations.is_empty() {
318            counts.push(
319                Line::mark(Mark::Declaration)
320                    .and(Role::Plain, " ")
321                    .and(Role::Plain, declarations.len().to_string()),
322            );
323        }
324        if !uses.is_empty() {
325            counts.push(
326                Line::of(Role::Dim, "○")
327                    .and(Role::Plain, " ")
328                    .and(Role::Plain, uses.len().to_string()),
329            );
330        }
331        Self::join(counts, "  ").and(Role::Plain, "  ").and(
332            Role::Dim,
333            Files::among(matches.iter().map(|m| m.path.as_path())).to_string(),
334        )
335    }
336
337    // --------------------------------------------------------------- outline
338
339    fn outline(result: &Outline) -> Self {
340        let mut report = Self::new();
341        report.module_header(result.module.as_ref(), &result.path);
342        if result.items.is_empty() {
343            report.block_note(Block::Summary(
344                Line::mark(Mark::Nothing).and(Role::Plain, " no declarations"),
345            ));
346            return report;
347        }
348        report.block_body(Block::Blank);
349        report.block_body(Block::Outline(result.items.clone()));
350        report.block_note(Block::Summary(Self::outline_summary(result)));
351        report
352    }
353
354    /// `● 14   pub 9  pub(crate) 1  · 4`: how many of each modifier.
355    fn outline_summary(result: &Outline) -> Line {
356        let mut counts: Vec<(String, usize)> = Vec::new();
357        for item in &result.items {
358            if item.symbol.kind == SymbolKind::Impl {
359                continue;
360            }
361            let key = item.symbol.modifier().unwrap_or("·").to_owned();
362            match counts.iter_mut().find(|(k, _)| *k == key) {
363                Some((_, n)) => *n += 1,
364                None => counts.push((key, 1)),
365            }
366        }
367        counts.sort_by_key(|(k, _)| k == "·");
368        let counts: Vec<Line> = counts
369            .iter()
370            .map(|(k, n)| {
371                Line::of(Role::Dim, k.clone())
372                    .and(Role::Plain, " ")
373                    .and(Role::Plain, n.to_string())
374            })
375            .collect();
376        Line::mark(Mark::Declaration)
377            .and(Role::Plain, " ")
378            .and(Role::Plain, result.items.len().to_string())
379            .and(Role::Plain, "   ")
380            .and_line(Self::join(counts, "  "))
381    }
382
383    // ------------------------------------------------------------ references
384
385    fn references(result: &References) -> Self {
386        let mut report = Self::new();
387        report.declarations(&result.declarations);
388        report.block_body(Block::Verdicts {
389            occurrences: result.occurrences.clone(),
390            files: None,
391        });
392        report.block_note(Block::Summary(Self::verdict_counts(&result.occurrences)));
393        report
394    }
395
396    // ------------------------------------------------------------- locations
397
398    fn locations(result: &Locations) -> Self {
399        let mut report = Self::new();
400        report.block_body(Block::Sites(result.sites.clone()));
401        report.block_note(Block::Summary(
402            Line::mark(Mark::Declaration)
403                .and(Role::Plain, " ")
404                .and(Role::Plain, result.sites.len().to_string()),
405        ));
406        if result.sites.iter().all(|s| s.import.is_none())
407            && result.sites.iter().any(|s| s.address.is_some())
408        {
409            report.hint("--from <file> for the import to write there");
410        }
411        report
412    }
413
414    // ------------------------------------------------------------------ deps
415
416    fn deps(result: &Deps) -> Self {
417        let mut report = Self::new();
418        report.module_header(result.module.as_ref(), &result.path);
419        report.block_body(Block::Blank);
420        let outgoing = l::DepGroups::statements(&result.imports);
421        report.body([Line::mark(Mark::Import)
422            .and(Role::Plain, " ")
423            .and(Role::Strong, outgoing.to_string())]);
424        if result.imports.is_empty() {
425            report.body([Line::of(Role::Plain, "  ").and_line(Line::mark(Mark::Nothing))]);
426        }
427        let own = result
428            .module
429            .as_ref()
430            .map(|m| m.package().as_str().to_owned());
431        report.block_body(Block::DepGroups {
432            imports: result.imports.clone(),
433            own,
434        });
435        report.block_body(Block::Blank);
436        let incoming = l::ImporterRows::sites(&result.importers).len();
437        report.body([Line::mark(Mark::ImportedBy)
438            .and(Role::Plain, " ")
439            .and(Role::Strong, incoming.to_string())
440            .and(Role::Plain, "   ")
441            .and(
442                Role::Dim,
443                Files::among(result.importers.iter().map(|i| i.path.as_path())).to_string(),
444            )]);
445        if result.importers.is_empty() {
446            report.body([Line::of(Role::Plain, "  ").and_line(Line::mark(Mark::Nothing))]);
447        }
448        report.block_body(Block::Importers(result.importers.clone()));
449        report.block_note(Block::Summary(Self::deps_summary(outgoing, incoming)));
450        for skipped in &result.skipped {
451            report.warning(l::SkippedLine::new(skipped).line());
452        }
453        report
454    }
455
456    fn deps_summary(outgoing: usize, incoming: usize) -> Line {
457        Line::mark(Mark::Import)
458            .and(Role::Plain, format!(" {outgoing}  "))
459            .and_line(Line::mark(Mark::ImportedBy))
460            .and(Role::Plain, format!(" {incoming}"))
461    }
462
463    // --------------------------------------------------------------- explain
464
465    fn explain(result: &Explanation) -> Self {
466        let mut report = Self::new();
467        report.block_body(Block::Explanation(Box::new(result.clone())));
468        report
469    }
470
471    // --------------------------------------------------------------- surface
472
473    fn surface(result: &Surface) -> Self {
474        let mut report = Self::new();
475        let scope = result
476            .package
477            .as_ref()
478            .map_or_else(|| "every package".to_owned(), ToString::to_string);
479        report.title(format!("surface {scope}"));
480        if result.items.is_empty() {
481            report.block_note(Block::Summary(
482                Line::mark(Mark::Nothing).and(Role::Plain, " nothing exposed"),
483            ));
484            return report;
485        }
486        report.block_body(Block::Exposed(result.items.clone()));
487        report.block_note(Block::Summary(Self::surface_summary(result)));
488        report
489    }
490
491    fn surface_summary(result: &Surface) -> Line {
492        let importers: usize = result.items.iter().map(|i| i.importers).sum();
493        Line::mark(Mark::Declaration)
494            .and(Role::Plain, " ")
495            .and(Role::Strong, result.items.len().to_string())
496            .and(Role::Plain, "   ")
497            .and_line(Line::mark(Mark::ImportedBy))
498            .and(Role::Plain, " ")
499            .and(Role::Dim, format!("{importers} imports"))
500    }
501
502    // ---------------------------------------------------------------- impact
503
504    fn impact(result: &Impact) -> Self {
505        let mut report = Self::new();
506        report.body([Line::of(Role::Title, format!("impact {}", result.name))
507            .and(Role::Plain, "   ")
508            .and(Role::Address, format!("◆ {}", result.address))]);
509        if result.consumers.is_empty() {
510            report.block_note(Block::Summary(
511                Line::mark(Mark::Nothing).and(Role::Plain, " no module imports it"),
512            ));
513            return report;
514        }
515        report.block_body(Block::Consumers(result.consumers.clone()));
516        report.block_note(Block::Summary(
517            Line::mark(Mark::ImportedBy)
518                .and(Role::Plain, " ")
519                .and(Role::Strong, result.consumers.len().to_string())
520                .and(Role::Plain, "   ")
521                .and(
522                    Role::Dim,
523                    Files::among(result.consumers.iter().map(|c| c.path.as_path())).to_string(),
524                ),
525        ));
526        report
527    }
528
529    // ------------------------------------------------------------------ dead
530
531    fn dead(result: &Dead) -> Self {
532        let mut report = Self::new();
533        report.title("dead");
534        if result.items.is_empty() {
535            report.block_note(Block::Summary(
536                Line::mark(Mark::Nothing).and(Role::Plain, " everything is referred to"),
537            ));
538            return report;
539        }
540        report.block_body(Block::Dead(result.items.clone()));
541        report.block_note(Block::Summary(Self::dead_summary(result)));
542        report
543    }
544
545    fn dead_summary(result: &Dead) -> Line {
546        let unsure = result.items.iter().filter(|i| i.unsure > 0).count();
547        Line::mark(Mark::Declaration)
548            .and(Role::Plain, " ")
549            .and(Role::Strong, result.items.len().to_string())
550            .and(Role::Plain, "   ")
551            .and_line(Line::mark(Mark::Unverified))
552            .and(Role::Plain, " ")
553            .and(
554                Role::Dim,
555                format!("{unsure} with tokens that might be uses"),
556            )
557    }
558
559    // --------------------------------------------------------------- imports
560
561    fn imports(result: &ImportsReport) -> Self {
562        let mut report = Self::new();
563        let scope = result.path.as_ref().map_or_else(
564            || "every file".to_owned(),
565            |path| path.display().to_string(),
566        );
567        report.title(format!("imports {scope}"));
568        let sections: [(Mark, &str, &[ImportSite]); 3] = [
569            (Mark::Nothing, "unresolved", &result.unresolved),
570            (Mark::ByHand, "unused", &result.unused),
571            (Mark::ByHand, "redundant", &result.redundant),
572        ];
573        let total: usize = sections.iter().map(|(_, _, s)| s.len()).sum();
574        if total == 0 {
575            report.block_note(Block::Summary(
576                Line::mark(Mark::Nothing).and(Role::Plain, " nothing to look at"),
577            ));
578            return report;
579        }
580        report.block_body(Block::Imports {
581            unresolved: result.unresolved.clone(),
582            unused: result.unused.clone(),
583            redundant: result.redundant.clone(),
584        });
585        report.block_note(Block::Summary(Self::imports_summary(
586            &sections,
587            result.unplaced.len(),
588        )));
589        report
590    }
591
592    fn imports_summary(sections: &[(Mark, &str, &[ImportSite])], unplaced: usize) -> Line {
593        let mut counts: Vec<Line> = sections
594            .iter()
595            .filter(|(_, _, s)| !s.is_empty())
596            .map(|(mark, word, s)| {
597                Line::mark(*mark)
598                    .and(Role::Plain, format!(" {word} "))
599                    .and(Role::Plain, s.len().to_string())
600            })
601            .collect();
602        if unplaced > 0 {
603            counts.push(
604                Line::mark(Mark::Nothing)
605                    .and(Role::Plain, " ")
606                    .and(Role::Dim, "not placed")
607                    .and(Role::Plain, " ")
608                    .and(Role::Dim, unplaced.to_string()),
609            );
610        }
611        Self::join(counts, "   ")
612    }
613
614    // --------------------------------------------------------------- rewrite
615
616    fn rewrite(result: &Rewrite) -> Self {
617        let mut report = Self::new();
618        report.title(IntentLine(&Intent::Rewrite(result.intent.clone())));
619        report.block_body(Block::Changes(result.files.clone()));
620        let edits = Self::edits_in(&result.files);
621        if edits == 0 {
622            report.block_note(Block::Summary(
623                Line::mark(Mark::Nothing).and(Role::Plain, " no matches"),
624            ));
625            return report;
626        }
627        report.receipt(
628            result.applied,
629            result.history_id,
630            Line::mark(Mark::Rewrite)
631                .and(Role::Plain, format!(" {edits}   "))
632                .and(Role::Dim, Plural(result.files.len(), "file").to_string()),
633        );
634        report
635    }
636
637    // ---------------------------------------------------------------- rename
638
639    fn rename(result: &Rename, options: Options) -> Self {
640        let mut report = Self::new();
641        report.title(IntentLine(&Intent::Rename(result.intent.clone())));
642        report.declarations(&result.declarations);
643        report.block_body(Block::Verdicts {
644            occurrences: result.occurrences.clone(),
645            files: Some(result.files.clone()),
646        });
647        let strip = Self::verdict_counts(&result.occurrences);
648        let edits = Self::edits_in(&result.files);
649        let plan = Line::of(
650            Role::Dim,
651            format!(
652                "→ {} in {}",
653                Plural(edits, "occurrence"),
654                Plural(result.files.len(), "file")
655            ),
656        );
657        if result.applied {
658            report.block_note(Block::Summary(strip));
659            report.receipt(true, result.history_id, plan);
660            return report;
661        }
662        report.block_note(Block::Summary(strip.and(Role::Plain, "   ").and_line(plan)));
663        let unsure = l::Verdicts::selection(&result.occurrences, Confidence::Unresolved);
664        let mut flags = vec!["--apply to write".to_owned()];
665        if !unsure.is_empty() {
666            flags.push(format!("--select {unsure} for the ? rows alone"));
667        }
668        if !options.verbose
669            && result
670                .occurrences
671                .iter()
672                .any(|o| o.confidence == Confidence::Resolved)
673        {
674            flags.push("-v to list the ✓ rows".to_owned());
675        }
676        report.hint(flags.join(" · "));
677        report
678    }
679
680    // ----------------------------------------------------------------- moves
681
682    fn move_file(result: &Move, options: Options) -> Self {
683        let mut report = Self::new();
684        // Normalised paths, not the ones typed: what history will show.
685        report.title(IntentLine(&Intent::Move(MoveIntent::new(
686            &result.from,
687            &result.to,
688        ))));
689        if let (Some(from), Some(to)) = (&result.from_address, &result.to_address) {
690            report.addresses(from, to);
691        }
692        report.block_body(Block::Blank);
693        let structural = report.moved(&result.files, &result.respellings, &result.notices);
694        report.moved_summary(
695            result.applied,
696            result.history_id,
697            MoveCounts {
698                respellings: result.respellings.len(),
699                structural,
700                notices: result.notices.len(),
701                files: result.files.len(),
702            },
703            options.diff,
704        );
705        report
706    }
707
708    fn move_symbol(result: &MoveSymbol, options: Options) -> Self {
709        let mut report = Self::new();
710        report.title(IntentLine(&Intent::MoveSymbol(result.intent.clone())));
711        report.addresses(&result.from, &result.to);
712        report.block_body(Block::Blank);
713        let structural = report.moved(&result.files, &result.respellings, &result.notices);
714        report.moved_summary(
715            result.applied,
716            result.history_id,
717            MoveCounts {
718                respellings: result.respellings.len(),
719                structural,
720                notices: result.notices.len(),
721                files: result.files.len(),
722            },
723            options.diff,
724        );
725        report
726    }
727
728    fn batch(result: &Batch, options: Options) -> Self {
729        let mut report = Self::new();
730        report.title(IntentLine(&Intent::Batch(BatchIntent {
731            intents: result.intents.clone(),
732        })));
733        report.block_body(Block::Batch(result.intents.clone()));
734        report.block_body(Block::Blank);
735        // Steps compose, so no edit is one re-spelled path: every file is a hunk.
736        let structural = report.moved(&result.files, &[], &result.notices);
737        report.moved_summary(
738            result.applied,
739            result.history_id,
740            MoveCounts {
741                respellings: 0,
742                structural,
743                notices: result.notices.len(),
744                files: result.files.len(),
745            },
746            options.diff,
747        );
748        report
749    }
750
751    // ------------------------------------------------------------------ undo
752
753    fn undo(result: &Undo) -> Self {
754        let mut report = Self::new();
755        report.title(format!(
756            "{} #{}  {}",
757            Mark::Undo.glyph(),
758            result.undone.id,
759            IntentLine(&result.undone.intent)
760        ));
761        report.block_body(Block::Undo {
762            moves: result.moves_reverted.clone(),
763            restored: result.restored.clone(),
764        });
765        report.block_note(Block::Summary(
766            Line::mark(Mark::Undo)
767                .and(Role::Plain, " ")
768                .and(Role::Plain, format!("#{}   ", result.undone.id))
769                .and(Role::Dim, Plural(result.restored.len(), "file").to_string()),
770        ));
771        report
772    }
773
774    // --------------------------------------------------------------- history
775
776    fn history(result: &History) -> Self {
777        let mut report = Self::new();
778        if result.entries.is_empty() {
779            report.block_note(Block::Summary(
780                Line::mark(Mark::Nothing).and(Role::Plain, " no history"),
781            ));
782            report
783                .hint("--apply writes a plan and records it here; `vvv undo` reverses the newest");
784            return report;
785        }
786        let last = result.entries.len() - 1;
787        report.block_body(Block::History(result.entries.clone()));
788        report.block_note(Block::Summary(
789            Line::of(
790                Role::Plain,
791                Plural(result.entries.len(), "entry").to_string(),
792            )
793            .and(Role::Plain, "   ")
794            .and_line(Line::mark(Mark::Undo))
795            .and(Role::Plain, format!(" #{}", result.entries[last].id)),
796        ));
797        report
798    }
799}
800
801/// One piece of a report, named for what it is so a view can place it.
802#[derive(Debug, Clone)]
803pub enum Block {
804    /// The command and its intent: its own line, then a blank.
805    Title(String),
806    /// A section label.
807    Heading(String),
808    /// Found rows — hits — that a view numbers and groups.
809    Matches(Vec<Match>),
810    /// Occurrences a view judges: a reference, a rename.
811    Verdicts {
812        occurrences: Vec<Occurrence>,
813        /// The files a plan would change, when there is one, so a view can
814        /// mark the rows an edit touches (`±`).
815        files: Option<Vec<FileChange>>,
816    },
817    /// Import sites worth a look: unresolved, then unused, then redundant.
818    Imports {
819        unresolved: Vec<ImportSite>,
820        unused: Vec<ImportSite>,
821        redundant: Vec<ImportSite>,
822    },
823    /// What a file imports, grouped by package; `own` is its own, to mark.
824    DepGroups {
825        imports: Vec<Dep>,
826        own: Option<String>,
827    },
828    /// Who imports a file.
829    Importers(Vec<Importer>),
830    /// What is at a position, and how it is reached.
831    Explanation(Box<Explanation>),
832    /// A file's declarations as a tree, a view aligning the name column.
833    Outline(Vec<OutlineItem>),
834    /// Where a name is declared: the sites `where` found.
835    Sites(Vec<Site>),
836    /// Declarations nothing refers to, and the unsure-token count of each.
837    Dead(Vec<Unreferenced>),
838    /// A package's exposed names, and how many import each.
839    Exposed(Vec<Exposed>),
840    /// The modules that import a declaration, nearest first.
841    Consumers(Vec<Consumer>),
842    /// The ledger, oldest first.
843    History(Vec<HistoryEntry>),
844    /// A batch's steps, in order.
845    Batch(Vec<Intent>),
846    /// What `undo` reversed: moves, then restored files.
847    Undo {
848        moves: Vec<(RelPath, RelPath)>,
849        restored: Vec<RelPath>,
850    },
851    /// A bare line.
852    Line(Line),
853    /// The closing summary: what happened, and what to do next.
854    Summary(Line),
855    /// A hint or a warning.
856    Note(Note),
857    /// The change a plan would make: one file's edits, laid out as a diff.
858    Changes(Vec<FileChange>),
859    /// A move preview: the changes, and what a plan re-spelled or left by hand.
860    Moved {
861        files: Vec<FileChange>,
862        respellings: Vec<Respelling>,
863        notices: Vec<Notice>,
864    },
865    /// A vertical gap.
866    Blank,
867}
868
869/// A row: the line to draw, and the source it stands for.
870#[derive(Debug, Clone)]
871pub struct Row {
872    pub line: Line,
873    /// Where the row is, when an interface can act on it.
874    pub source: Option<Source>,
875}
876
877/// The source a row stands for: the file and the line in it.
878#[derive(Debug, Clone, PartialEq, Eq)]
879pub struct Source {
880    pub path: RelPath,
881    pub line: u32,
882}
883
884impl Row {
885    /// A row no renderer can act on.
886    pub fn new(line: Line) -> Self {
887        Self { line, source: None }
888    }
889
890    /// A row that stands for a source.
891    pub fn at(line: Line, path: RelPath, at: u32) -> Self {
892        Self {
893            line,
894            source: Some(Source { path, line: at }),
895        }
896    }
897
898    /// Wrap plain lines as rows no renderer can act on.
899    pub fn wrap(lines: Vec<Line>) -> Vec<Self> {
900        lines.into_iter().map(Self::new).collect()
901    }
902}
903
904/// A hint or a warning: a view prefixes each.
905#[derive(Debug, Clone)]
906pub enum Note {
907    Hint(String),
908    Warning(Line),
909}
910
911/// The counts a move's summary line reports.
912struct MoveCounts {
913    respellings: usize,
914    structural: usize,
915    notices: usize,
916    files: usize,
917}