Skip to main content

vvv_engine/report/
document.rs

1//! Shared document construction and delegation to capability-owned composition.
2use super::lines as l;
3use super::{Block, MoveCounts, Note};
4use crate::protocol::display::{Line, Role};
5use crate::protocol::vocabulary::{Files, Mark, Plural};
6use crate::{Answer, Confidence, Failure, FileChange, Match, Notice, Occurrence, Respelling};
7
8/// A command's output, one sequence of blocks per stream: results, then
9/// notes (summaries, hints, warnings).
10#[derive(Debug, Default, Clone)]
11pub struct Document {
12    body: Vec<Block>,
13    notes: Vec<Block>,
14}
15
16impl Document {
17    pub fn new() -> Self {
18        Self::default()
19    }
20
21    /// Append bare lines to the result stream.
22    pub fn body(&mut self, lines: impl IntoIterator<Item = Line>) {
23        self.body.extend(lines.into_iter().map(Block::Line));
24    }
25
26    /// Append bare lines to the note stream.
27    pub fn notes(&mut self, lines: impl IntoIterator<Item = Line>) {
28        self.notes.extend(lines.into_iter().map(Block::Line));
29    }
30
31    /// Append one structured block to the result stream.
32    pub fn block_body(&mut self, block: Block) {
33        self.body.push(block);
34    }
35
36    /// Append one structured block to the note stream.
37    pub fn block_note(&mut self, block: Block) {
38        self.notes.push(block);
39    }
40
41    /// Both streams, for the view.
42    pub fn parts(&self) -> (&[Block], &[Block]) {
43        (&self.body, &self.notes)
44    }
45
46    // ------------------------------------------------------------------ entry
47
48    /// Compose one answer into the blocks its command prints.
49    pub fn of(answer: &Answer) -> Self {
50        match answer {
51            Answer::DiscardPlan(r) => Self::plan_review(r),
52            Answer::ApplyPlan(r) => Self::plan_receipt(r),
53            Answer::ValidatePlan(r) => Self::validation(r),
54            Answer::InspectPlan(r) => Self::plan_reply(r),
55            Answer::PrepareRename(r)
56            | Answer::PrepareRewrite(r)
57            | Answer::PrepareMove(r)
58            | Answer::PrepareMoveSymbol(r) => Self::plan_reply(r),
59            Answer::ReviewPlan(r) => Self::plan_page(r),
60            #[cfg(feature = "schema")]
61            Answer::Schema(r) => Self::schema(r),
62            Answer::SearchPage(r) => Self::search_page(r),
63            Answer::ContextPage(r) => Self::context_page(r),
64            Answer::Continue(r) => Self::page(r),
65            Answer::Expand(r) => Self::expansion(r),
66            Answer::Discover(r) => Self::discovery(r),
67            Answer::Context(r) => Self::context(r),
68            Answer::Relationships(r) => Self::relationships(r),
69            Answer::Resolve(r) => Self::resolution(r),
70            Answer::Navigate(r) => Self::navigation(r),
71            Answer::Search(r) => Self::search(&r.matches, &r.skipped),
72            Answer::Outline(r) => Self::outline(r),
73            Answer::References(r) => Self::references(r),
74            Answer::Where(r) => Self::locations(r),
75            Answer::Deps(r) => Self::deps(r),
76            Answer::Explain(r) => Self::explain(r),
77            Answer::Surface(r) => Self::surface(r),
78            Answer::Impact(r) => Self::impact(r),
79            Answer::Dead(r) => Self::dead(r),
80            Answer::Imports(r) => Self::imports(r),
81            // The file answer is the picker's; no CLI command asks for one.
82            Answer::WorkspaceFiles(files) => Self::workspace_files(files),
83            Answer::File(_) => Self::new(),
84            Answer::Rewrite(r) => Self::rewrite(r),
85            Answer::Rename(r) => Self::rename(r),
86            Answer::Move(r) => Self::move_file(r),
87            Answer::MoveSymbol(r) => Self::move_symbol(r),
88            Answer::SymbolMoveCandidates(r) => Self::symbol_move_candidates(r),
89            Answer::Batch(r) => Self::batch(r),
90            Answer::Undo(r) => Self::undo(r),
91            Answer::History(r) => Self::history(r),
92        }
93    }
94
95    /// Compose a failure as `✗ message`; interfaces present its hints.
96    pub fn error(failure: &Failure) -> Self {
97        let mut report = Self::new();
98        report.notes([Line::single(Role::Error, "✗ ").and(Role::Plain, failure.message.clone())]);
99        report
100    }
101
102    // ---------------------------------------------------------------- helpers
103
104    /// A title line, then a blank.
105    pub(crate) fn title(&mut self, text: impl std::fmt::Display) {
106        self.block_body(Block::Title(text.to_string()));
107    }
108
109    /// `warning: …` on the note stream.
110    pub(crate) fn warning(&mut self, line: Line) {
111        self.block_note(Block::Note(Note::Warning(line)));
112    }
113
114    /// `path`: the file the command opened.
115    pub(crate) fn file_header(&mut self, path: &std::path::Path) {
116        self.body([Line::single(Role::Path, path.display().to_string())]);
117    }
118
119    /// The body of a move preview: counts, the `→` rows, the `!` rows, and a
120    /// `±` hunk for every file whose edits are more than re-spelled paths.
121    /// Answers how many are structural.
122    pub(crate) fn moved(
123        &mut self,
124        state: crate::MutationState,
125        files: &[FileChange],
126        respellings: &[Respelling],
127        notices: &[Notice],
128    ) -> usize {
129        let structural = files
130            .iter()
131            .filter(|f| l::Diff::is_structural(f, respellings))
132            .count();
133        self.block_body(Block::Moved {
134            state,
135            files: files.to_vec(),
136            respellings: respellings.to_vec(),
137            notices: notices.to_vec(),
138        });
139        structural
140    }
141
142    /// `→ 12  ± 2  ! 1   12 files` on the note stream, then the verdict.
143    pub(crate) fn moved_summary(&mut self, state: crate::MutationState, counts: MoveCounts) {
144        let MoveCounts {
145            respellings,
146            structural,
147            notices,
148            files,
149        } = counts;
150        let mut counts: Vec<Line> = Vec::new();
151        if respellings > 0 {
152            counts.push(
153                Line::mark(Mark::Import)
154                    .and(Role::Plain, " ")
155                    .and(Role::Plain, respellings.to_string()),
156            );
157        }
158        if structural > 0 {
159            counts.push(
160                Line::mark(Mark::Structure)
161                    .and(Role::Plain, " ")
162                    .and(Role::Plain, structural.to_string()),
163            );
164        }
165        if notices > 0 {
166            counts.push(
167                Line::mark(Mark::ByHand)
168                    .and(Role::Plain, " ")
169                    .and(Role::Plain, notices.to_string()),
170            );
171        }
172        let counts = Self::join(counts, "  ")
173            .and(Role::Plain, "   ")
174            .and(Role::Dim, Plural(files, "file").to_string());
175        if state.is_applied() {
176            self.receipt(state, counts);
177            return;
178        }
179        self.notes([counts]);
180    }
181
182    /// The last line of a mutating command: `counts` then, applied, the
183    /// history entry it made (`✓ #3`).
184    pub(crate) fn receipt(&mut self, state: crate::MutationState, counts: Line) {
185        match state {
186            crate::MutationState::Applied { history_id } => self.notes([Line::mark(Mark::Safe)
187                .and(Role::Plain, " ")
188                .and(Role::Strong, format!("#{history_id}"))
189                .and(Role::Plain, "   ")
190                .and_line(counts)]),
191            crate::MutationState::Preview => self.notes([counts]),
192        }
193    }
194
195    /// The `●` lines a rename or references answer opens with.
196    pub(crate) fn declarations(&mut self, declarations: &[Match]) {
197        self.block_body(Block::Declarations(declarations.to_vec()));
198        self.block_body(Block::Blank);
199    }
200
201    /// `✓ 26  ? 7  ✗ 0   4 files`, for a caller to end or continue.
202    pub(crate) fn verdict_counts(occurrences: &[Occurrence]) -> Line {
203        let count = |c: Confidence| occurrences.iter().filter(|o| o.confidence == c).count();
204        Line::counts(&[
205            (
206                Mark::from(Confidence::Resolved),
207                count(Confidence::Resolved),
208            ),
209            (
210                Mark::from(Confidence::Unresolved),
211                count(Confidence::Unresolved),
212            ),
213            (Mark::from(Confidence::Other), count(Confidence::Other)),
214        ])
215        .and(
216            Role::Dim,
217            format!(
218                "   {}",
219                Files::among(occurrences.iter().map(|o| o.m.path.as_path()))
220            ),
221        )
222    }
223
224    pub(crate) fn edits_in(files: &[FileChange]) -> usize {
225        files.iter().map(|f| f.edits.len()).sum()
226    }
227
228    /// Lines joined by `separator`.
229    pub(crate) fn join(parts: Vec<Line>, separator: &str) -> Line {
230        let mut line = Line::new();
231        for (i, part) in parts.into_iter().enumerate() {
232            if i > 0 {
233                line = line.and(Role::Plain, separator.to_owned());
234            }
235            line = line.and_line(part);
236        }
237        line
238    }
239}