layline_codegen/emit/
committed.rs1use std::collections::{BTreeMap, BTreeSet};
4use std::path::{Path, PathBuf};
5
6#[derive(Debug, Clone)]
33pub struct Committed {
34 command: String,
35 files: BTreeMap<PathBuf, String>,
36 owned: BTreeSet<PathBuf>,
37}
38
39impl Committed {
40 #[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 #[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 #[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 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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
149#[non_exhaustive]
150pub enum Change {
151 Wrote(PathBuf),
153 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168#[non_exhaustive]
169pub enum Drift {
170 Stale,
172 Missing,
174 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#[derive(Clone)]
192pub struct Drifted {
193 command: String,
194 ci: bool,
195 paths: Vec<(PathBuf, Drift)>,
196}
197
198impl Drifted {
199 #[must_use]
201 pub fn paths(&self) -> &[(PathBuf, Drift)] {
202 &self.paths
203 }
204
205 #[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}