bynk_project/
snapshots.rs1use std::collections::BTreeMap;
10use std::io;
11use std::path::{Path, PathBuf};
12
13pub const PROJECT_SNAPSHOTS_DIR: &str = "snapshots";
15
16pub const SNAPSHOT_SUFFIX: &str = ".snap.json";
18
19pub fn snapshot_path(identity: &Path) -> String {
22 let path = identity.to_string_lossy().replace('\\', "/");
23 let stem = path.strip_suffix(".bynk").unwrap_or(&path);
24 format!("{PROJECT_SNAPSHOTS_DIR}/{stem}{SNAPSHOT_SUFFIX}")
25}
26
27pub fn read_snapshot_files(root: &Path) -> io::Result<BTreeMap<String, String>> {
31 let mut out = BTreeMap::new();
32 let dir = root.join(PROJECT_SNAPSHOTS_DIR);
33 if dir.is_dir() {
34 walk(&dir, PROJECT_SNAPSHOTS_DIR, &mut out)?;
35 }
36 Ok(out)
37}
38
39fn walk(dir: &Path, prefix: &str, out: &mut BTreeMap<String, String>) -> io::Result<()> {
40 let mut entries: Vec<PathBuf> = std::fs::read_dir(dir)?
41 .map(|e| e.map(|e| e.path()))
42 .collect::<io::Result<_>>()?;
43 entries.sort();
44 for path in entries {
45 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
46 continue;
47 };
48 let kind = std::fs::symlink_metadata(&path)?.file_type();
51 if kind.is_symlink() {
52 continue;
53 }
54 let key = format!("{prefix}/{name}");
55 if kind.is_dir() {
56 walk(&path, &key, out)?;
57 } else if name.ends_with(SNAPSHOT_SUFFIX) {
58 out.insert(key, std::fs::read_to_string(&path)?);
59 }
60 }
61 Ok(())
62}
63
64#[cfg(test)]
65mod tests {
66 use super::*;
67
68 #[test]
69 fn a_suite_file_maps_to_its_snapshot_file() {
70 assert_eq!(
71 snapshot_path(Path::new("tests/github/events.bynk")),
72 "snapshots/tests/github/events.snap.json"
73 );
74 assert_eq!(
75 snapshot_path(Path::new("tests\\a.bynk")),
76 "snapshots/tests/a.snap.json"
77 );
78 }
79}