1use vvv_core::RelPath;
5
6use serde::{Deserialize, Serialize};
7use vvv_core::Edit;
8
9use super::diff::Diff;
10use super::{Intent, Notice};
11use crate::batch::Batch;
12use crate::capabilities::moves::{Move, MoveSymbol};
13use crate::capabilities::rename::Rename;
14use crate::rewrite::Rewrite;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(try_from = "MutationStateFields", into = "MutationStateFields")]
20pub enum MutationState {
21 Preview,
22 Applied { history_id: u64 },
23}
24
25#[cfg(feature = "schema")]
26impl schemars::JsonSchema for MutationState {
27 fn schema_name() -> std::borrow::Cow<'static, str> {
28 "MutationState".into()
29 }
30
31 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
32 let preview_history = if generator.contract().is_deserialize() {
33 serde_json::json!({"type": "null"})
34 } else {
35 serde_json::json!(false)
36 };
37 schemars::json_schema!({
38 "type": "object",
39 "oneOf": [
40 {
41 "properties": {
42 "applied": {"const": false},
43 "history_id": preview_history
44 },
45 "required": ["applied"]
46 },
47 {
48 "properties": {
49 "applied": {"const": true},
50 "history_id": generator.subschema_for::<u64>()
51 },
52 "required": ["applied", "history_id"]
53 }
54 ]
55 })
56 }
57}
58
59impl MutationState {
60 pub fn is_applied(self) -> bool {
61 matches!(self, Self::Applied { .. })
62 }
63
64 pub fn history_id(self) -> Option<u64> {
65 match self {
66 Self::Preview => None,
67 Self::Applied { history_id } => Some(history_id),
68 }
69 }
70}
71
72#[derive(Serialize, Deserialize)]
73#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
74struct MutationStateFields {
75 applied: bool,
76 #[serde(default, skip_serializing_if = "Option::is_none")]
77 history_id: Option<u64>,
78}
79
80impl From<MutationState> for MutationStateFields {
81 fn from(state: MutationState) -> Self {
82 Self {
83 applied: state.is_applied(),
84 history_id: state.history_id(),
85 }
86 }
87}
88
89impl TryFrom<MutationStateFields> for MutationState {
90 type Error = MutationStateError;
91
92 fn try_from(fields: MutationStateFields) -> Result<Self, Self::Error> {
93 match (fields.applied, fields.history_id) {
94 (false, None) => Ok(Self::Preview),
95 (true, Some(history_id)) => Ok(Self::Applied { history_id }),
96 (false, Some(_)) => Err(MutationStateError::PreviewWithHistory),
97 (true, None) => Err(MutationStateError::AppliedWithoutHistory),
98 }
99 }
100}
101
102#[derive(Debug, thiserror::Error)]
103enum MutationStateError {
104 #[error("a preview cannot have a history_id")]
105 PreviewWithHistory,
106 #[error("an applied mutation requires a history_id")]
107 AppliedWithoutHistory,
108}
109
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
112#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
113pub struct HistoryEntry {
114 pub id: u64,
115 pub at: u64,
117 pub intent: Intent,
119 pub files: usize,
121 #[serde(default, skip_serializing_if = "Vec::is_empty")]
123 pub paths: Vec<RelPath>,
124 #[serde(default, skip_serializing_if = "Vec::is_empty")]
126 pub moves: Vec<(RelPath, RelPath)>,
127}
128
129#[derive(Debug, Clone, Serialize, Deserialize)]
131#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
132pub struct History {
133 pub entries: Vec<HistoryEntry>,
135}
136
137#[derive(Debug, Clone, Serialize, Deserialize)]
139#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
140pub struct Undo {
141 pub undone: HistoryEntry,
142 pub restored: Vec<RelPath>,
144 #[serde(default, skip_serializing_if = "Vec::is_empty")]
146 pub moves_reverted: Vec<(RelPath, RelPath)>,
147}
148
149#[derive(Debug, Clone, Serialize, Deserialize)]
151#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
152pub struct FileChange {
153 pub path: RelPath,
155 #[serde(default, skip_serializing_if = "Option::is_none")]
157 pub moved_to: Option<RelPath>,
158 pub edits: Vec<Edit>,
159 pub diff: Diff,
160}
161
162pub trait Mutation: sealed::Sealed {
174 fn into_mutation(self) -> MutationAnswer;
176 fn applied(&mut self, id: u64);
178}
179
180#[derive(Debug, Clone, Serialize)]
182#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
183#[serde(untagged)]
184#[allow(clippy::large_enum_variant)]
185pub enum MutationAnswer {
186 Rewrite(Rewrite),
187 Rename(Rename),
188 Move(Move),
189 MoveSymbol(MoveSymbol),
190 Batch(Batch),
191}
192
193impl MutationAnswer {
194 pub fn notices(&self) -> &[Notice] {
196 match self {
197 Self::Rewrite(_) | Self::Rename(_) => &[],
198 Self::Move(result) => &result.notices,
199 Self::MoveSymbol(result) => &result.notices,
200 Self::Batch(result) => &result.notices,
201 }
202 }
203
204 pub fn history_id(&self) -> Option<u64> {
206 match self {
207 Self::Rewrite(result) => result.state.history_id(),
208 Self::Rename(result) => result.state.history_id(),
209 Self::Move(result) => result.state.history_id(),
210 Self::MoveSymbol(result) => result.state.history_id(),
211 Self::Batch(result) => result.state.history_id(),
212 }
213 }
214}
215
216impl Mutation for MutationAnswer {
217 fn into_mutation(self) -> Self {
218 self
219 }
220
221 fn applied(&mut self, id: u64) {
222 match self {
223 Self::Rewrite(result) => result.applied(id),
224 Self::Rename(result) => result.applied(id),
225 Self::Move(result) => result.applied(id),
226 Self::MoveSymbol(result) => result.applied(id),
227 Self::Batch(result) => result.applied(id),
228 }
229 }
230}
231
232impl TryFrom<super::Answer> for MutationAnswer {
233 type Error = super::Answer;
234
235 fn try_from(answer: super::Answer) -> Result<Self, Self::Error> {
236 match answer {
237 super::Answer::Rewrite(result) => Ok(Self::Rewrite(result)),
238 super::Answer::Rename(result) => Ok(Self::Rename(result)),
239 super::Answer::Move(result) => Ok(Self::Move(result)),
240 super::Answer::MoveSymbol(result) => Ok(Self::MoveSymbol(result)),
241 super::Answer::Batch(result) => Ok(Self::Batch(result)),
242 query => Err(query),
243 }
244 }
245}
246
247mod sealed {
249 pub trait Sealed {}
250 impl Sealed for super::Rewrite {}
251 impl Sealed for super::Rename {}
252 impl Sealed for super::Move {}
253 impl Sealed for super::MoveSymbol {}
254 impl Sealed for super::Batch {}
255 impl Sealed for super::MutationAnswer {}
256}
257
258#[cfg(test)]
259mod tests {
260 use super::*;
261 use serde_json::json;
262
263 #[test]
264 fn mutation_states_round_trip_with_history_only_when_applied() {
265 for (state, wire) in [
266 (MutationState::Preview, json!({"applied": false})),
267 (
268 MutationState::Applied { history_id: 7 },
269 json!({"applied": true, "history_id": 7}),
270 ),
271 ] {
272 assert_eq!(serde_json::to_value(state).unwrap(), wire);
273 assert_eq!(
274 serde_json::from_value::<MutationState>(wire).unwrap(),
275 state
276 );
277 }
278 }
279
280 #[test]
281 fn previews_accept_an_omitted_or_null_history_id() {
282 for wire in [
283 json!({"applied": false}),
284 json!({"applied": false, "history_id": null}),
285 ] {
286 assert_eq!(
287 serde_json::from_value::<MutationState>(wire).unwrap(),
288 MutationState::Preview
289 );
290 }
291 }
292
293 #[test]
294 fn contradictory_mutation_states_are_rejected() {
295 for (wire, message) in [
296 (
297 json!({"applied": false, "history_id": 7}),
298 "a preview cannot have a history_id",
299 ),
300 (
301 json!({"applied": true}),
302 "an applied mutation requires a history_id",
303 ),
304 (
305 json!({"applied": true, "history_id": null}),
306 "an applied mutation requires a history_id",
307 ),
308 ] {
309 let error = serde_json::from_value::<MutationState>(wire).unwrap_err();
310 assert!(error.to_string().contains(message), "{error}");
311 }
312 }
313}