Skip to main content

soothfast_docs/
lockfile.rs

1//! `soothfast.lock`: committed fingerprints for every bound item. A bind is
2//! stale when the item's current fingerprint differs from the locked one;
3//! `docs accept` re-locks after the prose has been re-verified by a human.
4
5use std::collections::{BTreeMap, BTreeSet};
6use std::path::Path;
7
8use serde_json::{Value, json};
9
10/// Lockfile name, resolved relative to the workspace root.
11pub const LOCKFILE: &str = "soothfast.lock";
12
13/// item path → fingerprint (hex).
14pub type Binds = BTreeMap<String, String>;
15
16/// Current lockfile format. Bumped whenever the fingerprint input changes, so
17/// a lock written by an older release reports as needing one re-accept rather
18/// than as prose that drifted.
19pub const VERSION: u64 = 2;
20
21/// Accepted binds, and the format version they were written under.
22#[derive(Debug, Default)]
23pub struct Lock {
24    /// Format on disk. A lockfile that does not exist yet reports [`VERSION`].
25    pub version: u64,
26    /// item path → fingerprint (hex).
27    pub binds: Binds,
28}
29
30/// Read `root`'s lockfile. A missing file is an empty map at the current
31/// version, not an error (a fresh repo has accepted nothing yet). A file
32/// without a `version` key predates the field and reads as v1.
33pub fn read(root: &Path) -> Result<Lock, String> {
34    let path = root.join(LOCKFILE);
35    if !path.exists() {
36        return Ok(Lock {
37            version: VERSION,
38            binds: Binds::new(),
39        });
40    }
41    let text = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
42    let doc: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
43    let mut binds = Binds::new();
44    if let Some(map) = doc["binds"].as_object() {
45        for (k, v) in map {
46            if let Some(fp) = v.as_str() {
47                binds.insert(k.clone(), fp.to_string());
48            }
49        }
50    }
51    Ok(Lock {
52        version: doc["version"].as_u64().unwrap_or(1),
53        binds,
54    })
55}
56
57/// Persist `binds` to `root`'s lockfile as stable, pretty-printed JSON.
58pub fn write(root: &Path, binds: &Binds) -> Result<(), String> {
59    let doc = json!({ "version": VERSION, "binds": binds });
60    let text = serde_json::to_string_pretty(&doc).map_err(|e| e.to_string())?;
61    std::fs::write(root.join(LOCKFILE), text + "\n").map_err(|e| e.to_string())
62}
63
64/// Overlay freshly accepted binds on `existing`, keeping every other entry.
65pub fn merge(existing: &Binds, fresh: &Binds) -> Binds {
66    let mut merged = existing.clone();
67    merged.extend(fresh.iter().map(|(k, v)| (k.clone(), v.clone())));
68    merged
69}
70
71/// Locked binds that no marker in `bound` names. Only meaningful when
72/// `bound` holds the targets of every configured docs page.
73pub fn orphans(locked: &Binds, bound: &BTreeSet<&str>) -> Vec<String> {
74    locked
75        .keys()
76        .filter(|target| !bound.contains(target.as_str()))
77        .cloned()
78        .collect()
79}
80
81/// The entries of `lock` a fresh accept may merge over.
82///
83/// Fingerprints from an older format are not comparable to what this build
84/// derives, so they are dropped rather than carried under a stamp claiming
85/// they are current; their pages read as unlocked until their own
86/// `docs accept` runs, which is what lets a repo migrate one accept at a
87/// time.
88///
89/// A lock from a *newer* format is equally incomparable but is not this
90/// build's to discard, so it is refused instead. The asymmetry is the point:
91/// an older entry is worthless, a newer one is someone else's valid work.
92/// Accepting is deliberately stricter than checking here: a check against a
93/// newer lock only misreports, while an accept would overwrite it.
94pub fn comparable(lock: Lock) -> Result<Binds, String> {
95    if lock.version > VERSION {
96        return Err(format!(
97            "{LOCKFILE} is format v{}, this build writes v{VERSION}: upgrade cargo-soothfast rather than overwriting a newer lock",
98            lock.version
99        ));
100    }
101    if lock.version == VERSION {
102        Ok(lock.binds)
103    } else {
104        Ok(Binds::new())
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    fn binds(pairs: &[(&str, &str)]) -> Binds {
113        pairs
114            .iter()
115            .map(|(k, v)| (k.to_string(), v.to_string()))
116            .collect()
117    }
118
119    #[test]
120    fn partial_scope_merge_preserves_out_of_scope_entries() {
121        let existing = binds(&[("a::x", "1111"), ("b::y", "2222")]);
122        let fresh = binds(&[("a::x", "9999")]);
123        let merged = merge(&existing, &fresh);
124        assert_eq!(merged.get("a::x").map(String::as_str), Some("9999"));
125        assert_eq!(merged.get("b::y").map(String::as_str), Some("2222"));
126        assert_eq!(merged.len(), 2);
127    }
128
129    #[test]
130    fn entries_from_an_older_format_are_not_merged_over() {
131        let lock = Lock {
132            version: VERSION - 1,
133            binds: binds(&[("a::x", "1111")]),
134        };
135        assert!(comparable(lock).unwrap().is_empty());
136    }
137
138    #[test]
139    fn entries_from_this_format_survive_a_partial_accept() {
140        let lock = Lock {
141            version: VERSION,
142            binds: binds(&[("a::x", "1111")]),
143        };
144        assert_eq!(comparable(lock).unwrap().len(), 1);
145    }
146
147    #[test]
148    fn a_newer_lock_is_refused_rather_than_overwritten() {
149        let lock = Lock {
150            version: VERSION + 1,
151            binds: binds(&[("a::x", "1111")]),
152        };
153        assert!(comparable(lock).is_err());
154    }
155
156    #[test]
157    fn orphans_are_the_locked_binds_no_marker_names() {
158        let locked = binds(&[("a::x", "1111"), ("gone::z", "2222"), ("old::w", "3333")]);
159        let bound = BTreeSet::from(["a::x", "unlocked::q"]);
160        assert_eq!(orphans(&locked, &bound), ["gone::z", "old::w"]);
161    }
162
163    #[test]
164    fn a_fully_bound_lock_has_no_orphans() {
165        let locked = binds(&[("a::x", "1111")]);
166        assert!(orphans(&locked, &BTreeSet::from(["a::x"])).is_empty());
167    }
168}