1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//! An in-memory copy of every file a plan touches.
//!
//! Operations change the overlay, never the disk. The overlay records each
//! file's text as first read, so the finished plan knows exactly what it was
//! computed against.
use crate::{ChangeKind, FileChange, Source, content_hash, splice::SpliceLog};
use std::{
collections::BTreeMap,
path::{Path, PathBuf},
};
/// One file's state inside the overlay.
#[derive(Debug, Clone, Default)]
pub struct Slot {
/// Text as first read; `None` when the file did not exist.
pub before: Option<String>,
/// Text after every operation so far; `None` when absent.
pub current: Option<String>,
/// Splices applied so far, to map find-result ranges.
pub log: SpliceLog,
}
/// Every file the plan has read or changed.
pub struct Overlay<'a> {
source: &'a dyn Source,
slots: BTreeMap<PathBuf, Slot>,
}
impl<'a> Overlay<'a> {
/// Starts an empty overlay over `source`.
pub fn new(source: &'a dyn Source) -> Self {
Self {
source,
slots: BTreeMap::new(),
}
}
/// Returns the slot for `path`, reading it on first use.
///
/// # Errors
/// Returns the source's message when the file cannot be read.
pub fn slot(&mut self, path: &Path) -> Result<&mut Slot, String> {
if !self.slots.contains_key(path) {
let text = self.source.read(path)?;
self.slots.insert(
path.to_path_buf(),
Slot {
before: text.clone(),
current: text,
log: SpliceLog::default(),
},
);
}
self.slots
.get_mut(path)
.ok_or_else(|| format!("{}: slot vanished", path.display()))
}
/// Every file whose text changed, sorted by path.
#[must_use]
pub fn into_changes(self) -> Vec<FileChange> {
self.slots
.into_iter()
.filter(|(_, slot)| slot.before != slot.current)
.map(|(path, slot)| change(path, slot))
.collect()
}
}
fn change(path: PathBuf, slot: Slot) -> FileChange {
let kind = match (&slot.before, &slot.current) {
(None, _) => ChangeKind::Create,
(Some(_), None) => ChangeKind::Delete,
(Some(_), Some(_)) => ChangeKind::Modify,
};
FileChange {
path,
kind,
before_hash: slot.before.as_deref().map(content_hash),
after_hash: slot.current.as_deref().map(content_hash),
before: slot.before,
after: slot.current,
}
}