Skip to main content

vvv_engine/plan/
mod.rs

1//! The mutation lifecycle: a [`Plan`] is previewed, then consumed by `apply`
2//! into a [`Receipt`] that can roll the change back.
3//!
4//! A plan remembers a fingerprint of every file it touches. Preview and apply
5//! refuse to proceed if a file changed since planning, so an agent that runs
6//! `rewrite` (preview) and later `rewrite --apply` cannot corrupt edits made
7//! in between.
8
9use std::collections::{BTreeMap, BTreeSet};
10use std::path::{Path, PathBuf};
11
12use serde::{Deserialize, Serialize};
13
14mod fingerprint;
15mod planned;
16
17pub use fingerprint::Fingerprint;
18pub use planned::Planned;
19
20use crate::{VfsError, Workspace};
21use vvv_core::ChangeSet;
22use vvv_core::RelPath;
23
24#[derive(Debug, thiserror::Error)]
25pub enum ApplyError {
26    #[error(transparent)]
27    Vfs(#[from] VfsError),
28    #[error("{} changed since the plan was made", path.display())]
29    Stale { path: RelPath },
30    #[error("{} changed since it was written; refusing to undo", path.display())]
31    Modified { path: RelPath },
32    #[error("writing {} failed; {restored} file(s) restored: {source}", path.display())]
33    Write {
34        path: RelPath,
35        restored: usize,
36        #[source]
37        source: VfsError,
38    },
39}
40
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42pub struct Plan {
43    change_set: ChangeSet,
44    fingerprints: BTreeMap<PathBuf, Fingerprint>,
45}
46
47impl Plan {
48    /// Bind a change set to the current contents of the files it touches.
49    pub fn new(change_set: ChangeSet, workspace: &Workspace) -> Result<Self, VfsError> {
50        let fingerprints = change_set
51            .paths()
52            .map(|path| {
53                let text = workspace.vfs().read(&workspace.absolute(path))?;
54                Ok((path.to_path_buf(), Fingerprint::of(&text)))
55            })
56            .collect::<Result<_, VfsError>>()?;
57        Ok(Self {
58            change_set,
59            fingerprints,
60        })
61    }
62
63    pub fn change_set(&self) -> &ChangeSet {
64        &self.change_set
65    }
66
67    pub fn is_empty(&self) -> bool {
68        self.change_set.is_empty()
69    }
70
71    pub fn preview(&self, workspace: &Workspace) -> Result<Preview, ApplyError> {
72        Ok(Preview {
73            files: self.stage(workspace)?,
74        })
75    }
76
77    pub fn apply(self, workspace: &Workspace) -> Result<Receipt, ApplyError> {
78        let staged = self.stage(workspace)?;
79        let vfs = workspace.vfs();
80        let mut receipt = Receipt::default();
81        for file in &staged {
82            let result = match &file.moved_to {
83                Some(to) => vfs
84                    .rename(&workspace.absolute(&file.path), &workspace.absolute(to))
85                    .and_then(|()| {
86                        receipt
87                            .moves
88                            .push((file.path.to_path_buf(), to.to_path_buf()));
89                        vfs.write(&workspace.absolute(to), &file.after)
90                    }),
91                None => vfs.write(&workspace.absolute(&file.path), &file.after),
92            };
93            if let Err(source) = result {
94                let restored = receipt.rollback(workspace).unwrap_or(0);
95                return Err(ApplyError::Write {
96                    path: file.path.clone(),
97                    restored,
98                    source,
99                });
100            }
101            receipt
102                .originals
103                .insert(file.path.to_path_buf(), file.before.clone());
104            let final_path = file.moved_to.clone().unwrap_or_else(|| file.path.clone());
105            receipt
106                .written
107                .insert(final_path.to_path_buf(), Fingerprint::of(&file.after));
108        }
109        Ok(receipt)
110    }
111
112    /// Read every touched file, check it is unchanged, and compute its new contents.
113    fn stage(&self, workspace: &Workspace) -> Result<Vec<FilePreview>, ApplyError> {
114        self.fingerprints
115            .iter()
116            .map(|(path, expected)| {
117                let before = workspace.vfs().read(&workspace.absolute(path))?;
118                if &Fingerprint::of(&before) != expected {
119                    return Err(ApplyError::Stale {
120                        path: path.clone().into(),
121                    });
122                }
123                let after = self.change_set.apply_to(path, &before);
124                Ok(FilePreview {
125                    path: path.clone().into(),
126                    moved_to: self.change_set.destination(path).map(Into::into),
127                    before,
128                    after,
129                })
130            })
131            .collect()
132    }
133}
134
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub struct Preview {
137    pub files: Vec<FilePreview>,
138}
139
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct FilePreview {
142    /// Path before the plan runs.
143    pub path: RelPath,
144    /// Path after, when the plan moves the file.
145    pub moved_to: Option<RelPath>,
146    pub before: String,
147    pub after: String,
148}
149
150/// Proof that a plan was applied, holding what is needed to undo it.
151#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
152pub struct Receipt {
153    /// Pre-apply contents keyed by pre-apply path.
154    originals: BTreeMap<PathBuf, String>,
155    /// Moves performed, in order.
156    #[serde(default, skip_serializing_if = "Vec::is_empty")]
157    moves: Vec<(PathBuf, PathBuf)>,
158    /// What was written, keyed by post-apply path, so an undo can tell
159    /// whether the files have been touched since.
160    #[serde(default)]
161    written: BTreeMap<PathBuf, Fingerprint>,
162}
163
164impl Receipt {
165    pub fn paths(&self) -> impl Iterator<Item = &Path> {
166        self.originals.keys().map(PathBuf::as_path)
167    }
168
169    pub fn moves(&self) -> &[(PathBuf, PathBuf)] {
170        &self.moves
171    }
172
173    /// This apply followed by `next`, as one receipt: rolling it back undoes
174    /// both, checking it checks the files as `next` left them. Originals are
175    /// the first ones seen for a file; a path `next` touched that this apply
176    /// had already written keeps this apply's original.
177    pub fn then(mut self, next: Receipt) -> Receipt {
178        let written_here: BTreeSet<PathBuf> = self.written.keys().cloned().collect();
179        for (path, original) in next.originals {
180            if !written_here.contains(&path) {
181                self.originals.entry(path).or_insert(original);
182            }
183        }
184        let moved_away: BTreeSet<&PathBuf> = next.moves.iter().map(|(from, _)| from).collect();
185        self.written.retain(|path, _| !moved_away.contains(path));
186        self.written.extend(next.written);
187        self.moves.extend(next.moves);
188        self
189    }
190
191    /// Undo: move files back, then restore every file to its pre-apply
192    /// contents. Returns how many files were restored. Does not check that
193    /// the files are still as written; see [`Receipt::undo`].
194    pub fn rollback(&self, workspace: &Workspace) -> Result<usize, VfsError> {
195        let vfs = workspace.vfs();
196        for (from, to) in self.moves.iter().rev() {
197            vfs.rename(&workspace.absolute(to), &workspace.absolute(from))?;
198        }
199        for (path, original) in &self.originals {
200            vfs.write(&workspace.absolute(path), original)?;
201        }
202        Ok(self.originals.len())
203    }
204
205    /// Roll back only if every file is still exactly as this apply left it.
206    pub fn undo(&self, workspace: &Workspace) -> Result<usize, ApplyError> {
207        for (path, expected) in &self.written {
208            let current = workspace.vfs().read(&workspace.absolute(path))?;
209            if &Fingerprint::of(&current) != expected {
210                return Err(ApplyError::Modified {
211                    path: path.clone().into(),
212                });
213            }
214        }
215        Ok(self.rollback(workspace)?)
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use std::sync::Arc;
222
223    use super::*;
224    use crate::MemoryVfs;
225    use vvv_core::{Edit, Span};
226
227    fn workspace() -> Workspace {
228        let vfs = MemoryVfs::new()
229            .with_file("/ws/a.txt", "hello world")
230            .with_file("/ws/b.txt", "foo");
231        Workspace::new("/ws", Arc::new(vfs))
232    }
233
234    fn plan(ws: &Workspace) -> Plan {
235        let mut cs = ChangeSet::new();
236        cs.insert("a.txt", Edit::replace(Span::new(0, 5), "goodbye"))
237            .unwrap();
238        cs.insert("b.txt", Edit::replace(Span::new(0, 3), "bar"))
239            .unwrap();
240        Plan::new(cs, ws).unwrap()
241    }
242
243    #[test]
244    fn preview_does_not_write() {
245        let ws = workspace();
246        let preview = plan(&ws).preview(&ws).unwrap();
247        assert_eq!(preview.files[0].after, "goodbye world");
248        assert_eq!(
249            ws.vfs().read(Path::new("/ws/a.txt")).unwrap(),
250            "hello world"
251        );
252    }
253
254    #[test]
255    fn apply_then_rollback_round_trips() {
256        let ws = workspace();
257        let receipt = plan(&ws).apply(&ws).unwrap();
258        assert_eq!(
259            ws.vfs().read(Path::new("/ws/a.txt")).unwrap(),
260            "goodbye world"
261        );
262        assert_eq!(ws.vfs().read(Path::new("/ws/b.txt")).unwrap(), "bar");
263        assert_eq!(receipt.rollback(&ws).unwrap(), 2);
264        assert_eq!(
265            ws.vfs().read(Path::new("/ws/a.txt")).unwrap(),
266            "hello world"
267        );
268    }
269
270    #[test]
271    fn moves_apply_after_edits_and_roll_back_in_reverse() {
272        let ws = workspace();
273        let mut cs = ChangeSet::new();
274        cs.insert("a.txt", Edit::replace(Span::new(0, 5), "moved"))
275            .unwrap();
276        cs.move_file("a.txt", "dir/z.txt").unwrap();
277        let plan = Plan::new(cs, &ws).unwrap();
278
279        let preview = plan.preview(&ws).unwrap();
280        assert_eq!(
281            preview.files[0].moved_to.as_deref(),
282            Some(Path::new("dir/z.txt"))
283        );
284        assert_eq!(preview.files[0].after, "moved world");
285
286        let receipt = plan.apply(&ws).unwrap();
287        assert!(!ws.vfs().exists(Path::new("/ws/a.txt")));
288        assert_eq!(
289            ws.vfs().read(Path::new("/ws/dir/z.txt")).unwrap(),
290            "moved world"
291        );
292
293        receipt.rollback(&ws).unwrap();
294        assert!(!ws.vfs().exists(Path::new("/ws/dir/z.txt")));
295        assert_eq!(
296            ws.vfs().read(Path::new("/ws/a.txt")).unwrap(),
297            "hello world"
298        );
299    }
300
301    #[test]
302    fn undo_refuses_files_edited_after_apply() {
303        let ws = workspace();
304        let receipt = plan(&ws).apply(&ws).unwrap();
305        ws.vfs()
306            .write(Path::new("/ws/b.txt"), "edited later")
307            .unwrap();
308        assert!(
309            matches!(receipt.undo(&ws), Err(ApplyError::Modified { path }) if path == Path::new("b.txt"))
310        );
311        assert_eq!(
312            ws.vfs().read(Path::new("/ws/a.txt")).unwrap(),
313            "goodbye world",
314            "nothing touched"
315        );
316    }
317
318    #[test]
319    fn stale_file_is_refused() {
320        let ws = workspace();
321        let plan = plan(&ws);
322        ws.vfs().write(Path::new("/ws/b.txt"), "changed").unwrap();
323        assert!(
324            matches!(plan.apply(&ws), Err(ApplyError::Stale { path }) if path == Path::new("b.txt"))
325        );
326        assert_eq!(
327            ws.vfs().read(Path::new("/ws/a.txt")).unwrap(),
328            "hello world"
329        );
330    }
331
332    /// Two applies chained: the second edits a file the first moved. Rolling
333    /// the chained receipt back restores the tree exactly.
334    #[test]
335    fn chained_receipts_roll_back_both_steps() {
336        let ws = workspace();
337        let mut first = ChangeSet::new();
338        first.move_file("a.txt", "moved.txt").unwrap();
339        first
340            .insert("b.txt", Edit::replace(Span::new(0, 3), "bar"))
341            .unwrap();
342        let r1 = Plan::new(first, &ws).unwrap().apply(&ws).unwrap();
343        let mut second = ChangeSet::new();
344        second
345            .insert("moved.txt", Edit::replace(Span::new(0, 5), "goodbye"))
346            .unwrap();
347        second
348            .insert("b.txt", Edit::replace(Span::new(0, 3), "baz"))
349            .unwrap();
350        let r2 = Plan::new(second, &ws).unwrap().apply(&ws).unwrap();
351        let read = |p: &str| ws.vfs().read(Path::new(p)).unwrap();
352        assert_eq!(read("/ws/moved.txt"), "goodbye world");
353        assert_eq!(read("/ws/b.txt"), "baz");
354
355        let chained = r1.then(r2);
356        assert_eq!(
357            chained.paths().count(),
358            2,
359            "originals keyed by pre-batch paths"
360        );
361        chained.undo(&ws).unwrap();
362        assert_eq!(read("/ws/a.txt"), "hello world");
363        assert_eq!(read("/ws/b.txt"), "foo");
364        assert!(!ws.vfs().exists(Path::new("/ws/moved.txt")));
365    }
366}