Skip to main content

litz_cli/
build.rs

1//! `litz build`: a project's own build recipe, in TOML.
2//!
3//! Litz does not ship a compiler. A board's toolchain changes faster than a
4//! simulator should, and pinning Arduino cores or ESP-IDF inside this binary
5//! would make every project's build depend on our release schedule. Instead a
6//! project writes `litz.build.toml`, the same way it writes `litz.toml`: a
7//! short, ordered list of shell steps, each with its own directory, environment
8//! and timeout. `litz build` runs them; `litz test --build` runs them first.
9//!
10//! The recipe is deliberately close to a CI job, because that is where most
11//! firmware is built. It is not a sandbox: a step runs with the user's
12//! permissions, exactly like `make` or a GitHub Actions `run:` line, and the
13//! only path rule is that a step's working directory must stay inside the
14//! project.
15
16use crate::config::parse_duration;
17use serde::Deserialize;
18use std::collections::BTreeMap;
19use std::path::{Path, PathBuf};
20use std::process::{Command, Stdio};
21use std::time::{Duration, Instant};
22
23/// The file a project writes.
24pub const FILE: &str = "litz.build.toml";
25
26#[derive(Debug, Default, Deserialize)]
27pub struct BuildConfig {
28    #[serde(default)]
29    pub build: BuildSection,
30    /// One entry per `[[step]]`.
31    #[serde(default, rename = "step")]
32    pub steps: Vec<Step>,
33}
34
35#[derive(Debug, Default, Deserialize)]
36pub struct BuildSection {
37    /// Directory every step runs in, relative to the project.
38    #[serde(default)]
39    pub workdir: Option<String>,
40    /// Environment for every step. A step's own `env` wins on a collision.
41    #[serde(default)]
42    pub env: BTreeMap<String, String>,
43    /// A file that must exist when the last step succeeds.
44    #[serde(default)]
45    pub firmware: Option<String>,
46}
47
48#[derive(Debug, Clone, Deserialize)]
49pub struct Step {
50    /// A label for the transcript; defaults to the command.
51    #[serde(default)]
52    pub name: Option<String>,
53    /// The command, run by the platform shell.
54    pub run: String,
55    #[serde(default)]
56    pub workdir: Option<String>,
57    #[serde(default)]
58    pub env: BTreeMap<String, String>,
59    /// Wall-clock limit for this step, for example `5m`. A step without one
60    /// is limited by the caller's own patience, as `make` is.
61    #[serde(default)]
62    pub timeout: Option<String>,
63}
64
65impl BuildConfig {
66    pub fn load(dir: &Path) -> Result<Self, String> {
67        let path = dir.join(FILE);
68        let text =
69            std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
70        let config: BuildConfig =
71            toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
72        config.validate()?;
73        Ok(config)
74    }
75
76    fn validate(&self) -> Result<(), String> {
77        if self.steps.is_empty() {
78            return Err(format!("{FILE}: at least one [[step]] is required"));
79        }
80        for (index, step) in self.steps.iter().enumerate() {
81            if step.run.trim().is_empty() {
82                return Err(format!("{FILE}: step {} has an empty `run`", index + 1));
83            }
84            if let Some(timeout) = &step.timeout {
85                parse_duration(timeout)
86                    .map_err(|e| format!("{FILE}: step {} timeout: {e}", index + 1))?;
87            }
88        }
89        Ok(())
90    }
91}
92
93/// Run a project's recipe. Returns a transcript; an error means a step failed
94/// or the recipe could not be loaded.
95pub fn run(dir: &Path, dry_run: bool) -> Result<String, String> {
96    let config = BuildConfig::load(dir)?;
97    let root = dir
98        .canonicalize()
99        .map_err(|e| format!("{}: {e}", dir.display()))?;
100    let mut output = String::new();
101    for (index, step) in config.steps.iter().enumerate() {
102        let label = step.name.clone().unwrap_or_else(|| step.run.clone());
103        output.push_str(&format!(
104            "[build {}/{}] {label}\n",
105            index + 1,
106            config.steps.len()
107        ));
108        if dry_run {
109            output.push_str(&format!("  $ {}\n", step.run));
110            continue;
111        }
112        let workdir = resolve_workdir(
113            &root,
114            config.build.workdir.as_deref(),
115            step.workdir.as_deref(),
116        )?;
117        let mut env: BTreeMap<&str, &str> = BTreeMap::new();
118        for (key, value) in &config.build.env {
119            env.insert(key, value);
120        }
121        for (key, value) in &step.env {
122            env.insert(key, value);
123        }
124        let timeout = step
125            .timeout
126            .as_deref()
127            .map(parse_duration)
128            .transpose()?
129            .map(Duration::from_nanos);
130        let step_output = execute(&step.run, &workdir, &env, timeout)
131            .map_err(|e| format!("step {} ({label}): {e}", index + 1))?;
132        output.push_str(&step_output);
133        if !output.ends_with('\n') {
134            output.push('\n');
135        }
136    }
137    if let Some(firmware) = &config.build.firmware {
138        let path = root.join(firmware);
139        if !dry_run && !path.exists() {
140            return Err(format!(
141                "[build] firmware = {firmware:?} does not exist after the last step"
142            ));
143        }
144    }
145    Ok(output)
146}
147
148/// A step's working directory, refused when it leaves the project.
149fn resolve_workdir(
150    root: &Path,
151    default: Option<&str>,
152    step: Option<&str>,
153) -> Result<PathBuf, String> {
154    let relative = step.or(default).unwrap_or(".");
155    if relative.split(['/', '\\']).any(|part| part == "..") {
156        return Err(format!("build workdir {relative:?} escapes the project"));
157    }
158    let path = root.join(relative);
159    let path = path
160        .canonicalize()
161        .map_err(|e| format!("{}: {e}", path.display()))?;
162    if !path.starts_with(root) {
163        return Err(format!("build workdir {relative:?} escapes the project"));
164    }
165    Ok(path)
166}
167
168/// Run one command through the platform shell and capture its transcript.
169fn execute(
170    command: &str,
171    workdir: &Path,
172    env: &BTreeMap<&str, &str>,
173    timeout: Option<Duration>,
174) -> Result<String, String> {
175    #[cfg(windows)]
176    let mut child = {
177        let mut cmd = Command::new("cmd");
178        cmd.arg("/C").arg(command);
179        cmd
180    };
181    #[cfg(not(windows))]
182    let mut child = {
183        let mut cmd = Command::new("sh");
184        cmd.arg("-c").arg(command);
185        cmd
186    };
187    child
188        .current_dir(workdir)
189        .envs(env.iter().map(|(key, value)| (*key, *value)))
190        .stdout(Stdio::piped())
191        .stderr(Stdio::piped());
192    let mut child = child
193        .spawn()
194        .map_err(|e| format!("cannot start {command:?}: {e}"))?;
195
196    let started = Instant::now();
197    loop {
198        match child.try_wait() {
199            Ok(Some(_)) => break,
200            Ok(None) => {}
201            Err(e) => return Err(format!("waiting for {command:?}: {e}")),
202        }
203        if let Some(limit) = timeout
204            && started.elapsed() >= limit
205        {
206            let _ = child.kill();
207            let _ = child.wait();
208            return Err(format!(
209                "{command:?} did not finish within {} ms",
210                limit.as_millis()
211            ));
212        }
213        std::thread::sleep(Duration::from_millis(10));
214    }
215    let output = child
216        .wait_with_output()
217        .map_err(|e| format!("reading the output of {command:?}: {e}"))?;
218    let mut text = String::from_utf8_lossy(&output.stdout).into_owned();
219    text.push_str(&String::from_utf8_lossy(&output.stderr));
220    if !output.status.success() {
221        let code = output
222            .status
223            .code()
224            .map(|code| code.to_string())
225            .unwrap_or_else(|| "a signal".to_string());
226        return Err(format!("{command:?} exited with {code}"));
227    }
228    Ok(text)
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    fn scratch(tag: &str) -> PathBuf {
236        static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
237        let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
238        let dir = std::env::temp_dir().join(format!("litz-build-{}-{n}-{tag}", std::process::id()));
239        let _ = std::fs::remove_dir_all(&dir);
240        std::fs::create_dir_all(&dir).unwrap();
241        dir
242    }
243
244    #[test]
245    fn a_recipe_runs_every_step_in_order() {
246        let dir = scratch("ok");
247        std::fs::write(
248            dir.join(FILE),
249            r#"
250[build]
251firmware = "out/app.bin"
252
253[[step]]
254name = "first"
255run = "mkdir -p out && printf one > out/app.bin"
256
257[[step]]
258name = "second"
259run = "printf two >> out/app.bin"
260"#,
261        )
262        .unwrap();
263        let text = run(&dir, false).unwrap();
264        assert!(text.contains("[build 1/2] first"), "{text}");
265        assert!(text.contains("[build 2/2] second"), "{text}");
266        assert_eq!(std::fs::read(dir.join("out/app.bin")).unwrap(), b"onetwo");
267        let _ = std::fs::remove_dir_all(&dir);
268    }
269
270    #[test]
271    fn a_failing_step_stops_the_recipe() {
272        let dir = scratch("fail");
273        std::fs::write(
274            dir.join(FILE),
275            r#"
276[[step]]
277run = "printf before"
278
279[[step]]
280name = "explode"
281run = "exit 7"
282
283[[step]]
284run = "printf after"
285"#,
286        )
287        .unwrap();
288        let error = run(&dir, false).unwrap_err();
289        assert!(error.contains("explode"), "{error}");
290        assert!(error.contains("exited with 7"), "{error}");
291        let _ = std::fs::remove_dir_all(&dir);
292    }
293
294    #[test]
295    fn a_step_workdir_may_not_leave_the_project() {
296        let dir = scratch("escape");
297        std::fs::write(
298            dir.join(FILE),
299            "[[step]]\nrun = \"true\"\nworkdir = \"../\"\n",
300        )
301        .unwrap();
302        let error = run(&dir, false).unwrap_err();
303        assert!(error.contains("escapes the project"), "{error}");
304        let _ = std::fs::remove_dir_all(&dir);
305    }
306
307    #[test]
308    fn a_missing_firmware_output_is_an_error() {
309        let dir = scratch("missing");
310        std::fs::write(
311            dir.join(FILE),
312            "[build]\nfirmware = \"out/app.bin\"\n\n[[step]]\nrun = \"true\"\n",
313        )
314        .unwrap();
315        let error = run(&dir, false).unwrap_err();
316        assert!(error.contains("does not exist"), "{error}");
317        let _ = std::fs::remove_dir_all(&dir);
318    }
319
320    #[test]
321    fn a_dry_run_runs_nothing() {
322        let dir = scratch("dry");
323        std::fs::write(
324            dir.join(FILE),
325            "[[step]]\nrun = \"touch should-not-exist\"\n",
326        )
327        .unwrap();
328        let text = run(&dir, true).unwrap();
329        assert!(text.contains("$ touch should-not-exist"), "{text}");
330        assert!(!dir.join("should-not-exist").exists());
331        let _ = std::fs::remove_dir_all(&dir);
332    }
333
334    #[test]
335    fn step_environment_reaches_the_command() {
336        let dir = scratch("env");
337        std::fs::write(
338            dir.join(FILE),
339            r#"
340[build.env]
341GLOBAL = "one"
342
343[[step]]
344run = "printf \"$GLOBAL-$LOCAL\" > out.txt"
345env = { LOCAL = "two" }
346"#,
347        )
348        .unwrap();
349        run(&dir, false).unwrap();
350        assert_eq!(std::fs::read(dir.join("out.txt")).unwrap(), b"one-two");
351        let _ = std::fs::remove_dir_all(&dir);
352    }
353
354    #[test]
355    fn an_empty_recipe_is_refused() {
356        let dir = scratch("empty");
357        std::fs::write(dir.join(FILE), "[build]\n").unwrap();
358        let error = BuildConfig::load(&dir).unwrap_err();
359        assert!(error.contains("[[step]]"), "{error}");
360        let _ = std::fs::remove_dir_all(&dir);
361    }
362}