Skip to main content

reflex/pulse/render/
project.rs

1//! Write files into a staged project only when their bytes change.
2//!
3//! Unchanged files keep their mtime, which keeps Astro's and Vite's caches warm.
4//! `.pulse-files.json` records what the last run wrote, so files of pages that no
5//! longer exist are removed (only under managed prefixes; the template is never swept).
6
7use crate::atomic_write::{atomic_replace, tmp_path_for};
8use anyhow::{Context, Result};
9use std::collections::BTreeMap;
10use std::path::{Path, PathBuf};
11
12const MANIFEST: &str = ".pulse-files.json";
13
14#[derive(Debug, Default, Clone, Copy)]
15pub struct WriteStats {
16    pub written: usize,
17    pub unchanged: usize,
18    pub removed: usize,
19}
20
21pub struct ProjectWriter {
22    root: PathBuf,
23    prev: BTreeMap<String, String>,
24    now: BTreeMap<String, String>,
25    stats: WriteStats,
26}
27
28impl ProjectWriter {
29    pub fn open(root: &Path) -> Result<Self> {
30        std::fs::create_dir_all(root).with_context(|| format!("creating {}", root.display()))?;
31        let prev = std::fs::read(root.join(MANIFEST))
32            .ok()
33            .and_then(|b| serde_json::from_slice(&b).ok())
34            .unwrap_or_default();
35        Ok(Self {
36            root: root.to_path_buf(),
37            prev,
38            now: BTreeMap::new(),
39            stats: WriteStats::default(),
40        })
41    }
42
43    /// Write `rel` unless it already holds exactly `bytes`.
44    pub fn put(&mut self, rel: &str, bytes: &[u8]) -> Result<()> {
45        let hash = blake3::hash(bytes).to_hex().to_string();
46        let path = self.root.join(rel);
47        let same = self.prev.get(rel) == Some(&hash) && path.exists();
48        if same {
49            self.stats.unchanged += 1;
50        } else {
51            if let Some(parent) = path.parent() {
52                std::fs::create_dir_all(parent)?;
53            }
54            let tmp = tmp_path_for(&path);
55            std::fs::write(&tmp, bytes).with_context(|| format!("writing {}", tmp.display()))?;
56            atomic_replace(&tmp, &path)?;
57            self.stats.written += 1;
58        }
59        self.now.insert(rel.to_string(), hash);
60        Ok(())
61    }
62
63    /// Remove files written last run under `sweep_prefix` but not this run; save the
64    /// manifest.
65    pub fn finish(mut self, sweep_prefix: &str) -> Result<WriteStats> {
66        for rel in self.prev.keys() {
67            if rel.starts_with(sweep_prefix)
68                && !self.now.contains_key(rel)
69                && std::fs::remove_file(self.root.join(rel)).is_ok()
70            {
71                self.stats.removed += 1;
72            }
73        }
74        // Keep entries this run did not touch outside the sweep prefix (template files
75        // are written by another pass with its own writer).
76        for (rel, hash) in &self.prev {
77            if !rel.starts_with(sweep_prefix) && !self.now.contains_key(rel) {
78                self.now.insert(rel.clone(), hash.clone());
79            }
80        }
81        let path = self.root.join(MANIFEST);
82        let tmp = tmp_path_for(&path);
83        std::fs::write(&tmp, serde_json::to_vec_pretty(&self.now)?)?;
84        atomic_replace(&tmp, &path)?;
85        Ok(self.stats)
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92
93    #[test]
94    fn second_run_writes_nothing_and_sweeps_removed_pages() {
95        let dir = tempfile::TempDir::new().unwrap();
96        let mut w = ProjectWriter::open(dir.path()).unwrap();
97        w.put("bundle/pages/a.json", b"A").unwrap();
98        w.put("bundle/pages/b.json", b"B").unwrap();
99        w.put("pulse.config.json", b"{}").unwrap();
100        let s = w.finish("bundle/").unwrap();
101        assert_eq!((s.written, s.unchanged, s.removed), (3, 0, 0));
102
103        let mut w = ProjectWriter::open(dir.path()).unwrap();
104        w.put("bundle/pages/a.json", b"A").unwrap();
105        w.put("pulse.config.json", b"{}").unwrap();
106        let s = w.finish("bundle/").unwrap();
107        assert_eq!((s.written, s.unchanged, s.removed), (0, 2, 1));
108        assert!(!dir.path().join("bundle/pages/b.json").exists());
109
110        let mut w = ProjectWriter::open(dir.path()).unwrap();
111        w.put("bundle/pages/a.json", b"A2").unwrap();
112        let s = w.finish("bundle/").unwrap();
113        assert_eq!((s.written, s.unchanged, s.removed), (1, 0, 0));
114        assert!(
115            dir.path().join("pulse.config.json").exists(),
116            "outside the sweep prefix"
117        );
118    }
119}