Skip to main content

vvv_core/edit/
change_set.rs

1use std::collections::BTreeMap;
2use std::path::{Path, PathBuf};
3
4use serde::{Deserialize, Serialize};
5
6use super::Edit;
7use crate::paths::RelPath;
8use crate::text::{Span, SpanError};
9
10#[derive(Debug, thiserror::Error, PartialEq, Eq)]
11pub enum EditConflict {
12    #[error("{}: {source}", path.display())]
13    InvalidSpan { path: RelPath, source: SpanError },
14    #[error("{}: serialized edits are not in span order", path.display())]
15    Unordered { path: RelPath },
16    #[error("{}: moved file is missing from the touched files", path.display())]
17    MissingSource { path: RelPath },
18    #[error("{}: edit at {new:?} overlaps existing edit at {existing:?}", path.display())]
19    Overlap {
20        path: RelPath,
21        existing: Span,
22        new: Span,
23    },
24    #[error("{} is already being moved to {}", from.display(), existing.display())]
25    AlreadyMoved { from: RelPath, existing: RelPath },
26}
27
28/// Non-overlapping edits grouped by file, kept sorted by span, plus file moves.
29///
30/// Edits to a moved file are keyed by its *current* path; the move is applied
31/// after the edits, so a planner never has to think about ordering.
32#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
33#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
34#[serde(try_from = "ChangeSetData")]
35pub struct ChangeSet {
36    files: BTreeMap<PathBuf, Vec<Edit>>,
37    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
38    moves: BTreeMap<PathBuf, PathBuf>,
39}
40
41#[derive(Deserialize)]
42#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
43struct ChangeSetData {
44    files: BTreeMap<PathBuf, Vec<Edit>>,
45    #[serde(default)]
46    moves: BTreeMap<PathBuf, PathBuf>,
47}
48
49impl TryFrom<ChangeSetData> for ChangeSet {
50    type Error = EditConflict;
51
52    fn try_from(data: ChangeSetData) -> Result<Self, Self::Error> {
53        let mut change = Self::new();
54        for (from, to) in data.moves {
55            if !data.files.contains_key(&from) {
56                return Err(EditConflict::MissingSource { path: from.into() });
57            }
58            change.move_file(from, to)?;
59        }
60        for (path, edits) in data.files {
61            if edits.windows(2).any(|pair| pair[0].span > pair[1].span) {
62                return Err(EditConflict::Unordered { path: path.into() });
63            }
64            change.files.entry(path.clone()).or_default();
65            for edit in edits {
66                change.insert(&path, edit)?;
67            }
68        }
69        Ok(change)
70    }
71}
72
73impl ChangeSet {
74    pub fn new() -> Self {
75        Self::default()
76    }
77
78    /// Record that `from` ends up at `to`. Registers `from` as a touched file.
79    pub fn move_file(
80        &mut self,
81        from: impl Into<PathBuf>,
82        to: impl Into<PathBuf>,
83    ) -> Result<(), EditConflict> {
84        let from = from.into();
85        if let Some(existing) = self.moves.get(&from) {
86            return Err(EditConflict::AlreadyMoved {
87                from: from.into(),
88                existing: existing.clone().into(),
89            });
90        }
91        self.files.entry(from.clone()).or_default();
92        self.moves.insert(from, to.into());
93        Ok(())
94    }
95
96    /// Where `path` ends up, if it is moved.
97    pub fn destination(&self, path: &Path) -> Option<&Path> {
98        self.moves.get(path).map(PathBuf::as_path)
99    }
100
101    pub fn moves(&self) -> impl Iterator<Item = (&Path, &Path)> {
102        self.moves.iter().map(|(f, t)| (f.as_path(), t.as_path()))
103    }
104
105    /// Add an edit, refusing one that overlaps an edit already recorded for the file.
106    pub fn insert(&mut self, path: impl Into<PathBuf>, edit: Edit) -> Result<(), EditConflict> {
107        let path = path.into();
108        edit.span
109            .validate()
110            .map_err(|source| EditConflict::InvalidSpan {
111                path: path.clone().into(),
112                source,
113            })?;
114        let edits = self.files.entry(path.clone()).or_default();
115        if let Some(existing) = edits.iter().find(|e| e.span.overlaps(&edit.span)) {
116            return Err(EditConflict::Overlap {
117                path: path.into(),
118                existing: existing.span,
119                new: edit.span,
120            });
121        }
122        let at = edits.partition_point(|e| e.span <= edit.span);
123        edits.insert(at, edit);
124        Ok(())
125    }
126
127    pub fn merge(mut self, other: ChangeSet) -> Result<Self, EditConflict> {
128        for (path, edits) in other.files {
129            for edit in edits {
130                self.insert(&path, edit)?;
131            }
132        }
133        for (from, to) in other.moves {
134            self.move_file(from, to)?;
135        }
136        Ok(self)
137    }
138
139    pub fn is_empty(&self) -> bool {
140        self.files.values().all(Vec::is_empty) && self.moves.is_empty()
141    }
142
143    pub fn paths(&self) -> impl Iterator<Item = &Path> {
144        self.files.keys().map(PathBuf::as_path)
145    }
146
147    pub fn edits_for(&self, path: &Path) -> &[Edit] {
148        self.files.get(path).map(Vec::as_slice).unwrap_or_default()
149    }
150
151    /// Produce the new contents of one file without touching any storage.
152    pub fn apply_to(&self, path: &Path, original: &str) -> Result<String, EditConflict> {
153        let mut out = String::with_capacity(original.len());
154        let mut cursor = 0;
155        for edit in self.edits_for(path) {
156            edit.span
157                .validate_in(original)
158                .map_err(|source| EditConflict::InvalidSpan {
159                    path: path.into(),
160                    source,
161                })?;
162            out.push_str(&original[cursor..edit.span.start]);
163            out.push_str(&edit.replacement);
164            cursor = edit.span.end;
165        }
166        out.push_str(&original[cursor..]);
167        Ok(out)
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    #[test]
176    fn source_ranges_reject_reversed_out_of_bounds_and_split_characters() {
177        let p = Path::new("f.rs");
178        let mut cs = ChangeSet::new();
179        assert!(matches!(
180            cs.insert(p, Edit::delete(Span { start: 2, end: 1 })),
181            Err(EditConflict::InvalidSpan {
182                source: SpanError::Reversed { .. },
183                ..
184            })
185        ));
186        for (span, source) in [(Span::new(1, 2), "é"), (Span::new(0, 3), "é")] {
187            let mut cs = ChangeSet::new();
188            cs.insert(p, Edit::delete(span)).unwrap();
189            assert!(matches!(
190                cs.apply_to(p, source),
191                Err(EditConflict::InvalidSpan { .. })
192            ));
193        }
194    }
195
196    #[test]
197    fn serialized_changes_preserve_insertion_order_and_reject_invalid_structure() {
198        let mut cs = ChangeSet::new();
199        cs.insert("f.rs", Edit::insert(0, "a")).unwrap();
200        cs.insert("f.rs", Edit::insert(0, "b")).unwrap();
201        cs.insert("f.rs", Edit::replace(Span::new(0, 1), "c"))
202            .unwrap();
203        cs.move_file("f.rs", "g.rs").unwrap();
204        let encoded = serde_json::to_value(&cs).unwrap();
205        let decoded: ChangeSet = serde_json::from_value(encoded.clone()).unwrap();
206        assert_eq!(decoded, cs);
207        assert_eq!(decoded.apply_to(Path::new("f.rs"), "-").unwrap(), "abc");
208
209        let mut unordered = encoded.clone();
210        unordered["files"]["f.rs"].as_array_mut().unwrap().reverse();
211        assert!(serde_json::from_value::<ChangeSet>(unordered).is_err());
212        let mut overlapping = encoded.clone();
213        overlapping["files"]["f.rs"]
214            .as_array_mut()
215            .unwrap()
216            .push(serde_json::to_value(Edit::delete(Span::new(0, 2))).unwrap());
217        assert!(serde_json::from_value::<ChangeSet>(overlapping).is_err());
218        let mut missing = encoded;
219        missing["files"].as_object_mut().unwrap().clear();
220        assert!(serde_json::from_value::<ChangeSet>(missing).is_err());
221    }
222
223    #[test]
224    fn insertion_precedes_replacement_at_the_same_start_in_either_insertion_order() {
225        for reverse in [false, true] {
226            let mut edits = [Edit::delete(Span::new(0, 2)), Edit::insert(0, "é")];
227            if reverse {
228                edits.reverse();
229            }
230            let mut cs = ChangeSet::new();
231            for edit in edits {
232                cs.insert("f.rs", edit).unwrap();
233            }
234            assert_eq!(cs.apply_to(Path::new("f.rs"), "ab!").unwrap(), "é!");
235        }
236    }
237
238    #[test]
239    fn edits_apply_in_span_order_regardless_of_insertion_order() {
240        let mut cs = ChangeSet::new();
241        let p = Path::new("f.rs");
242        cs.insert(p, Edit::replace(Span::new(8, 11), "qux"))
243            .unwrap();
244        cs.insert(p, Edit::replace(Span::new(0, 3), "baz")).unwrap();
245        assert_eq!(cs.apply_to(p, "foo and bar").unwrap(), "baz and qux");
246    }
247
248    #[test]
249    fn overlapping_edits_are_rejected() {
250        let mut cs = ChangeSet::new();
251        let p = Path::new("f.rs");
252        cs.insert(p, Edit::replace(Span::new(0, 5), "x")).unwrap();
253        let err = cs.insert(p, Edit::delete(Span::new(4, 8))).unwrap_err();
254        assert!(matches!(
255            err,
256            EditConflict::Overlap { existing, new, .. }
257                if existing == Span::new(0, 5) && new == Span::new(4, 8)
258        ));
259    }
260
261    #[test]
262    fn insertions_at_the_same_offset_are_allowed() {
263        let mut cs = ChangeSet::new();
264        let p = Path::new("f.rs");
265        cs.insert(p, Edit::insert(0, "a")).unwrap();
266        cs.insert(p, Edit::insert(0, "b")).unwrap();
267        assert_eq!(cs.apply_to(p, "-").unwrap(), "ab-");
268    }
269}