1use std::collections::{BTreeMap, BTreeSet};
15use std::path::{Path, PathBuf};
16
17use serde::Serialize;
18
19pub const REPORT_MARKER: char = '\u{1}';
22const REPORT_PREFIX: &str = "bynk-snapshots ";
23
24pub use bynk_project::env_protocol::SNAPSHOT_REPORT as REPORT_ENV;
26pub use bynk_project::env_protocol::UPDATE_SNAPSHOTS as UPDATE_ENV;
28
29#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize)]
34pub struct Counts {
35 pub written: u32,
36 pub updated: u32,
37 pub obsolete: u32,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct FileReport {
43 pub file: String,
44 pub written: u32,
45 pub updated: u32,
46 pub obsolete: u32,
47 pub content: Change,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum Change {
54 Absent,
55 Write(String),
56 Delete,
57}
58
59#[derive(Debug, Default, Clone, PartialEq, Eq)]
61pub struct Report {
62 pub files: Vec<FileReport>,
63}
64
65impl Report {
66 pub fn from_files_value(files: &serde_json::Value) -> Self {
69 let num = |v: &serde_json::Value, key: &str| {
70 v.get(key)
71 .and_then(serde_json::Value::as_u64)
72 .map_or(0, |n| u32::try_from(n).unwrap_or(u32::MAX))
73 };
74 let files = files
75 .as_array()
76 .map(|a| {
77 a.iter()
78 .filter_map(|f| {
79 Some(FileReport {
80 file: f.get("file")?.as_str()?.to_string(),
81 written: num(f, "written"),
82 updated: num(f, "updated"),
83 obsolete: num(f, "obsolete"),
84 content: match f.get("content") {
85 None => Change::Absent,
86 Some(serde_json::Value::Null) => Change::Delete,
87 Some(v) => Change::Write(v.as_str()?.to_string()),
88 },
89 })
90 })
91 .collect()
92 })
93 .unwrap_or_default();
94 Report { files }
95 }
96
97 pub fn from_marked_line(line: &str) -> Option<Self> {
100 let rest = line
101 .strip_prefix(REPORT_MARKER)?
102 .strip_prefix(REPORT_PREFIX)?;
103 let value: serde_json::Value = serde_json::from_str(rest.trim()).ok()?;
104 Some(Self::from_files_value(&value))
105 }
106}
107
108#[derive(Debug, Clone)]
111pub struct SnapshotRun {
112 pub update: bool,
114 root: PathBuf,
115 live: BTreeSet<String>,
116 stored: BTreeMap<String, String>,
117}
118
119impl SnapshotRun {
120 pub fn new(
123 update: bool,
124 root: &Path,
125 live: BTreeSet<String>,
126 stored: BTreeMap<String, String>,
127 ) -> Option<Self> {
128 let run = SnapshotRun {
129 update,
130 root: root.to_path_buf(),
131 live,
132 stored,
133 };
134 (!run.live.is_empty() || !run.orphans().is_empty()).then_some(run)
135 }
136
137 pub fn orphans(&self) -> Vec<(String, u32)> {
140 self.stored
141 .iter()
142 .filter(|(file, _)| !self.live.contains(*file))
143 .map(|(file, text)| (file.clone(), entries_in(text)))
144 .collect()
145 }
146
147 pub fn report_for<'r>(&self, sent: Option<&'r Report>) -> Option<std::borrow::Cow<'r, Report>> {
152 match sent {
153 Some(report) => Some(std::borrow::Cow::Borrowed(report)),
154 None if self.live.is_empty() => Some(std::borrow::Cow::Owned(Report::default())),
155 None => None,
156 }
157 }
158
159 pub fn counts(&self, report: Option<&Report>) -> Counts {
163 let mut counts = Counts::default();
164 for f in report.map_or(&[][..], |r| r.files.as_slice()) {
165 counts.written += f.written;
166 counts.updated += f.updated;
167 counts.obsolete += f.obsolete;
168 }
169 counts.obsolete += self.orphans().iter().map(|(_, n)| n).sum::<u32>();
170 counts
171 }
172
173 pub fn settle(&self, report: &Report) -> std::io::Result<Counts> {
177 if self.update {
178 for f in report.files.iter().filter(|f| self.live.contains(&f.file)) {
181 match &f.content {
182 Change::Absent => {}
183 Change::Write(text) => {
184 let path = self.root.join(&f.file);
185 if let Some(dir) = path.parent() {
186 std::fs::create_dir_all(dir)?;
187 }
188 std::fs::write(&path, text)?;
189 }
190 Change::Delete => self.remove(&f.file)?,
191 }
192 }
193 for (file, _) in self.orphans() {
194 self.remove(&file)?;
195 }
196 }
197 Ok(self.counts(Some(report)))
198 }
199
200 fn remove(&self, file: &str) -> std::io::Result<()> {
203 let path = self.root.join(file);
204 match std::fs::remove_file(&path) {
205 Ok(()) => {}
206 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
207 Err(e) => return Err(e),
208 }
209 let stop = self
210 .root
211 .join(bynk_project::snapshots::PROJECT_SNAPSHOTS_DIR);
212 let mut dir = path.parent().map(Path::to_path_buf);
213 while let Some(d) = dir {
214 if !d.starts_with(&stop) || std::fs::remove_dir(&d).is_err() {
215 break;
216 }
217 dir = d.parent().map(Path::to_path_buf);
218 }
219 Ok(())
220 }
221
222 pub fn summary_line(&self, counts: Counts) -> Option<String> {
224 let mut parts = Vec::new();
225 if counts.written > 0 {
226 parts.push(format!("{} written", counts.written));
227 }
228 if counts.updated > 0 {
229 parts.push(format!("{} updated", counts.updated));
230 }
231 if counts.obsolete > 0 {
232 parts.push(if self.update {
233 format!("{} obsolete removed", counts.obsolete)
234 } else {
235 format!(
236 "{} obsolete (remove with --update-snapshots)",
237 counts.obsolete
238 )
239 });
240 }
241 (!parts.is_empty()).then(|| format!("snapshots: {}", parts.join(", ")))
242 }
243}
244
245fn entries_in(text: &str) -> u32 {
248 match serde_json::from_str::<serde_json::Value>(text) {
249 Ok(serde_json::Value::Object(cases)) => cases
250 .values()
251 .map(|c| c.as_object().map_or(1, |o| o.len()))
252 .sum::<usize>()
253 .try_into()
254 .unwrap_or(u32::MAX),
255 _ => 1,
256 }
257}
258
259#[cfg(test)]
260mod tests {
261 use super::*;
262
263 fn run(update: bool, live: &[&str], stored: &[(&str, &str)]) -> Option<SnapshotRun> {
264 SnapshotRun::new(
265 update,
266 Path::new("/nowhere"),
267 live.iter().map(|s| s.to_string()).collect(),
268 stored
269 .iter()
270 .map(|(k, v)| (k.to_string(), v.to_string()))
271 .collect(),
272 )
273 }
274
275 #[test]
276 fn a_project_without_snapshots_has_no_run() {
277 assert!(run(false, &[], &[]).is_none());
278 }
279
280 #[test]
281 fn an_unclaimed_file_is_obsolete_by_its_entries() {
282 let r = run(
283 false,
284 &["snapshots/a.snap.json"],
285 &[
286 ("snapshots/a.snap.json", "{}"),
287 (
288 "snapshots/b.snap.json",
289 r#"{"c":{"x":1,"y":2},"d":{"z":3}}"#,
290 ),
291 ],
292 )
293 .unwrap();
294 assert_eq!(r.orphans(), vec![("snapshots/b.snap.json".to_string(), 3)]);
295 assert_eq!(r.counts(None).obsolete, 3);
296 }
297
298 #[test]
299 fn a_report_line_round_trips() {
300 let line = "\u{1}bynk-snapshots [{\"file\":\"snapshots/a.snap.json\",\"written\":1,\"updated\":2,\"obsolete\":3,\"content\":\"{}\\n\"},{\"file\":\"snapshots/b.snap.json\",\"written\":0,\"updated\":0,\"obsolete\":1,\"content\":null}]";
301 let report = Report::from_marked_line(line).unwrap();
302 assert_eq!(report.files.len(), 2);
303 assert_eq!(report.files[0].content, Change::Write("{}\n".to_string()));
304 assert_eq!(report.files[1].content, Change::Delete);
305 assert!(Report::from_marked_line(" ✓ a case").is_none());
306 }
307
308 #[test]
309 fn the_summary_says_what_changed() {
310 let r = run(false, &["snapshots/a.snap.json"], &[]).unwrap();
311 assert_eq!(r.summary_line(Counts::default()), None);
312 assert_eq!(
313 r.summary_line(Counts {
314 written: 2,
315 updated: 1,
316 obsolete: 3
317 })
318 .as_deref(),
319 Some("snapshots: 2 written, 1 updated, 3 obsolete (remove with --update-snapshots)")
320 );
321 }
322}