1use crate::image;
8use crate::script::{exit, Frame, Script, Step};
9use crate::tools::ToolSet;
10use serde::Serialize;
11use serde_json::{json, Value};
12use std::path::{Path, PathBuf};
13use std::time::Instant;
14
15#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
16#[serde(rename_all = "snake_case")]
17pub enum Outcome {
18 Pass,
19 ExpectationFailed,
20 ToolError,
21 Timeout,
22}
23
24#[derive(Debug, Clone, Serialize)]
25pub struct StepResult {
26 #[serde(skip_serializing_if = "Option::is_none")]
27 pub group: Option<String>,
28 #[serde(skip_serializing_if = "Option::is_none")]
29 pub expected_error: Option<bool>,
30 pub index: usize,
31 pub tool: String,
32 pub outcome: Outcome,
33 pub elapsed_ms: u128,
34 #[serde(skip_serializing_if = "Vec::is_empty")]
35 pub failures: Vec<String>,
36 #[serde(skip_serializing_if = "Option::is_none")]
37 pub image: Option<String>,
38 #[serde(skip_serializing_if = "Option::is_none")]
39 pub diff_ratio: Option<f64>,
40}
41
42#[derive(Debug, Clone, Serialize)]
44pub struct VideoResult {
45 pub out: String,
47 pub written: Vec<String>,
49 pub frames: usize,
50 pub bytes: usize,
51 pub size: [u32; 2],
53 pub duration_ms: u32,
55 pub encode_ms: u128,
57}
58
59#[derive(Debug, Clone, Serialize)]
60pub struct RunResult {
61 pub script: String,
62 pub passed: bool,
63 pub exit_code: i32,
64 pub steps: Vec<StepResult>,
65 #[serde(skip_serializing_if = "Option::is_none")]
66 pub failed_step: Option<usize>,
67 #[serde(skip_serializing_if = "Option::is_none")]
68 pub video: Option<VideoResult>,
69}
70
71pub use crate::script::{PLM_REQUEST, PLM_SERVER};
72
73pub struct RunOptions {
74 pub out_dir: PathBuf,
75 pub baselines_dir: PathBuf,
76 pub update_baselines: bool,
77 pub stop_on_fail: bool,
78 pub video_root: Option<PathBuf>,
83 pub plm: Option<std::sync::Arc<crate::plm_fixture::PlmFixture>>,
86}
87
88pub(crate) async fn stale_frames(tools: &ToolSet) -> Option<u64> {
91 let get = tools.get("state_get")?;
92 let out = (get.handler)(json!({ "names": ["__brepPerf"] })).await.ok()?;
93 out.json.get("__brepPerf")?.get("staleFrames")?.as_u64()
94}
95
96pub async fn run(script: &Script, tools: &ToolSet, opts: &RunOptions) -> RunResult {
99 let _ = std::fs::create_dir_all(&opts.out_dir);
100 let deadline = Instant::now() + std::time::Duration::from_millis(script.timeout_ms);
101 let mut steps = Vec::new();
102 let mut failed_step = None;
103 let total_frames = script.steps.iter().filter(|s| s.frame.is_some()).count();
107 let mut shots: Vec<image::GifFrame> = Vec::new();
108 let mut framed = 0usize;
113 let mut recording_failed = false;
114 let stale_before = stale_frames(tools).await;
115 for (index, step) in script.steps.iter().enumerate() {
116 if Instant::now() > deadline {
117 steps.push(StepResult {
118 group: None, expected_error: None,
119 index,
120 tool: step.tool.clone(),
121 outcome: Outcome::Timeout,
122 elapsed_ms: 0,
123 failures: vec![format!("script timeout ({} ms) reached before step {index}", script.timeout_ms)],
124 image: None,
125 diff_ratio: None,
126 });
127 failed_step = Some(index);
128 break;
129 }
130 let motion = script
144 .video
145 .as_ref()
146 .and(step.frame.as_ref())
147 .and_then(|f| f.motion.as_ref());
148 let mut capture_args = None;
149 if let (Some(video), Some(frame)) = (&script.video, &step.frame) {
150 framed += 1;
151 let recorded = match motion {
152 None => capture_frame(tools, video, frame, framed, total_frames)
153 .await
154 .map(|shot| shots.push(shot)),
155 Some(motion) => {
156 capture_args = Some(json!({ "capture": {
157 "frames": motion.frames,
158 "max_width": video.width,
159 "cursor_scale": motion.cursor_scale,
160 }}));
161 set_annotation(tools, video, frame, framed, total_frames).await
168 }
169 };
170 if let Err(why) = recorded {
171 steps.push(StepResult {
172 group: None, expected_error: None,
173 index,
174 tool: "annotate+screenshot".into(),
175 outcome: Outcome::ToolError,
176 elapsed_ms: 0,
177 failures: vec![format!("recording the walkthrough frame before step {index}: {why}")],
178 image: None,
179 diff_ratio: None,
180 });
181 recording_failed = true;
182 failed_step = Some(index);
183 break;
184 }
185 }
186 let (result, images) = run_step(index, step, tools, opts, capture_args).await;
187 if let (Some(motion), Some(frame)) = (motion, step.frame.as_ref()) {
188 if let Some(annotate) = tools.get("annotate") {
191 let _ = (annotate.handler)(json!({})).await;
192 }
193 match motion_frames(&images, frame, motion) {
194 Ok(mut filmed) => shots.append(&mut filmed),
195 Err(why) => {
196 steps.push(result);
200 steps.push(StepResult {
201 group: None, expected_error: None,
202 index,
203 tool: "annotate+screenshot".into(),
204 outcome: Outcome::ToolError,
205 elapsed_ms: 0,
206 failures: vec![format!("filming the drag at step {index}: {why}")],
207 image: None,
208 diff_ratio: None,
209 });
210 recording_failed = true;
211 failed_step = Some(index);
212 break;
213 }
214 }
215 }
216 let failed = result.outcome != Outcome::Pass;
217 steps.push(result);
218 if failed {
219 failed_step = Some(index);
220 if opts.stop_on_fail {
221 break;
222 }
223 }
224 }
225 match (stale_before, stale_frames(tools).await) {
229 (Some(before), Some(after)) => {
230 eprintln!("stale-frame check: {} {}", script.name, after - before);
231 if after > before {
232 steps.push(StepResult {
233 group: None, expected_error: None,
234 index: script.steps.len(),
235 tool: "stale-frame check".into(),
236 outcome: Outcome::ExpectationFailed,
237 elapsed_ms: 0,
238 failures: vec![format!(
239 "{} frame(s) changed what the viewport draws without a render (BREP_STALE_FRAME lines on stderr name the inputs)",
240 after - before
241 )],
242 image: None,
243 diff_ratio: None,
244 });
245 failed_step.get_or_insert(script.steps.len());
246 }
247 }
248 _ => eprintln!("stale-frame check: {} unavailable", script.name),
249 }
250 let mut video = None;
251 if let Some(spec) = &script.video {
252 if !recording_failed {
253 match write_video(spec, &shots, opts) {
254 Ok(v) => video = Some(v),
255 Err(why) => {
256 steps.push(StepResult {
257 group: None, expected_error: None,
258 index: script.steps.len(),
259 tool: "video".into(),
260 outcome: Outcome::ToolError,
261 elapsed_ms: 0,
262 failures: vec![why],
263 image: None,
264 diff_ratio: None,
265 });
266 failed_step.get_or_insert(script.steps.len());
267 }
268 }
269 }
270 }
271 let exit_code = steps
272 .iter()
273 .map(|s| match s.outcome {
274 Outcome::Pass => exit::PASS,
275 Outcome::ExpectationFailed => exit::EXPECTATION_FAILED,
276 Outcome::ToolError => exit::TOOL_ERROR,
277 Outcome::Timeout => exit::TIMEOUT,
278 })
279 .max()
280 .unwrap_or(exit::PASS);
281 let result = RunResult {
282 script: script.name.clone(),
283 passed: exit_code == exit::PASS,
284 exit_code,
285 steps,
286 failed_step,
287 video,
288 };
289 if let Ok(text) = serde_json::to_string_pretty(&result) {
290 let _ = std::fs::write(opts.out_dir.join("result.json"), text);
291 }
292 result
293}
294
295async fn capture_frame(
307 tools: &ToolSet,
308 video: &crate::script::Video,
309 frame: &Frame,
310 n: usize,
311 total: usize,
312) -> Result<image::GifFrame, String> {
313 let screenshot = tools.get("screenshot").ok_or("no `screenshot` tool in this session")?;
314 set_annotation(tools, video, frame, n, total).await?;
315 let shot = (screenshot.handler)(json!({
316 "region": "full",
317 "max_width": video.width,
318 "cursor": false
319 }))
320 .await?;
321 let png = &shot.images.first().ok_or("the screenshot tool produced no image")?.png;
322 let image = image::decode_png(png)?;
323 let annotate = tools.get("annotate").ok_or("no `annotate` tool in this session")?;
324 (annotate.handler)(json!({})).await?;
325 Ok(image::GifFrame { image, hold_ms: frame.hold_ms })
326}
327
328async fn set_annotation(
335 tools: &ToolSet,
336 video: &crate::script::Video,
337 frame: &Frame,
338 n: usize,
339 total: usize,
340) -> Result<(), String> {
341 let annotate = tools
342 .get("annotate")
343 .ok_or("no `annotate` tool in this session: a walkthrough needs a live app host")?;
344 let mut spec = json!({ "caption": frame.caption, "step": [n, total] });
345 if let Some(title) = &video.title {
346 spec["title"] = json!(title);
347 }
348 if let Some(highlight) = &frame.highlight {
349 spec["highlight"] = highlight.clone();
350 }
351 if let Some(entity) = &frame.entity {
352 spec["entity"] = entity.clone();
353 }
354 if let Some(point) = &frame.point {
355 spec["point"] = point.clone();
356 }
357 (annotate.handler)(spec).await?;
358 Ok(())
359}
360
361fn motion_frames(
373 images: &[crate::tools::ToolImage],
374 frame: &Frame,
375 motion: &crate::script::Motion,
376) -> Result<Vec<image::GifFrame>, String> {
377 let expected = motion.frames as usize + 1;
378 if images.len() != expected {
379 return Err(format!(
380 "the drag returned {} pictures, expected {expected} (the still plus {} motion frames) — does this tool take a `capture`?",
381 images.len(),
382 motion.frames
383 ));
384 }
385 images
386 .iter()
387 .enumerate()
388 .map(|(i, img)| {
389 Ok(image::GifFrame {
390 image: image::decode_png(&img.png)?,
391 hold_ms: if i == 0 { frame.hold_ms } else { motion.hold_ms },
392 })
393 })
394 .collect()
395}
396
397fn write_video(spec: &crate::script::Video, shots: &[image::GifFrame], opts: &RunOptions) -> Result<VideoResult, String> {
404 if shots.is_empty() {
405 return Err(format!(
406 "the script declares a video (`{}`) but no step carries a `frame`, so there is nothing to record",
407 spec.out
408 ));
409 }
410 let out = Path::new(&spec.out);
414 if out.is_absolute() || out.components().any(|c| matches!(c, std::path::Component::ParentDir)) {
415 return Err(format!("video.out `{}` must be a relative path with no `..`", spec.out));
416 }
417 let started = Instant::now();
418 let bytes = image::encode_gif(shots, spec.speed)?;
419 let encode_ms = started.elapsed().as_millis();
420 let name = out
421 .file_name()
422 .ok_or_else(|| format!("video.out `{}` has no file name", spec.out))?;
423 let mut written = Vec::new();
424 let local = opts.out_dir.join(name);
425 std::fs::write(&local, &bytes).map_err(|e| format!("{}: {e}", local.display()))?;
426 written.push(local.display().to_string());
427 if let Some(root) = &opts.video_root {
428 let dst = root.join(&spec.out);
429 if let Some(parent) = dst.parent() {
430 std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
431 }
432 std::fs::write(&dst, &bytes).map_err(|e| format!("{}: {e}", dst.display()))?;
433 written.push(dst.display().to_string());
434 }
435 let (w, h) = shots[0].image.dimensions();
436 Ok(VideoResult {
437 out: spec.out.clone(),
438 written,
439 frames: shots.len(),
440 bytes: bytes.len(),
441 size: [w, h],
442 duration_ms: shots.iter().map(|f| f.hold_ms).sum(),
443 encode_ms,
444 })
445}
446
447async fn run_step(
455 index: usize,
456 step: &Step,
457 tools: &ToolSet,
458 opts: &RunOptions,
459 extra_args: Option<Value>,
460) -> (StepResult, Vec<crate::tools::ToolImage>) {
461 let started = Instant::now();
462 let mut res = StepResult {
463 group: None, expected_error: None,
464 index,
465 tool: step.tool.clone(),
466 outcome: Outcome::Pass,
467 elapsed_ms: 0,
468 failures: Vec::new(),
469 image: None,
470 diff_ratio: None,
471 };
472 let step_args = if step.args.is_null() { json!({}) } else { step.args.clone() };
476 let substituted = match &opts.plm {
478 Some(plm) => plm.substitute(step_args).and_then(|args| {
479 let expect = serde_json::to_value(&step.expect).map_err(|e| e.to_string())?;
480 let expect = serde_json::from_value(plm.substitute(expect)?).map_err(|e| e.to_string())?;
481 Ok((args, expect))
482 }),
483 None => Ok((step_args, step.expect.clone())),
484 };
485 let (step_args, expects): (Value, Vec<crate::script::Expect>) = match substituted {
486 Ok(both) => both,
487 Err(e) => {
488 write_step_json(opts, index, &step.tool, &json!({ "error": e }));
489 match &step.expect_error {
490 Some(pattern) if crate::script::glob_match(pattern, &e) => {}
491 Some(pattern) => {
492 res.outcome = Outcome::ExpectationFailed;
493 res.failures.push(format!("tool failed as expected but with `{e}`, which does not match `{pattern}`"));
494 }
495 None => {
496 res.outcome = Outcome::ToolError;
497 res.failures.push(e);
498 }
499 }
500 res.elapsed_ms = started.elapsed().as_millis();
501 return (res, Vec::new());
502 }
503 };
504 if step.tool == PLM_REQUEST || step.tool == PLM_SERVER {
509 let outcome = match &opts.plm {
510 None => Err(format!("`{}` needs the script to declare `plm`", step.tool)),
511 Some(plm) if step.tool == PLM_SERVER => {
512 let plm = plm.clone();
513 let action = step_args["action"].as_str().unwrap_or_default().to_string();
514 match tokio::task::spawn_blocking(move || plm.server(&action)).await {
515 Ok(answer) => answer,
516 Err(e) => Err(e.to_string()),
517 }
518 }
519 Some(plm) => match serde_json::from_value::<crate::script::PlmCall>(step_args) {
520 Err(e) => Err(format!("plm_request arguments: {e}")),
521 Ok(call) => {
522 let plm = plm.clone();
523 match tokio::task::spawn_blocking(move || plm.call(&call).map(|a| a.to_value())).await {
524 Ok(answer) => answer,
525 Err(e) => Err(e.to_string()),
526 }
527 }
528 },
529 };
530 let output = match outcome {
531 Ok(v) => crate::tools::ToolOutput::json(v),
532 Err(e) => crate::tools::ToolOutput::json(json!({ "error": e })),
533 };
534 let failed = output.json.get("error").and_then(Value::as_str).map(str::to_string);
535 write_step_json(opts, index, &step.tool, &output.json);
536 match (failed, &step.expect_error) {
537 (Some(e), Some(pattern)) if crate::script::glob_match(pattern, &e) => {}
538 (Some(e), Some(pattern)) => {
539 res.outcome = Outcome::ExpectationFailed;
540 res.failures.push(format!("tool failed as expected but with `{e}`, which does not match `{pattern}`"));
541 }
542 (Some(e), None) => {
543 res.outcome = Outcome::ToolError;
544 res.failures.push(e);
545 }
546 (None, Some(pattern)) => {
547 res.outcome = Outcome::ExpectationFailed;
548 res.failures.push(format!("expected the tool to fail with `{pattern}` but it succeeded"));
549 }
550 (None, None) => {
551 if let (Some(plm), false) = (&opts.plm, step.bind.is_empty()) {
554 if let Err(e) = plm.bind(&output.json, &step.bind) {
555 res.failures.push(e);
556 }
557 }
558 for e in &expects {
559 if let Err(why) = e.check(&output.json) {
560 res.failures.push(why);
561 }
562 }
563 if !res.failures.is_empty() {
564 res.outcome = Outcome::ExpectationFailed;
565 }
566 }
567 }
568 res.elapsed_ms = started.elapsed().as_millis();
569 return (res, Vec::new());
570 }
571 let Some(spec) = tools.get(&step.tool) else {
572 res.outcome = Outcome::ToolError;
573 res.failures.push(format!("no tool `{}` in this session", step.tool));
574 res.elapsed_ms = started.elapsed().as_millis();
575 return (res, Vec::new());
576 };
577 let mut args = substitute_out(step_args, &opts.out_dir);
580 if let (Some(Value::Object(extra)), Value::Object(into)) = (extra_args, &mut args) {
581 into.extend(extra);
582 }
583 let limit = args.get("timeout_ms").and_then(Value::as_u64).map_or(600_000, |t| t.saturating_add(120_000));
586 let answered = match tokio::time::timeout(std::time::Duration::from_millis(limit), (spec.handler)(args)).await {
587 Ok(answered) => answered,
588 Err(_) => Err(format!("step {index} (`{}`) gave no answer within {} s", step.tool, limit / 1000)),
589 };
590 let output = match answered {
591 Ok(o) => {
592 if let Some(pattern) = &step.expect_error {
593 res.outcome = Outcome::ExpectationFailed;
594 res.failures.push(format!("expected the tool to fail with `{pattern}` but it succeeded"));
595 res.elapsed_ms = started.elapsed().as_millis();
596 write_step_json(opts, index, &step.tool, &o.json);
597 return (res, Vec::new());
598 }
599 o
600 }
601 Err(e) => {
602 write_step_json(opts, index, &step.tool, &json!({ "error": e }));
603 if let Some(pattern) = &step.expect_error {
604 if !crate::script::glob_match(pattern, &e) {
605 res.outcome = Outcome::ExpectationFailed;
606 res.failures.push(format!("tool failed as expected but with `{e}`, which does not match `{pattern}`"));
607 }
608 res.elapsed_ms = started.elapsed().as_millis();
609 return (res, Vec::new());
610 }
611 res.outcome = Outcome::ToolError;
612 res.failures.push(e);
613 res.elapsed_ms = started.elapsed().as_millis();
614 return (res, Vec::new());
615 }
616 };
617 write_step_json(opts, index, &step.tool, &output.json);
618 if !step.bind.is_empty() {
619 let bound = match &opts.plm {
620 Some(plm) => plm.bind(&output.json, &step.bind),
621 None => Err("`bind` needs the script to declare `plm`, which holds the variables".to_string()),
622 };
623 if let Err(e) = bound {
624 res.failures.push(e);
625 }
626 }
627 for e in &expects {
628 if let Err(why) = e.check(&output.json) {
629 res.failures.push(why);
630 }
631 }
632 keep_image(
633 index,
634 &step.tool,
635 output.images.first().map(|i| i.png.as_slice()),
636 step.save.as_deref(),
637 step.compare.as_ref(),
638 &opts.out_dir,
639 &opts.baselines_dir,
640 opts.update_baselines,
641 &mut res,
642 );
643 if !res.failures.is_empty() {
644 res.outcome = Outcome::ExpectationFailed;
645 }
646 res.elapsed_ms = started.elapsed().as_millis();
647 (res, output.images)
648}
649
650#[allow(clippy::too_many_arguments)]
654pub(crate) fn keep_image(
655 index: usize,
656 tool: &str,
657 png: Option<&[u8]>,
658 save: Option<&str>,
659 compare: Option<&crate::script::Compare>,
660 out_dir: &Path,
661 baselines_dir: &Path,
662 update_baselines: bool,
663 res: &mut StepResult,
664) {
665 if let Some(png) = png {
666 let name = save.map(str::to_string).unwrap_or_else(|| format!("{index:04}-{tool}.png"));
667 let path = out_dir.join(&name);
668 let _ = std::fs::write(&path, png);
669 res.image = Some(name.clone());
670 if let Some(cmp) = compare {
671 let baseline = baselines_dir.join(&cmp.baseline);
672 match (image::decode_png(png), std::fs::read(&baseline)) {
673 (Ok(actual), Ok(base_bytes)) => match image::decode_png(&base_bytes) {
674 Ok(base) => {
675 let d = image::diff(&base, &actual, 8);
676 res.diff_ratio = Some(d.ratio);
677 if d.ratio > cmp.max_diff_ratio {
678 if update_baselines {
679 let _ = std::fs::create_dir_all(baseline.parent().unwrap_or(Path::new(".")));
680 let _ = std::fs::write(&baseline, png);
681 } else {
682 let _ = std::fs::write(out_dir.join(format!("{name}.diff.png")), image::encode_png(&d.mask).unwrap_or_default());
683 res.failures.push(format!(
684 "image differs from baseline `{}` by {:.4} (max {:.4})",
685 cmp.baseline, d.ratio, cmp.max_diff_ratio
686 ));
687 }
688 }
689 }
690 Err(e) => res.failures.push(format!("baseline `{}`: {e}", cmp.baseline)),
691 },
692 (Ok(_), Err(_)) => {
693 if update_baselines {
694 let _ = std::fs::create_dir_all(baseline.parent().unwrap_or(Path::new(".")));
695 let _ = std::fs::write(&baseline, png);
696 } else {
697 res.failures.push(format!(
698 "no baseline `{}` (run with --update-baselines to create it)",
699 cmp.baseline
700 ));
701 }
702 }
703 (Err(e), _) => res.failures.push(format!("step image: {e}")),
704 }
705 }
706 } else if compare.is_some() || save.is_some() {
707 res.failures.push(format!("step {index} asked to save/compare an image but `{tool}` produced none"));
708 }
709}
710
711pub fn prepare_store(out_dir: &Path, fixtures: &[String]) -> Result<PathBuf, String> {
725 let store = out_dir.join("store");
726 if store.exists() {
727 std::fs::remove_dir_all(&store).map_err(|e| format!("clear store {}: {e}", store.display()))?;
731 }
732 std::fs::create_dir_all(&store).map_err(|e| format!("store {}: {e}", store.display()))?;
733 if !fixtures.is_empty() {
734 let models = store.join("models");
735 std::fs::create_dir_all(&models).map_err(|e| format!("store models {}: {e}", models.display()))?;
736 for fixture in fixtures {
737 let from = Path::new(fixture);
738 let name = from
739 .file_name()
740 .ok_or_else(|| format!("fixture `{fixture}` has no file name"))?;
741 std::fs::copy(from, models.join(name)).map_err(|e| format!("fixture {fixture}: {e}"))?;
742 }
743 }
744 Ok(store)
745}
746
747#[derive(Debug, Clone)]
757pub struct BootSample {
758 pub script: String,
759 pub pass: String,
761 pub state: Value,
764}
765
766pub fn order_check_failures(samples: &[BootSample]) -> Vec<String> {
778 let mut by_script: std::collections::BTreeMap<&str, Vec<&BootSample>> = std::collections::BTreeMap::new();
779 for s in samples {
780 by_script.entry(s.script.as_str()).or_default().push(s);
781 }
782 let mut failures = Vec::new();
783 for (script, group) in by_script {
784 let Some(first) = group.first() else { continue };
785 for other in group.iter().skip(1) {
786 if other.state == first.state {
787 continue;
788 }
789 let mut diffs = Vec::new();
790 diff_paths(&first.state, &other.state, "", &mut diffs);
791 if diffs.len() > 8 {
792 let rest = diffs.len() - 8;
793 diffs.truncate(8);
794 diffs.push(format!(" (+{rest} more)"));
795 }
796 failures.push(format!(
797 "{script}: the session it starts in differs between pass `{}` and pass `{}`\n{}",
798 first.pass,
799 other.pass,
800 diffs.join("\n")
801 ));
802 break;
803 }
804 }
805 failures
806}
807
808fn diff_paths(a: &Value, b: &Value, at: &str, out: &mut Vec<String>) {
810 match (a, b) {
811 (Value::Object(x), Value::Object(y)) => {
812 let mut keys: Vec<&String> = x.keys().chain(y.keys()).collect();
813 keys.sort();
814 keys.dedup();
815 for k in keys {
816 let null = Value::Null;
817 diff_paths(x.get(k).unwrap_or(&null), y.get(k).unwrap_or(&null), &format!("{at}/{k}"), out);
818 }
819 }
820 (Value::Array(x), Value::Array(y)) if x.len() == y.len() => {
821 for (i, (xi, yi)) in x.iter().zip(y).enumerate() {
822 diff_paths(xi, yi, &format!("{at}/{i}"), out);
823 }
824 }
825 _ if a != b => out.push(format!(" {at}: {a} vs {b}")),
826 _ => {}
827 }
828}
829
830pub(crate) fn substitute_out(v: Value, out: &Path) -> Value {
831 match v {
832 Value::String(s) if s.contains("${out}") => Value::String(s.replace("${out}", &out.display().to_string())),
833 Value::Array(a) => Value::Array(a.into_iter().map(|x| substitute_out(x, out)).collect()),
834 Value::Object(o) => Value::Object(o.into_iter().map(|(k, x)| (k, substitute_out(x, out))).collect()),
835 other => other,
836 }
837}
838
839pub(crate) fn write_step_json(opts: &RunOptions, index: usize, tool: &str, value: &Value) {
840 if let Ok(text) = serde_json::to_string_pretty(value) {
841 let _ = std::fs::write(opts.out_dir.join(format!("{index:04}-{tool}.json")), text);
842 }
843}
844