1use std::path::{Path, PathBuf};
7use std::time::{SystemTime, UNIX_EPOCH};
8
9use serde::{Deserialize, Serialize};
10
11use crate::command::{Command, Context};
12use crate::{
13 EngineError, History as HistoryResult, HistoryEntry, HistoryQuery, Intent, Mutation, Planned,
14 Receipt, Undo, UndoLast, VfsError, Workspace,
15};
16
17const FILE: &str = ".vvv/history.json";
18const LIMIT: usize = 20;
20
21#[derive(Debug, thiserror::Error)]
22pub enum HistoryError {
23 #[error(transparent)]
24 Vfs(#[from] VfsError),
25 #[error(
26 "{FILE} is not readable as history ({0}); if it was written by an older vvv, delete it"
27 )]
28 Corrupt(String),
29 #[error("nothing to undo")]
30 Empty,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36pub(crate) struct Record {
37 pub id: u64,
38 pub at: u64,
40 pub intent: Intent,
41 pub receipt: Receipt,
42}
43
44impl Record {
45 pub fn entry(&self) -> HistoryEntry {
46 HistoryEntry {
47 id: self.id,
48 at: self.at,
49 intent: self.intent.clone(),
50 files: self.receipt.paths().count(),
51 paths: self.receipt.paths().map(Into::into).collect(),
52 moves: self
53 .receipt
54 .moves()
55 .iter()
56 .map(|(f, t)| (f.into(), t.into()))
57 .collect(),
58 }
59 }
60}
61
62pub(crate) struct History<'a> {
63 workspace: &'a Workspace,
64}
65
66impl<'a> History<'a> {
67 pub fn new(workspace: &'a Workspace) -> Self {
68 Self { workspace }
69 }
70
71 pub fn path() -> &'static Path {
72 Path::new(FILE)
73 }
74
75 fn file(&self) -> PathBuf {
76 self.workspace.absolute(Self::path())
77 }
78
79 pub fn entries(&self) -> Result<Vec<Record>, HistoryError> {
80 let vfs = self.workspace.vfs();
81 let file = self.file();
82 if !vfs.exists(&file) {
83 return Ok(Vec::new());
84 }
85 serde_json::from_str(&vfs.read(&file)?).map_err(|e| HistoryError::Corrupt(e.to_string()))
86 }
87
88 fn save(&self, entries: &[Record]) -> Result<(), HistoryError> {
89 let text =
90 serde_json::to_string(entries).map_err(|e| HistoryError::Corrupt(e.to_string()))?;
91 Ok(self.workspace.vfs().write(&self.file(), &text)?)
92 }
93
94 pub fn push(&self, intent: Intent, receipt: Receipt) -> Result<Record, HistoryError> {
95 let mut entries = self.entries()?;
96 let entry = Record {
97 id: entries.last().map_or(1, |e| e.id + 1),
98 at: SystemTime::now()
99 .duration_since(UNIX_EPOCH)
100 .map_or(0, |d| d.as_secs()),
101 intent,
102 receipt,
103 };
104 entries.push(entry.clone());
105 if entries.len() > LIMIT {
106 entries.drain(..entries.len() - LIMIT);
107 }
108 self.save(&entries)?;
109 Ok(entry)
110 }
111
112 pub fn last(&self) -> Result<Record, HistoryError> {
114 self.entries()?.pop().ok_or(HistoryError::Empty)
115 }
116
117 pub fn pop(&self) -> Result<(), HistoryError> {
119 let mut entries = self.entries()?;
120 entries.pop().ok_or(HistoryError::Empty)?;
121 self.save(&entries)
122 }
123}
124
125pub struct Apply<T>(pub Planned<T>);
130
131impl<T: Mutation> Command for Apply<T> {
132 type Output = T;
133
134 fn run(self, cx: &mut Context<'_>) -> Result<Self::Output, EngineError> {
135 let workspace = cx.workspace;
136 cx.graph.touched();
138 let (mut result, plans) = self.0.into_parts();
139 let mut receipt: Option<Receipt> = None;
140 for plan in plans {
141 match plan.apply(workspace) {
142 Ok(applied) => {
143 receipt = Some(match receipt.take() {
144 Some(so_far) => so_far.then(applied),
145 None => applied,
146 });
147 }
148 Err(error) => {
149 if let Some(so_far) = receipt {
150 let _ = so_far.rollback(workspace);
151 }
152 return Err(error.into());
153 }
154 }
155 }
156 let record =
157 History::new(cx.workspace).push(result.intent(), receipt.unwrap_or_default())?;
158 result.applied(record.id);
159 Ok(result)
160 }
161}
162
163impl Command for UndoLast {
165 type Output = Undo;
166
167 fn run(self, cx: &mut Context<'_>) -> Result<Self::Output, EngineError> {
168 let history = History::new(cx.workspace);
169 let record = history.last()?;
170 cx.graph.touched();
171 record.receipt.undo(cx.workspace)?;
172 history.pop()?;
173 Ok(Undo {
174 undone: record.entry(),
175 restored: record.receipt.paths().map(Into::into).collect(),
176 moves_reverted: record
177 .receipt
178 .moves()
179 .iter()
180 .map(|(f, t)| (f.into(), t.into()))
181 .collect(),
182 })
183 }
184}
185
186impl Command for HistoryQuery {
188 type Output = HistoryResult;
189
190 fn run(self, cx: &mut Context<'_>) -> Result<Self::Output, EngineError> {
191 let records = History::new(cx.workspace).entries()?;
192 Ok(HistoryResult {
193 entries: records.iter().map(Record::entry).collect(),
194 })
195 }
196}