Skip to main content

vitrify_cli/
home.rs

1//! `~/.vitrify` materialization and disk-wins resolution.
2//!
3//! Only `vitrify init` stands the home up: it writes `config.toml` and
4//! materializes the content. Every other command first checks that it is
5//! set up — `config.toml` is there — and otherwise refuses, naming
6//! `vitrify init` ([`require_set_up`]); the dispatch does it for all of
7//! them, and the seams that write into the home check again.
8//!
9//! The single resolution seam: `brief`, `new`, `schema`, and the
10//! escalation template all resolve assets through here. A file on disk
11//! overrides the embedded copy; a deleted file is restored on the next run;
12//! an unmodified default follows the binary — it refreshes whenever the
13//! embedded copy differs, an upgrade or a rebuild of the same version — and
14//! overrides are left in place (`vitrify init` and `vitrify probe` report
15//! them).
16
17use std::path::{Path, PathBuf};
18
19use vitrify_core::CoreError;
20use vitrify_core::content::{self, sha256_hex};
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Origin {
24    /// Served from the binary (no disk copy existed and one could not be written).
25    Embedded,
26    /// On disk, byte-identical to the shipped copy.
27    Materialized,
28    /// On disk, user-modified: disk wins.
29    Override,
30}
31
32impl Origin {
33    pub fn as_str(self) -> &'static str {
34        match self {
35            Origin::Embedded => "embedded",
36            Origin::Materialized => "materialized",
37            Origin::Override => "override",
38        }
39    }
40}
41
42/// One asset's home state, for `vitrify init` and `vitrify probe` to report.
43#[derive(Debug, Clone)]
44pub struct AssetState {
45    pub rel_path: String,
46    pub origin: Origin,
47    /// Override forked from another shipped version (manifest's recorded
48    /// shipped digest differs from the current embedded digest).
49    pub stale_against_embedded: bool,
50}
51
52#[derive(Debug, Default)]
53struct Manifest {
54    vitrify_version: String,
55    /// rel path → "sha256:<hex>" of the SHIPPED content last materialized.
56    files: Vec<(String, String)>,
57}
58
59impl Manifest {
60    fn digest_of(&self, rel: &str) -> Option<&str> {
61        self.files
62            .iter()
63            .find(|(k, _)| k == rel)
64            .map(|(_, v)| v.strip_prefix("sha256:").unwrap_or(v))
65    }
66
67    fn set(&mut self, rel: &str, hex: &str) {
68        let value = format!("sha256:{hex}");
69        match self.files.iter_mut().find(|(k, _)| k == rel) {
70            Some(slot) => slot.1 = value,
71            None => self.files.push((rel.to_string(), value)),
72        }
73    }
74}
75
76fn manifest_path(home: &Path) -> PathBuf {
77    home.join(".manifest.toml")
78}
79
80/// `~/.vitrify/config.toml`: the machine's configuration, and the mark of a
81/// home `vitrify init` has set up.
82pub fn config_path(home: &Path) -> PathBuf {
83    home.join("config.toml")
84}
85
86/// The refusal every command that needs the home gives when it is not set
87/// up: exit 4, naming the one command that sets it up.
88pub fn not_set_up() -> CoreError {
89    CoreError::refusal(
90        4,
91        "error: vitrify is not set up on this machine: ~/.vitrify/config.toml not found → vitrify init",
92    )
93}
94
95/// Refuse unless `vitrify init` has set the home up. Every command but
96/// `init` passes through it, so none but `init` ever creates the home.
97pub fn require_set_up(home: &Path) -> Result<(), CoreError> {
98    if config_path(home).is_file() {
99        Ok(())
100    } else {
101        Err(not_set_up())
102    }
103}
104
105fn read_manifest(home: &Path) -> Manifest {
106    let Ok(text) = std::fs::read_to_string(manifest_path(home)) else {
107        return Manifest::default();
108    };
109    let Ok(table) = text.parse::<toml::Table>() else {
110        return Manifest::default();
111    };
112    let mut m = Manifest {
113        vitrify_version: table
114            .get("vitrify_version")
115            .and_then(|v| v.as_str())
116            .unwrap_or("")
117            .to_string(),
118        files: Vec::new(),
119    };
120    if let Some(files) = table.get("files").and_then(|v| v.as_table()) {
121        for (k, v) in files {
122            if let Some(s) = v.as_str() {
123                m.files.push((k.clone(), s.to_string()));
124            }
125        }
126    }
127    m
128}
129
130fn write_manifest(home: &Path, m: &Manifest) -> Result<(), CoreError> {
131    let mut text = String::from("schema = 1\n");
132    text.push_str(&format!(
133        "vitrify_version = \"{}\"\n\n[files]\n",
134        m.vitrify_version
135    ));
136    let mut files = m.files.clone();
137    files.sort();
138    for (k, v) in &files {
139        text.push_str(&format!("\"{k}\" = \"{v}\"\n"));
140    }
141    // atomic: temp + rename
142    let tmp = home.join(".manifest.toml.tmp");
143    std::fs::write(&tmp, &text).map_err(|source| CoreError::Io {
144        path: tmp.clone(),
145        source,
146    })?;
147    std::fs::rename(&tmp, manifest_path(home)).map_err(|source| CoreError::Io {
148        path: manifest_path(home),
149        source,
150    })?;
151    Ok(())
152}
153
154/// Ensure `~/.vitrify/` is materialized per the staleness rules; returns the
155/// per-asset state for `init` and `probe` to report. Idempotent; reached by
156/// every content consumer through [`resolve`], which refuses a home that is
157/// not set up, and by `vitrify init`, which sets it up.
158pub fn ensure_materialized(home: &Path, version: &str) -> Result<Vec<AssetState>, CoreError> {
159    std::fs::create_dir_all(home).map_err(|source| CoreError::Io {
160        path: home.to_path_buf(),
161        source,
162    })?;
163    let mut manifest = read_manifest(home);
164    let mut states = Vec::new();
165
166    for asset in content::assets() {
167        let disk_path = home.join(asset.rel_path);
168        let disk = std::fs::read_to_string(&disk_path).ok();
169        let state = match disk {
170            None => {
171                // absent (or deleted): materialize the shipped copy
172                if let Some(parent) = disk_path.parent() {
173                    std::fs::create_dir_all(parent).map_err(|source| CoreError::Io {
174                        path: parent.to_path_buf(),
175                        source,
176                    })?;
177                }
178                std::fs::write(&disk_path, asset.body).map_err(|source| CoreError::Io {
179                    path: disk_path.clone(),
180                    source,
181                })?;
182                manifest.set(asset.rel_path, asset.sha256);
183                AssetState {
184                    rel_path: asset.rel_path.to_string(),
185                    origin: Origin::Materialized,
186                    stale_against_embedded: false,
187                }
188            }
189            Some(body) => {
190                let disk_digest = sha256_hex(&body);
191                let recorded = manifest.digest_of(asset.rel_path).map(str::to_string);
192                let unmodified = recorded.as_deref() == Some(disk_digest.as_str());
193                if unmodified {
194                    if disk_digest != asset.sha256 {
195                        // an unmodified default another build shipped — an
196                        // older version, or this one built from other
197                        // content: refresh
198                        std::fs::write(&disk_path, asset.body).map_err(|source| CoreError::Io {
199                            path: disk_path.clone(),
200                            source,
201                        })?;
202                        manifest.set(asset.rel_path, asset.sha256);
203                    }
204                    AssetState {
205                        rel_path: asset.rel_path.to_string(),
206                        origin: if sha256_hex(
207                            &std::fs::read_to_string(&disk_path).unwrap_or_default(),
208                        ) == asset.sha256
209                        {
210                            Origin::Materialized
211                        } else {
212                            Origin::Override
213                        },
214                        stale_against_embedded: false,
215                    }
216                } else if disk_digest == asset.sha256 {
217                    // matches the current shipped bytes (e.g. fresh manifest)
218                    manifest.set(asset.rel_path, asset.sha256);
219                    AssetState {
220                        rel_path: asset.rel_path.to_string(),
221                        origin: Origin::Materialized,
222                        stale_against_embedded: false,
223                    }
224                } else {
225                    // user override: left in place; stale when forked from
226                    // another shipped version
227                    let stale = recorded.is_some_and(|r| r != asset.sha256);
228                    AssetState {
229                        rel_path: asset.rel_path.to_string(),
230                        origin: Origin::Override,
231                        stale_against_embedded: stale,
232                    }
233                }
234            }
235        };
236        states.push(state);
237    }
238    manifest.vitrify_version = version.to_string();
239    write_manifest(home, &manifest)?;
240    Ok(states)
241}
242
243/// Resolve one asset disk-first: the `~/.vitrify` copy wins over the
244/// embedded copy. Refuses a home `vitrify init` has not set up; in one it
245/// has, materializes on every call (delete-restores).
246pub fn resolve(home: &Path, version: &str, rel: &str) -> Result<(String, Origin), CoreError> {
247    require_set_up(home)?;
248    ensure_materialized(home, version)?;
249    let disk_path = home.join(rel);
250    if let Ok(body) = std::fs::read_to_string(&disk_path) {
251        let origin = match content::get(rel) {
252            Some(asset) if sha256_hex(&body) == asset.sha256 => Origin::Materialized,
253            _ => Origin::Override,
254        };
255        return Ok((body, origin));
256    }
257    match content::get(rel) {
258        Some(asset) => Ok((asset.body.to_string(), Origin::Embedded)),
259        None => Err(CoreError::refusal(
260            4,
261            format!("error: unknown asset: {rel}"),
262        )),
263    }
264}