1use std::collections::BTreeMap;
10#[cfg(test)]
11use std::path::Path;
12use std::path::PathBuf;
13
14mod fingerprint;
15mod planned;
16mod receipt;
17mod transaction;
18
19pub use fingerprint::Fingerprint;
20pub use planned::Planned;
21pub use receipt::Receipt;
22pub(crate) use transaction::Transaction;
23
24use crate::protocol::Diff;
25use crate::{FileChange, VfsError, Workspace};
26use vvv_core::{ChangeSet, Edit, RelPath};
27
28#[derive(Debug, thiserror::Error)]
29pub enum ApplyError {
30 #[error(transparent)]
31 Edit(#[from] vvv_core::EditConflict),
32 #[error(transparent)]
33 Vfs(#[from] VfsError),
34 #[error("{} changed since the plan was made", path.display())]
35 Stale { path: RelPath },
36 #[error("{} already exists", path.display())]
37 DestinationExists { path: RelPath },
38 #[error("{} changed since it was written; refusing to undo", path.display())]
39 Modified { path: RelPath },
40 #[error("writing {} failed: {source}", path.display())]
41 Write {
42 path: RelPath,
43 #[source]
44 source: VfsError,
45 },
46}
47
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct Plan {
50 change_set: ChangeSet,
51 fingerprints: BTreeMap<PathBuf, Fingerprint>,
52}
53
54impl Plan {
55 pub(crate) fn new(change: crate::change::WitnessedChangeSet) -> Self {
57 let (change_set, fingerprints) = change.into_parts();
58 Self {
59 change_set,
60 fingerprints,
61 }
62 }
63
64 pub fn is_empty(&self) -> bool {
65 self.change_set.is_empty()
66 }
67
68 pub fn preview(&self, workspace: &Workspace) -> Result<Preview, ApplyError> {
69 Ok(Preview {
70 files: self.stage(workspace)?,
71 })
72 }
73
74 pub(crate) fn file_changes(&self, preview: &Preview) -> Vec<FileChange> {
76 preview
77 .files
78 .iter()
79 .map(|file| file.file_change(self.change_set.edits_for(&file.path).to_vec()))
80 .collect()
81 }
82
83 pub fn apply(self, workspace: &Workspace) -> Result<Receipt, crate::EngineError> {
84 let mut transaction = Transaction::new(workspace);
85 match transaction.apply(self) {
86 Ok(()) => Ok(transaction.receipt()),
87 Err(error) => Err(transaction.recover(error.into())),
88 }
89 }
90
91 fn stage(&self, workspace: &Workspace) -> Result<Vec<FilePreview>, ApplyError> {
93 for (from, to) in self.change_set.moves() {
96 if workspace
97 .vfs()
98 .entry_kind(&workspace.absolute(to))?
99 .is_some()
100 && !workspace
101 .vfs()
102 .same_entry(&workspace.absolute(from), &workspace.absolute(to))?
103 {
104 return Err(ApplyError::DestinationExists { path: to.into() });
105 }
106 }
107 self.fingerprints
108 .iter()
109 .map(|(path, expected)| {
110 let before = workspace.vfs().read(&workspace.absolute(path))?;
111 if &Fingerprint::of(&before) != expected {
112 return Err(ApplyError::Stale {
113 path: path.clone().into(),
114 });
115 }
116 let after = self.change_set.apply_to(path, &before)?;
117 Ok(FilePreview {
118 path: path.clone().into(),
119 moved_to: self.change_set.destination(path).map(Into::into),
120 before,
121 after,
122 })
123 })
124 .collect()
125 }
126}
127
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct Preview {
130 pub files: Vec<FilePreview>,
131}
132
133impl Preview {
134 pub(crate) fn file_changes(&self) -> Vec<FileChange> {
137 self.files
138 .iter()
139 .map(|file| file.file_change(Vec::new()))
140 .collect()
141 }
142}
143
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct FilePreview {
146 pub path: RelPath,
148 pub moved_to: Option<RelPath>,
150 pub before: String,
151 pub after: String,
152}
153
154impl FilePreview {
155 fn file_change(&self, edits: Vec<Edit>) -> FileChange {
156 FileChange {
157 path: self.path.clone(),
158 moved_to: self.moved_to.clone(),
159 edits,
160 diff: Diff::between(
161 &self.path,
162 self.moved_to.as_deref().unwrap_or(&self.path),
163 &self.before,
164 &self.after,
165 ),
166 }
167 }
168}
169
170#[cfg(test)]
171mod tests {
172 use std::sync::Arc;
173
174 use super::*;
175 use crate::MemoryVfs;
176 use vvv_core::{Edit, Span};
177
178 struct Fixture {
179 workspace: Workspace,
180 }
181
182 impl Fixture {
183 fn new() -> Self {
184 let vfs = MemoryVfs::new()
185 .with_file("/ws/a.txt", "hello world")
186 .with_file("/ws/b.txt", "foo");
187 Self {
188 workspace: Workspace::new("/ws", Arc::new(vfs)),
189 }
190 }
191
192 fn plan(&self, cs: ChangeSet) -> Plan {
193 let mut change = crate::change::Change::new();
194 for path in cs.paths() {
195 let file = self.workspace.load(path).unwrap();
196 change
197 .edits(file.witness(), cs.edits_for(path).iter().cloned())
198 .unwrap();
199 if let Some(to) = cs.destination(path) {
200 change.move_file(file.witness(), to).unwrap();
201 }
202 }
203 Plan::new(change.bind().unwrap().change_set)
204 }
205
206 fn replacement(&self) -> Plan {
207 let mut cs = ChangeSet::new();
208 cs.insert("a.txt", Edit::replace(Span::new(0, 5), "goodbye"))
209 .unwrap();
210 cs.insert("b.txt", Edit::replace(Span::new(0, 3), "bar"))
211 .unwrap();
212 self.plan(cs)
213 }
214 }
215
216 #[test]
217 fn preview_does_not_write() {
218 let fixture = Fixture::new();
219 let ws = &fixture.workspace;
220 let preview = fixture.replacement().preview(ws).unwrap();
221 assert_eq!(preview.files[0].after, "goodbye world");
222 assert_eq!(
223 ws.vfs().read(Path::new("/ws/a.txt")).unwrap(),
224 "hello world"
225 );
226 }
227
228 #[test]
229 fn preview_refuses_a_newly_occupied_destination() {
230 let fixture = Fixture::new();
231 let ws = &fixture.workspace;
232 let mut cs = ChangeSet::new();
233 cs.move_file("a.txt", "new.txt").unwrap();
234 let plan = fixture.plan(cs);
235 ws.vfs()
236 .write(Path::new("/ws/new.txt"), "precious new file")
237 .unwrap();
238 assert!(
239 matches!(plan.preview(ws), Err(ApplyError::DestinationExists { path }) if path == Path::new("new.txt"))
240 );
241 assert_eq!(
242 ws.vfs().read(Path::new("/ws/a.txt")).unwrap(),
243 "hello world"
244 );
245 assert_eq!(
246 ws.vfs().read(Path::new("/ws/new.txt")).unwrap(),
247 "precious new file"
248 );
249 }
250
251 #[test]
252 fn apply_then_rollback_round_trips() {
253 let fixture = Fixture::new();
254 let ws = &fixture.workspace;
255 let receipt = fixture.replacement().apply(ws).unwrap();
256 assert_eq!(
257 ws.vfs().read(Path::new("/ws/a.txt")).unwrap(),
258 "goodbye world"
259 );
260 assert_eq!(ws.vfs().read(Path::new("/ws/b.txt")).unwrap(), "bar");
261 assert_eq!(receipt.rollback(ws).unwrap(), 2);
262 assert_eq!(
263 ws.vfs().read(Path::new("/ws/a.txt")).unwrap(),
264 "hello world"
265 );
266 }
267
268 #[test]
269 fn moves_apply_after_edits_and_roll_back_in_reverse() {
270 let fixture = Fixture::new();
271 let ws = &fixture.workspace;
272 let mut cs = ChangeSet::new();
273 cs.insert("a.txt", Edit::replace(Span::new(0, 5), "moved"))
274 .unwrap();
275 cs.move_file("a.txt", "dir/z.txt").unwrap();
276 let plan = fixture.plan(cs);
277
278 let preview = plan.preview(ws).unwrap();
279 assert_eq!(
280 preview.files[0].moved_to.as_deref(),
281 Some(Path::new("dir/z.txt"))
282 );
283 assert_eq!(preview.files[0].after, "moved world");
284
285 let receipt = plan.apply(ws).unwrap();
286 assert!(!ws.vfs().exists(Path::new("/ws/a.txt")));
287 assert_eq!(
288 ws.vfs().read(Path::new("/ws/dir/z.txt")).unwrap(),
289 "moved world"
290 );
291
292 receipt.rollback(ws).unwrap();
293 assert!(!ws.vfs().exists(Path::new("/ws/dir/z.txt")));
294 assert_eq!(
295 ws.vfs().read(Path::new("/ws/a.txt")).unwrap(),
296 "hello world"
297 );
298 }
299
300 #[test]
301 fn undo_refuses_files_edited_after_apply() {
302 let fixture = Fixture::new();
303 let ws = &fixture.workspace;
304 let receipt = fixture.replacement().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(crate::EngineError::Apply(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 fixture = Fixture::new();
321 let ws = &fixture.workspace;
322 let plan = fixture.replacement();
323 ws.vfs().write(Path::new("/ws/b.txt"), "changed").unwrap();
324 assert!(
325 matches!(plan.apply(ws), Err(crate::EngineError::Apply(ApplyError::Stale { path })) if path == Path::new("b.txt"))
326 );
327 assert_eq!(
328 ws.vfs().read(Path::new("/ws/a.txt")).unwrap(),
329 "hello world"
330 );
331 }
332
333 #[test]
336 fn chained_receipts_roll_back_both_steps() {
337 let fixture = Fixture::new();
338 let ws = &fixture.workspace;
339 let mut first = ChangeSet::new();
340 first.move_file("a.txt", "moved.txt").unwrap();
341 first
342 .insert("b.txt", Edit::replace(Span::new(0, 3), "bar"))
343 .unwrap();
344 let r1 = fixture.plan(first).apply(ws).unwrap();
345 let mut second = ChangeSet::new();
346 second
347 .insert("moved.txt", Edit::replace(Span::new(0, 5), "goodbye"))
348 .unwrap();
349 second
350 .insert("b.txt", Edit::replace(Span::new(0, 3), "baz"))
351 .unwrap();
352 let r2 = fixture.plan(second).apply(ws).unwrap();
353 let read = |p: &str| ws.vfs().read(Path::new(p)).unwrap();
354 assert_eq!(read("/ws/moved.txt"), "goodbye world");
355 assert_eq!(read("/ws/b.txt"), "baz");
356
357 let chained = r1.then(r2);
358 assert_eq!(
359 chained.paths().count(),
360 2,
361 "originals keyed by pre-batch paths"
362 );
363 chained.undo(ws).unwrap();
364 assert_eq!(read("/ws/a.txt"), "hello world");
365 assert_eq!(read("/ws/b.txt"), "foo");
366 assert!(!ws.vfs().exists(Path::new("/ws/moved.txt")));
367 }
368}