1use crate::History;
7use crate::protocol::display::{Line, Role};
8use crate::protocol::vocabulary::{IntentLine, Mark, Plural};
9use crate::report::{Block, Document};
10
11use std::path::{Path, PathBuf};
12use std::time::{SystemTime, UNIX_EPOCH};
13
14use serde::{Deserialize, Serialize};
15
16use crate::{
17 EngineError, History as HistoryResult, HistoryEntry, Intent, Mutation, Planned, Receipt, Undo,
18 VfsError,
19};
20
21const FILE: &str = ".vvv/history.json";
22const LIMIT: usize = 20;
24
25#[derive(Debug, thiserror::Error)]
26pub enum HistoryError {
27 #[error(transparent)]
28 Vfs(#[from] VfsError),
29 #[error(
30 "{FILE} is not readable as history ({0}); if it was written by an older vvv, delete it"
31 )]
32 Corrupt(String),
33 #[error("nothing to undo")]
34 Empty,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub(crate) struct Record {
41 pub id: u64,
42 pub at: u64,
44 pub intent: Intent,
45 pub receipt: Receipt,
46}
47
48impl Record {
49 pub fn entry(&self) -> HistoryEntry {
50 HistoryEntry {
51 id: self.id,
52 at: self.at,
53 intent: self.intent.clone(),
54 files: self.receipt.paths().count(),
55 paths: self.receipt.paths().map(Into::into).collect(),
56 moves: self
57 .receipt
58 .moves()
59 .iter()
60 .map(|(f, t)| (f.into(), t.into()))
61 .collect(),
62 }
63 }
64}
65
66pub struct Ledger<'a> {
67 engine: &'a crate::Engine,
68}
69
70impl<'a> Ledger<'a> {
71 pub fn new(engine: &'a crate::Engine) -> Self {
72 Self { engine }
73 }
74
75 pub fn path() -> &'static Path {
76 Path::new(FILE)
77 }
78
79 fn file(&self) -> PathBuf {
80 self.engine.workspace().absolute(Self::path())
81 }
82
83 fn snapshot(&self) -> Result<HistorySnapshot, HistoryError> {
84 let original = match self.engine.workspace().vfs().read(&self.file()) {
85 Ok(text) => Some(text),
86 Err(VfsError::NotFound(_)) => None,
87 Err(error) => return Err(error.into()),
88 };
89 let entries = original
90 .as_deref()
91 .map(serde_json::from_str)
92 .transpose()
93 .map_err(|e| HistoryError::Corrupt(e.to_string()))?
94 .unwrap_or_default();
95 Ok(HistorySnapshot { original, entries })
96 }
97
98 fn entries(&self) -> Result<Vec<Record>, HistoryError> {
99 Ok(self.snapshot()?.entries)
100 }
101}
102
103struct HistorySnapshot {
105 original: Option<String>,
106 entries: Vec<Record>,
107}
108
109impl HistorySnapshot {
110 fn save(&self, transaction: &mut crate::plan::Transaction<'_>) -> Result<(), HistoryError> {
111 let text = serde_json::to_string(&self.entries)
112 .map_err(|error| HistoryError::Corrupt(error.to_string()))?;
113 Ok(transaction.save_file(&Ledger::path().into(), self.original.as_deref(), &text)?)
114 }
115
116 fn push(
117 &mut self,
118 id: u64,
119 intent: Intent,
120 receipt: Receipt,
121 transaction: &mut crate::plan::Transaction<'_>,
122 ) -> Result<Record, HistoryError> {
123 let entry = Record {
124 id,
125 at: SystemTime::now()
126 .duration_since(UNIX_EPOCH)
127 .map_or(0, |d| d.as_secs()),
128 intent,
129 receipt,
130 };
131 self.entries.push(entry.clone());
132 if self.entries.len() > LIMIT {
133 self.entries.drain(..self.entries.len() - LIMIT);
134 }
135 self.save(transaction)?;
136 Ok(entry)
137 }
138
139 fn last(&self) -> Result<&Record, HistoryError> {
140 self.entries.last().ok_or(HistoryError::Empty)
141 }
142
143 fn pop(&mut self, transaction: &mut crate::plan::Transaction<'_>) -> Result<(), HistoryError> {
144 self.entries.pop().ok_or(HistoryError::Empty)?;
145 self.save(transaction)
146 }
147
148 fn next_id(&self) -> Result<u64, HistoryError> {
149 self.entries.last().map_or(Ok(1), |entry| {
150 entry
151 .id
152 .checked_add(1)
153 .ok_or_else(|| HistoryError::Corrupt("history entry id is exhausted".to_owned()))
154 })
155 }
156}
157
158pub struct Apply<T: Mutation>(pub Planned<T>);
169
170impl<T: Mutation> Apply<T> {
171 pub fn apply(self, engine: &crate::Engine) -> Result<Applied<T>, EngineError> {
173 let _operation = engine.operation();
174 self.apply_in(engine)
175 }
176
177 pub(crate) fn apply_in(self, engine: &crate::Engine) -> Result<Applied<T>, EngineError> {
178 let workspace = engine.workspace();
179 let history = Ledger::new(engine);
180 let mut snapshot = history.snapshot()?;
181 let id = snapshot.next_id()?;
182 engine.touched();
184 let (intent, result, plans) = self.0.into_parts();
185 let mut transaction = crate::plan::Transaction::new(workspace);
186 for plan in plans {
187 if let Err(error) = transaction.apply(plan) {
188 return Err(transaction.recover(error.into()));
189 }
190 }
191 let receipt = transaction.receipt();
192 let record = match snapshot.push(id, intent, receipt, &mut transaction) {
193 Ok(record) => record,
194 Err(error) => return Err(transaction.recover(error.into())),
195 };
196 Ok(Applied::new(result, record.id))
197 }
198}
199
200#[derive(Debug, Clone)]
210pub struct Applied<T: Mutation> {
211 result: T,
212 history_id: u64,
213}
214
215impl<T: Mutation> Applied<T> {
216 fn new(mut result: T, history_id: u64) -> Self {
217 result.applied(history_id);
218 Self { result, history_id }
219 }
220
221 pub fn history_id(&self) -> u64 {
223 self.history_id
224 }
225
226 pub fn into_mutation(self) -> Applied<crate::MutationAnswer> {
228 Applied {
229 result: self.result.into_mutation(),
230 history_id: self.history_id,
231 }
232 }
233
234 pub fn into_inner(self) -> T {
236 self.result
237 }
238}
239
240impl<T: Mutation> std::ops::Deref for Applied<T> {
241 type Target = T;
242
243 fn deref(&self) -> &T {
244 &self.result
245 }
246}
247
248impl<T: Mutation + Serialize> Serialize for Applied<T> {
249 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
250 self.result.serialize(serializer)
251 }
252}
253
254impl Ledger<'_> {
255 pub fn undo(&self) -> Result<Undo, EngineError> {
257 let _operation = self.engine.operation();
258 self.undo_in()
259 }
260
261 pub(crate) fn undo_in(&self) -> Result<Undo, EngineError> {
262 let history = self;
263 let mut snapshot = history.snapshot()?;
264 let record = snapshot.last()?.clone();
265 self.engine.touched();
266 let mut transaction = crate::plan::Transaction::new(self.engine.workspace());
267 if let Err(error) = record.receipt.undo_in(&mut transaction) {
268 return Err(transaction.recover(error.into()));
269 }
270 if let Err(error) = snapshot.pop(&mut transaction) {
271 return Err(transaction.recover(error.into()));
272 }
273 Ok(Undo {
274 undone: record.entry(),
275 restored: record.receipt.paths().map(Into::into).collect(),
276 moves_reverted: record
277 .receipt
278 .moves()
279 .iter()
280 .map(|(f, t)| (f.into(), t.into()))
281 .collect(),
282 })
283 }
284 pub fn history(&self) -> Result<HistoryResult, EngineError> {
286 let _operation = self.engine.operation();
287 self.history_in()
288 }
289
290 pub(crate) fn history_in(&self) -> Result<HistoryResult, EngineError> {
291 let records = self.entries()?;
292 Ok(HistoryResult {
293 entries: records.iter().map(Record::entry).collect(),
294 })
295 }
296}
297
298impl Document {
299 pub(crate) fn undo(result: &Undo) -> Self {
300 let mut report = Self::new();
301 report.title(format!(
302 "{} #{} {}",
303 Mark::Undo.glyph(),
304 result.undone.id,
305 IntentLine(&result.undone.intent)
306 ));
307 report.block_body(Block::Undo {
308 moves: result.moves_reverted.clone(),
309 restored: result.restored.clone(),
310 });
311 report.block_note(Block::Summary(
312 Line::mark(Mark::Undo)
313 .and(Role::Plain, " ")
314 .and(Role::Plain, format!("#{} ", result.undone.id))
315 .and(Role::Dim, Plural(result.restored.len(), "file").to_string()),
316 ));
317 report
318 }
319
320 pub(crate) fn history(result: &History) -> Self {
321 let mut report = Self::new();
322 if result.entries.is_empty() {
323 report.block_note(Block::Summary(
324 Line::mark(Mark::Nothing).and(Role::Plain, " no history"),
325 ));
326 return report;
327 }
328 let last = result.entries.len() - 1;
329 report.block_body(Block::History(result.entries.clone()));
330 report.block_note(Block::Summary(
331 Line::single(
332 Role::Plain,
333 Plural(result.entries.len(), "entry").to_string(),
334 )
335 .and(Role::Plain, " ")
336 .and_line(Line::mark(Mark::Undo))
337 .and(Role::Plain, format!(" #{}", result.entries[last].id)),
338 ));
339 report
340 }
341}
342
343#[cfg(test)]
344mod tests {
345 use super::*;
346
347 #[test]
348 fn history_ids_never_wrap() {
349 let snapshot = HistorySnapshot {
350 original: None,
351 entries: vec![Record {
352 id: u64::MAX,
353 at: 0,
354 intent: Intent::Rewrite(crate::RewriteIntent::new(crate::Query::pattern("a"), "b")),
355 receipt: Receipt::default(),
356 }],
357 };
358 assert!(matches!(snapshot.next_id(), Err(HistoryError::Corrupt(_))));
359 }
360}