Skip to main content

layline_codegen/emit/
committed.rs

1//! Writing generated files to disk and checking them.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::path::{Path, PathBuf};
5
6/// The files a generator writes, and the command that regenerates them.
7///
8/// [`update`](Self::update) writes the files. [`check`](Self::check) compares them with disk.
9///
10/// ```no_run
11/// use layline_codegen::emit::{Committed, Module, generate};
12///
13/// /// Regenerates the artifact.
14/// const COMMAND: &str = "cargo codegen";
15///
16/// fn committed() -> Committed {
17///     let module = Module::new(vec![]).with_doc(vec![format!("Regenerate with `{COMMAND}`.")]);
18///     Committed::by(COMMAND).file("src/generated/wire.rs", generate(&module).unwrap().source)
19/// }
20///
21/// fn main() {
22///     for change in committed().update().expect("write the artifact") {
23///         println!("{change}");
24///     }
25/// }
26///
27/// #[test]
28/// fn the_committed_source_is_what_the_emitter_writes() {
29///     committed().check().expect("the committed artifact is current");
30/// }
31/// ```
32#[derive(Debug, Clone)]
33pub struct Committed {
34    command: String,
35    files: BTreeMap<PathBuf, String>,
36    owned: BTreeSet<PathBuf>,
37}
38
39impl Committed {
40    /// An empty set of files, regenerated by `command`.
41    ///
42    /// Failures quote `command`, so it should run from the repository root.
43    #[must_use]
44    pub fn by(command: impl Into<String>) -> Self {
45        Self { command: command.into(), files: BTreeMap::new(), owned: BTreeSet::new() }
46    }
47
48    /// Adds a file. A later call for the same path replaces it.
49    #[must_use]
50    pub fn file(mut self, path: impl Into<PathBuf>, contents: impl Into<String>) -> Self {
51        self.files.insert(path.into(), contents.into());
52        self
53    }
54
55    /// Adds a directory whose `.rs` files must be exactly `files`, as (name, contents) pairs.
56    ///
57    /// Other `.rs` files in `dir` are reported and deleted. Everything else is left alone.
58    #[must_use]
59    pub fn dir<N, C>(
60        mut self,
61        dir: impl Into<PathBuf>,
62        files: impl IntoIterator<Item = (N, C)>,
63    ) -> Self
64    where
65        N: AsRef<Path>,
66        C: Into<String>,
67    {
68        let dir = dir.into();
69        for (name, contents) in files {
70            self.files.insert(dir.join(name), contents.into());
71        }
72        self.owned.insert(dir);
73        self
74    }
75
76    /// Writes changed files, creating parent directories, and deletes extra ones.
77    ///
78    /// Returns the changes in path order.
79    ///
80    /// # Errors
81    ///
82    /// The first filesystem error.
83    pub fn update(&self) -> std::io::Result<Vec<Change>> {
84        let mut changes = Vec::new();
85        for (path, contents) in &self.files {
86            let want = normalize_newlines(contents);
87            if reads_as(path, &want) {
88                continue;
89            }
90            if let Some(parent) = path.parent() {
91                std::fs::create_dir_all(parent)?;
92            }
93            std::fs::write(path, &want)?;
94            changes.push(Change::Wrote(path.clone()));
95        }
96        for extra in self.extra()? {
97            std::fs::remove_file(&extra)?;
98            changes.push(Change::Removed(extra));
99        }
100        Ok(changes)
101    }
102
103    /// Checks the files on disk without changing them.
104    ///
105    /// An unreadable file counts as [`Drift::Missing`].
106    ///
107    /// # Errors
108    ///
109    /// [`Drifted`], listing every mismatched path and the command that fixes it.
110    pub fn check(&self) -> Result<(), Drifted> {
111        let mut paths = Vec::new();
112        for (path, contents) in &self.files {
113            match std::fs::read_to_string(path) {
114                Ok(have) if normalize_newlines(&have) == normalize_newlines(contents) => {}
115                Ok(_) => paths.push((path.clone(), Drift::Stale)),
116                Err(_) => paths.push((path.clone(), Drift::Missing)),
117            }
118        }
119        for extra in self.extra().unwrap_or_default() {
120            paths.push((extra, Drift::Extra));
121        }
122        if paths.is_empty() {
123            return Ok(());
124        }
125        Err(Drifted { command: self.command.clone(), ci: std::env::var_os("CI").is_some(), paths })
126    }
127
128    /// `.rs` files in an owned directory that the generator does not write.
129    fn extra(&self) -> std::io::Result<Vec<PathBuf>> {
130        let mut extra = Vec::new();
131        for dir in &self.owned {
132            for entry in std::fs::read_dir(dir)? {
133                let path = entry?.path();
134                if path.extension().is_some_and(|e| e == "rs")
135                    && path.is_file()
136                    && !self.files.contains_key(&path)
137                {
138                    extra.push(path);
139                }
140            }
141        }
142        extra.sort();
143        Ok(extra)
144    }
145}
146
147/// A change made by [`Committed::update`].
148#[derive(Debug, Clone, PartialEq, Eq)]
149#[non_exhaustive]
150pub enum Change {
151    /// The file was written.
152    Wrote(PathBuf),
153    /// The file was deleted from an owned directory.
154    Removed(PathBuf),
155}
156
157impl std::fmt::Display for Change {
158    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
159        match self {
160            Self::Wrote(p) => write!(f, "wrote   {}", p.display()),
161            Self::Removed(p) => write!(f, "removed {} (no longer generated)", p.display()),
162        }
163    }
164}
165
166/// How a path differs from the generator's output.
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168#[non_exhaustive]
169pub enum Drift {
170    /// The contents differ.
171    Stale,
172    /// The file is absent or unreadable.
173    Missing,
174    /// The file is in an [owned](Committed::dir) directory but not generated.
175    Extra,
176}
177
178impl Drift {
179    const fn label(self) -> &'static str {
180        match self {
181            Self::Stale => "stale  ",
182            Self::Missing => "missing",
183            Self::Extra => "extra  ",
184        }
185    }
186}
187
188/// Files on disk differ from the generator's output.
189///
190/// `Debug` prints the same text as `Display`.
191#[derive(Clone)]
192pub struct Drifted {
193    command: String,
194    ci: bool,
195    paths: Vec<(PathBuf, Drift)>,
196}
197
198impl Drifted {
199    /// Each mismatched path, and how it differs.
200    #[must_use]
201    pub fn paths(&self) -> &[(PathBuf, Drift)] {
202        &self.paths
203    }
204
205    /// The command that regenerates the files.
206    #[must_use]
207    pub fn command(&self) -> &str {
208        &self.command
209    }
210}
211
212impl std::fmt::Display for Drifted {
213    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214        let n = self.paths.len();
215        let s = if n == 1 { "" } else { "s" };
216        writeln!(f, "{n} path{s} out of date:")?;
217        for (path, how) in &self.paths {
218            writeln!(f, "  {}  {}", how.label(), path.display())?;
219        }
220        write!(f, "\nRun `{}` and review the diff. It changes the wire format.", self.command)?;
221        if self.ci {
222            write!(f, "\n    NOTE: run `{}` locally and commit the updated files.", self.command)?;
223        }
224        Ok(())
225    }
226}
227
228impl std::fmt::Debug for Drifted {
229    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
230        std::fmt::Display::fmt(self, f)
231    }
232}
233
234impl core::error::Error for Drifted {}
235
236fn normalize_newlines(s: &str) -> String {
237    s.replace("\r\n", "\n")
238}
239
240fn reads_as(path: &Path, contents: &str) -> bool {
241    std::fs::read_to_string(path).is_ok_and(|old| normalize_newlines(&old) == contents)
242}