1use crate::config::parse_duration;
17use serde::Deserialize;
18use std::collections::BTreeMap;
19use std::io::Read;
20use std::path::{Path, PathBuf};
21use std::process::{Command, Stdio};
22use std::time::{Duration, Instant};
23
24pub const FILE: &str = "litz.build.toml";
26
27#[derive(Debug, Default, Deserialize)]
28pub struct BuildConfig {
29 #[serde(default)]
30 pub build: BuildSection,
31 #[serde(default, rename = "step")]
33 pub steps: Vec<Step>,
34}
35
36#[derive(Debug, Default, Deserialize)]
37pub struct BuildSection {
38 #[serde(default)]
40 pub workdir: Option<String>,
41 #[serde(default)]
43 pub env: BTreeMap<String, String>,
44 #[serde(default)]
46 pub firmware: Option<String>,
47}
48
49#[derive(Debug, Clone, Deserialize)]
50pub struct Step {
51 #[serde(default)]
53 pub name: Option<String>,
54 pub run: String,
56 #[serde(default)]
57 pub workdir: Option<String>,
58 #[serde(default)]
59 pub env: BTreeMap<String, String>,
60 #[serde(default)]
63 pub timeout: Option<String>,
64}
65
66impl BuildConfig {
67 pub fn load(dir: &Path) -> Result<Self, String> {
68 let path = dir.join(FILE);
69 let text =
70 std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
71 let config: BuildConfig =
72 toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
73 config.validate()?;
74 Ok(config)
75 }
76
77 fn validate(&self) -> Result<(), String> {
78 if self.steps.is_empty() {
79 return Err(format!("{FILE}: at least one [[step]] is required"));
80 }
81 for (index, step) in self.steps.iter().enumerate() {
82 if step.run.trim().is_empty() {
83 return Err(format!("{FILE}: step {} has an empty `run`", index + 1));
84 }
85 if let Some(timeout) = &step.timeout {
86 parse_duration(timeout)
87 .map_err(|e| format!("{FILE}: step {} timeout: {e}", index + 1))?;
88 }
89 }
90 Ok(())
91 }
92}
93
94pub fn run(dir: &Path, dry_run: bool) -> Result<String, String> {
97 let mut output = String::new();
98 run_with(dir, dry_run, &mut |chunk| output.push_str(chunk))?;
99 Ok(output)
100}
101
102pub fn run_with(dir: &Path, dry_run: bool, emit: &mut dyn FnMut(&str)) -> Result<(), String> {
106 let config = BuildConfig::load(dir)?;
107 let root = dir
108 .canonicalize()
109 .map_err(|e| format!("{}: {e}", dir.display()))?;
110 for (index, step) in config.steps.iter().enumerate() {
111 let label = step.name.clone().unwrap_or_else(|| step.run.clone());
112 emit(&format!(
113 "[build {}/{}] {label}\n",
114 index + 1,
115 config.steps.len()
116 ));
117 if dry_run {
118 emit(&format!(" $ {}\n", step.run));
119 continue;
120 }
121 let workdir = resolve_workdir(
122 &root,
123 config.build.workdir.as_deref(),
124 step.workdir.as_deref(),
125 )?;
126 let mut env: BTreeMap<&str, &str> = BTreeMap::new();
127 for (key, value) in &config.build.env {
128 env.insert(key, value);
129 }
130 for (key, value) in &step.env {
131 env.insert(key, value);
132 }
133 let timeout = step
134 .timeout
135 .as_deref()
136 .map(parse_duration)
137 .transpose()?
138 .map(Duration::from_nanos);
139 execute(&step.run, &workdir, &env, timeout, emit)
140 .map_err(|e| format!("step {} ({label}): {e}", index + 1))?;
141 }
142 if let Some(firmware) = &config.build.firmware {
143 let path = root.join(firmware);
144 if !dry_run && !path.exists() {
145 return Err(format!(
146 "[build] firmware = {firmware:?} does not exist after the last step"
147 ));
148 }
149 }
150 Ok(())
151}
152
153pub fn image_for(dir: &Path, board: Option<&str>) -> Result<(Option<String>, PathBuf), String> {
160 let recipe = BuildConfig::load(dir).ok();
161 let project = litz_engine::config::Config::load_project(dir).ok();
162 let board_image = |id: &str| {
163 project.as_ref().and_then(|config| {
164 config
165 .boards
166 .iter()
167 .find(|entry| entry.id == id)
168 .and_then(|entry| {
169 entry
170 .firmware
171 .clone()
172 .map(|path| (Some(entry.id.clone()), path))
173 })
174 })
175 };
176 let single_board = || {
177 project.as_ref().and_then(|config| {
178 let [entry] = &config.boards[..] else {
179 return None;
180 };
181 entry
182 .firmware
183 .clone()
184 .map(|path| (Some(entry.id.clone()), path))
185 })
186 };
187 let built = || {
188 recipe
189 .as_ref()
190 .and_then(|recipe| recipe.build.firmware.clone())
191 };
192 let configured = || {
193 project
194 .as_ref()
195 .and_then(|config| config.sim.firmware.clone())
196 };
197
198 let mut candidates: Vec<(Option<String>, String)> = Vec::new();
199 match board {
200 Some(id) => {
201 if let Some(hit) = board_image(id) {
202 candidates.push(hit);
203 }
204 if let Some(path) = built() {
205 candidates.push((Some(id.to_string()), path));
206 }
207 if let Some(path) = configured() {
208 candidates.push((Some(id.to_string()), path));
209 }
210 }
211 None => {
212 if let Some(path) = built() {
213 candidates.push((None, path));
214 }
215 if let Some(path) = configured() {
216 candidates.push((None, path));
217 }
218 if let Some(hit) = single_board() {
219 candidates.push(hit);
220 }
221 }
222 }
223 for (name, path) in candidates {
224 let path = dir.join(path);
225 if path.is_file() {
226 return Ok((name, path));
227 }
228 }
229 let available: Vec<String> = project
230 .map(|config| config.boards.into_iter().map(|entry| entry.id).collect())
231 .unwrap_or_default();
232 Err(match board {
233 Some(id) if !available.is_empty() => format!(
234 "no firmware for board {id:?}; this project names {}",
235 available.join(", ")
236 ),
237 Some(id) => format!("no firmware for board {id:?}; no image was built"),
238 None => "no built image to push: set [build] firmware or [sim] firmware".to_string(),
239 })
240}
241
242fn resolve_workdir(
244 root: &Path,
245 default: Option<&str>,
246 step: Option<&str>,
247) -> Result<PathBuf, String> {
248 let relative = step.or(default).unwrap_or(".");
249 if relative.split(['/', '\\']).any(|part| part == "..") {
250 return Err(format!("build workdir {relative:?} escapes the project"));
251 }
252 let path = root.join(relative);
253 let path = path
254 .canonicalize()
255 .map_err(|e| format!("{}: {e}", path.display()))?;
256 if !path.starts_with(root) {
257 return Err(format!("build workdir {relative:?} escapes the project"));
258 }
259 Ok(path)
260}
261
262fn execute(
269 command: &str,
270 workdir: &Path,
271 env: &BTreeMap<&str, &str>,
272 timeout: Option<Duration>,
273 emit: &mut dyn FnMut(&str),
274) -> Result<(), String> {
275 #[cfg(windows)]
276 let mut child = {
277 let mut cmd = Command::new("cmd");
278 cmd.arg("/C").arg(command);
279 cmd
280 };
281 #[cfg(not(windows))]
282 let mut child = {
283 let mut cmd = Command::new("sh");
284 cmd.arg("-c").arg(command);
285 cmd
286 };
287 child
288 .current_dir(workdir)
289 .envs(env.iter().map(|(key, value)| (*key, *value)))
290 .stdout(Stdio::piped())
291 .stderr(Stdio::piped());
292 let mut child = child
293 .spawn()
294 .map_err(|e| format!("cannot start {command:?}: {e}"))?;
295
296 let (sender, receiver) = std::sync::mpsc::channel::<Vec<u8>>();
297 let mut pipes: Vec<Box<dyn Read + Send>> = Vec::new();
298 if let Some(stdout) = child.stdout.take() {
299 pipes.push(Box::new(stdout));
300 }
301 if let Some(stderr) = child.stderr.take() {
302 pipes.push(Box::new(stderr));
303 }
304 let mut readers = Vec::new();
305 for mut pipe in pipes {
306 let sender = sender.clone();
307 readers.push(std::thread::spawn(move || {
308 let mut buffer = [0u8; 8192];
309 loop {
310 match pipe.read(&mut buffer) {
311 Ok(0) | Err(_) => break,
312 Ok(n) => {
313 if sender.send(buffer[..n].to_vec()).is_err() {
314 break;
315 }
316 }
317 }
318 }
319 }));
320 }
321 drop(sender);
322
323 let started = Instant::now();
324 let mut pending: Vec<u8> = Vec::new();
325 let status = loop {
326 while let Ok(chunk) = receiver.recv_timeout(Duration::from_millis(10)) {
327 pending.extend_from_slice(&chunk);
328 while let Some(index) = pending.iter().position(|byte| *byte == b'\n') {
329 let line: Vec<u8> = pending.drain(..=index).collect();
330 emit(&String::from_utf8_lossy(&line));
331 }
332 }
333 match child.try_wait() {
334 Ok(Some(finished)) => break finished,
335 Ok(None) => {}
336 Err(e) => return Err(format!("waiting for {command:?}: {e}")),
337 }
338 if let Some(limit) = timeout
339 && started.elapsed() >= limit
340 {
341 let _ = child.kill();
342 let _ = child.wait();
343 for reader in readers {
344 let _ = reader.join();
345 }
346 return Err(format!(
347 "{command:?} did not finish within {} ms",
348 limit.as_millis()
349 ));
350 }
351 };
352 for reader in readers {
353 let _ = reader.join();
354 }
355 while let Ok(chunk) = receiver.try_recv() {
356 pending.extend_from_slice(&chunk);
357 }
358 if !pending.is_empty() {
359 let mut line = String::from_utf8_lossy(&pending).into_owned();
360 line.push('\n');
361 emit(&line);
362 }
363
364 if !status.success() {
365 let code = status
366 .code()
367 .map(|code| code.to_string())
368 .unwrap_or_else(|| "a signal".to_string());
369 return Err(format!("{command:?} exited with {code}"));
370 }
371 Ok(())
372}
373
374#[cfg(test)]
375mod tests {
376 use super::*;
377
378 fn scratch(tag: &str) -> PathBuf {
379 static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
380 let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
381 let dir = std::env::temp_dir().join(format!("litz-build-{}-{n}-{tag}", std::process::id()));
382 let _ = std::fs::remove_dir_all(&dir);
383 std::fs::create_dir_all(&dir).unwrap();
384 dir
385 }
386
387 #[test]
388 fn a_recipe_runs_every_step_in_order() {
389 let dir = scratch("ok");
390 std::fs::write(
391 dir.join(FILE),
392 r#"
393[build]
394firmware = "out/app.bin"
395
396[[step]]
397name = "first"
398run = "mkdir -p out && printf one > out/app.bin"
399
400[[step]]
401name = "second"
402run = "printf two >> out/app.bin"
403"#,
404 )
405 .unwrap();
406 let text = run(&dir, false).unwrap();
407 assert!(text.contains("[build 1/2] first"), "{text}");
408 assert!(text.contains("[build 2/2] second"), "{text}");
409 assert_eq!(std::fs::read(dir.join("out/app.bin")).unwrap(), b"onetwo");
410 let _ = std::fs::remove_dir_all(&dir);
411 }
412
413 #[test]
414 fn a_failing_step_stops_the_recipe() {
415 let dir = scratch("fail");
416 std::fs::write(
417 dir.join(FILE),
418 r#"
419[[step]]
420run = "printf before"
421
422[[step]]
423name = "explode"
424run = "exit 7"
425
426[[step]]
427run = "printf after"
428"#,
429 )
430 .unwrap();
431 let error = run(&dir, false).unwrap_err();
432 assert!(error.contains("explode"), "{error}");
433 assert!(error.contains("exited with 7"), "{error}");
434 let _ = std::fs::remove_dir_all(&dir);
435 }
436
437 #[test]
438 fn a_step_workdir_may_not_leave_the_project() {
439 let dir = scratch("escape");
440 std::fs::write(
441 dir.join(FILE),
442 "[[step]]\nrun = \"true\"\nworkdir = \"../\"\n",
443 )
444 .unwrap();
445 let error = run(&dir, false).unwrap_err();
446 assert!(error.contains("escapes the project"), "{error}");
447 let _ = std::fs::remove_dir_all(&dir);
448 }
449
450 #[test]
451 fn a_missing_firmware_output_is_an_error() {
452 let dir = scratch("missing");
453 std::fs::write(
454 dir.join(FILE),
455 "[build]\nfirmware = \"out/app.bin\"\n\n[[step]]\nrun = \"true\"\n",
456 )
457 .unwrap();
458 let error = run(&dir, false).unwrap_err();
459 assert!(error.contains("does not exist"), "{error}");
460 let _ = std::fs::remove_dir_all(&dir);
461 }
462
463 #[test]
464 fn a_dry_run_runs_nothing() {
465 let dir = scratch("dry");
466 std::fs::write(
467 dir.join(FILE),
468 "[[step]]\nrun = \"touch should-not-exist\"\n",
469 )
470 .unwrap();
471 let text = run(&dir, true).unwrap();
472 assert!(text.contains("$ touch should-not-exist"), "{text}");
473 assert!(!dir.join("should-not-exist").exists());
474 let _ = std::fs::remove_dir_all(&dir);
475 }
476
477 #[test]
478 fn step_environment_reaches_the_command() {
479 let dir = scratch("env");
480 std::fs::write(
481 dir.join(FILE),
482 r#"
483[build.env]
484GLOBAL = "one"
485
486[[step]]
487run = "printf \"$GLOBAL-$LOCAL\" > out.txt"
488env = { LOCAL = "two" }
489"#,
490 )
491 .unwrap();
492 run(&dir, false).unwrap();
493 assert_eq!(std::fs::read(dir.join("out.txt")).unwrap(), b"one-two");
494 let _ = std::fs::remove_dir_all(&dir);
495 }
496
497 #[test]
498 fn an_empty_recipe_is_refused() {
499 let dir = scratch("empty");
500 std::fs::write(dir.join(FILE), "[build]\n").unwrap();
501 let error = BuildConfig::load(&dir).unwrap_err();
502 assert!(error.contains("[[step]]"), "{error}");
503 let _ = std::fs::remove_dir_all(&dir);
504 }
505}