Skip to main content

vvv_engine/protocol/
result.rs

1//! What each command answers with. A mutating command answers the same shape
2//! whether it previewed or wrote: `applied` and `history_id` say which.
3
4use vvv_core::RelPath;
5
6use serde::{Deserialize, Serialize};
7use vvv_core::{Address, Edit, Query};
8
9use super::diff::UnifiedDiff;
10use super::{
11    BatchIntent, Intent, Match, MoveIntent, MoveSymbolIntent, Notice, Occurrence, RenameIntent,
12    Respelling, RewriteIntent, Skipped,
13};
14use crate::plan::{FilePreview, Plan};
15
16/// `vvv search`: what was found, and which languages could not be asked.
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct Search {
19    pub query: Query,
20    pub matches: Vec<Match>,
21    /// Languages whose grammar could not compile the query; their files
22    /// were not searched.
23    #[serde(default, skip_serializing_if = "Vec::is_empty")]
24    pub skipped: Vec<Skipped>,
25}
26
27/// `vvv rewrite`: one edit per selected match.
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct Rewrite {
30    pub intent: RewriteIntent,
31    /// `true` when the files were written; otherwise this is a preview.
32    pub applied: bool,
33    /// The history entry the apply made, when `applied`; what `undo` reverses.
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub history_id: Option<u64>,
36    pub files: Vec<FileChange>,
37}
38
39/// `vvv rename`: the declaration and every occurrence, each judged.
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct Rename {
42    pub intent: RenameIntent,
43    pub applied: bool,
44    /// The history entry the apply made, when `applied`; what `undo` reverses.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub history_id: Option<u64>,
47    /// Where `name` is declared; more than one means the rename is ambiguous.
48    pub declarations: Vec<Match>,
49    /// Every identifier spelling the name, each judged against the target;
50    /// their ids feed a later `--select`.
51    pub occurrences: Vec<Occurrence>,
52    pub files: Vec<FileChange>,
53}
54
55/// `vvv move`: a file or directory moved, its importers respelled.
56#[derive(Debug, Clone, Serialize, Deserialize)]
57pub struct Move {
58    pub intent: MoveIntent,
59    pub applied: bool,
60    /// The history entry the apply made, when `applied`; what `undo` reverses.
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub history_id: Option<u64>,
63    /// Normalised, workspace-relative source and destination.
64    pub from: RelPath,
65    pub to: RelPath,
66    /// The module address before and after, when the language has one.
67    #[serde(default, skip_serializing_if = "Option::is_none")]
68    pub from_address: Option<Address>,
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub to_address: Option<Address>,
71    /// References vvv found but could not rewrite.
72    #[serde(default, skip_serializing_if = "Vec::is_empty")]
73    pub notices: Vec<Notice>,
74    /// References rewritten in place; every other edit in `files` is
75    /// structural (a `mod` line moved, a visibility widened).
76    #[serde(default, skip_serializing_if = "Vec::is_empty")]
77    pub respellings: Vec<Respelling>,
78    pub files: Vec<FileChange>,
79}
80
81/// `vvv move --symbol`: one declaration moved between files.
82#[derive(Debug, Clone, Serialize, Deserialize)]
83pub struct MoveSymbol {
84    pub intent: MoveSymbolIntent,
85    pub applied: bool,
86    /// The history entry the apply made, when `applied`; what `undo` reverses.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub history_id: Option<u64>,
89    /// The declaration's address before and after.
90    pub from: Address,
91    pub to: Address,
92    #[serde(default, skip_serializing_if = "Vec::is_empty")]
93    pub notices: Vec<Notice>,
94    /// Consumers rewritten in place; every other edit in `files` is the
95    /// declaration itself moving.
96    #[serde(default, skip_serializing_if = "Vec::is_empty")]
97    pub respellings: Vec<Respelling>,
98    pub files: Vec<FileChange>,
99}
100
101/// `vvv batch`: several intents planned in sequence and applied as one.
102#[derive(Debug, Clone, Serialize, Deserialize)]
103pub struct Batch {
104    pub intents: Vec<Intent>,
105    /// `true` when the files were written; otherwise this is a preview.
106    pub applied: bool,
107    /// The history entry the apply made, when `applied`; what `undo` reverses.
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub history_id: Option<u64>,
110    #[serde(default, skip_serializing_if = "Vec::is_empty")]
111    pub notices: Vec<Notice>,
112    /// Every file any step touches, before the first step against after the
113    /// last. Edits are not listed per file: they belong to the steps, each in
114    /// the coordinates of the state before it.
115    pub files: Vec<FileChange>,
116}
117
118/// One apply that can still be undone.
119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
120pub struct HistoryEntry {
121    pub id: u64,
122    /// Seconds since the Unix epoch.
123    pub at: u64,
124    /// What was applied, as data; the display layer renders it.
125    pub intent: Intent,
126    /// How many files it wrote.
127    pub files: usize,
128    /// The files it wrote, at their pre-apply paths: what undo restores.
129    #[serde(default, skip_serializing_if = "Vec::is_empty")]
130    pub paths: Vec<RelPath>,
131    /// Moves it made, as (from, to) pairs: what undo reverts.
132    #[serde(default, skip_serializing_if = "Vec::is_empty")]
133    pub moves: Vec<(RelPath, RelPath)>,
134}
135
136/// `vvv history`.
137#[derive(Debug, Clone, Serialize, Deserialize)]
138pub struct History {
139    /// Oldest first; the last entry is what `vvv undo` would reverse.
140    pub entries: Vec<HistoryEntry>,
141}
142
143/// `vvv undo`.
144#[derive(Debug, Clone, Serialize, Deserialize)]
145pub struct Undo {
146    pub undone: HistoryEntry,
147    /// Files restored to their pre-apply contents, at their pre-apply paths.
148    pub restored: Vec<RelPath>,
149    /// Moves reverted, as (original, moved-to) pairs.
150    #[serde(default, skip_serializing_if = "Vec::is_empty")]
151    pub moves_reverted: Vec<(RelPath, RelPath)>,
152}
153
154/// One file a plan touches: its edits and the whole-file diff.
155#[derive(Debug, Clone, Serialize, Deserialize)]
156pub struct FileChange {
157    /// Path before the change.
158    pub path: RelPath,
159    /// Path after, when the file is moved.
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub moved_to: Option<RelPath>,
162    pub edits: Vec<Edit>,
163    pub diff: UnifiedDiff,
164}
165
166impl FileChange {
167    /// One entry per previewed file, with the plan's edits for it when a
168    /// single plan made them (a batch's belong to its steps).
169    pub(crate) fn all(plan: Option<&Plan>, preview: &[FilePreview]) -> Vec<Self> {
170        preview
171            .iter()
172            .map(|file| FileChange {
173                path: file.path.clone(),
174                moved_to: file.moved_to.clone(),
175                edits: plan
176                    .map_or_else(Vec::new, |p| p.change_set().edits_for(&file.path).to_vec()),
177                diff: UnifiedDiff::between(
178                    &file.path,
179                    file.moved_to.as_deref().unwrap_or(&file.path),
180                    &file.before,
181                    &file.after,
182                ),
183            })
184            .collect()
185    }
186}
187
188/// A result that can be written: what `Engine::apply` needs from it and
189/// tells it.
190pub trait Mutation {
191    /// What is recorded in history.
192    fn intent(&self) -> Intent;
193    /// Mark the result as written by history entry `id`.
194    fn applied(&mut self, id: u64);
195}
196
197macro_rules! mutation {
198    ($t:ty, $variant:ident) => {
199        impl Mutation for $t {
200            fn intent(&self) -> Intent {
201                Intent::$variant(self.intent.clone())
202            }
203            fn applied(&mut self, id: u64) {
204                self.applied = true;
205                self.history_id = Some(id);
206            }
207        }
208    };
209}
210
211mutation!(Rewrite, Rewrite);
212mutation!(Rename, Rename);
213mutation!(Move, Move);
214mutation!(MoveSymbol, MoveSymbol);
215
216impl Mutation for Batch {
217    fn intent(&self) -> Intent {
218        Intent::Batch(BatchIntent {
219            intents: self.intents.clone(),
220        })
221    }
222    fn applied(&mut self, id: u64) {
223        self.applied = true;
224        self.history_id = Some(id);
225    }
226}