Skip to main content

rust_anything/
app.rs

1//! App-level record and replay for CLIs, in any language: the program is a black box.
2//!
3//! `record` runs the original on cases (the app's own examples, an inputs file, semantic traps)
4//! twice, marks what differs between the two runs as noise, and writes each case as trycmd files
5//! in `rust/app-cases/`. `replay` runs any build against those files and reports what differs.
6
7use crate::walk::Canonical;
8use std::collections::{BTreeMap, BTreeSet, HashMap};
9use std::io::{Read, Write};
10use std::path::{Component, Path, PathBuf};
11use std::process::{Command, Stdio};
12use std::sync::Mutex;
13use std::sync::atomic::{AtomicUsize, Ordering};
14use std::time::{Duration, Instant};
15
16use anyhow::{Context, Result, bail, ensure};
17use regex::Regex;
18use serde::{Deserialize, Serialize};
19use serde_json::Value;
20use toml_edit::{DocumentMut, Item, Table, value};
21
22pub const CASES_DIR: &str = "rust/app-cases";
23pub const CONFIG_FILE: &str = "rust-anything.json";
24pub const REPORT_FILE: &str = "replay-report.md";
25pub const FALLBACK_ENV: &str = "RUST_ANYTHING_FALLBACK_LOG";
26pub const BUILTIN_NORMALIZERS: [&str; 3] = ["timestamps", "uuids", "key-order"];
27pub(crate) const SCHEMA: &str = "rust-anything/app-cases@1";
28pub(crate) const MAX_TRAPS: usize = 300;
29pub(crate) const FRESH_DIR: &str = "files";
30const REMOVED_EXT: &str = "removed";
31const MAX_INPUT_FILE: u64 = 1 << 20;
32const TIMESTAMP: &str = r"\b(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{2} \d{4} \d{2}:\d{2}:\d{2} GMT[+-]\d{4}(?: \([^)\n]*\))?|\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:[.,]\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?|\b\d{2}:\d{2}:\d{2}(?:[.,]\d+)?\b";
33const UUID: &str =
34    r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b";
35
36pub(crate) const INT_TRAPS: [&str; 8] = [
37    "-7",
38    "0",
39    "-1",
40    "2147483648",
41    "9007199254740993",
42    "9223372036854775807",
43    "-9223372036854775808",
44    "18446744073709551616",
45];
46pub(crate) const FLOAT_TRAPS: [&str; 7] = [
47    "-0.0",
48    "0.1",
49    "0.30000000000000004",
50    "1e21",
51    "1e-7",
52    "5e-324",
53    "1.7976931348623157e308",
54];
55pub(crate) const STRING_TRAPS: [&str; 10] = [
56    "héllo wörld",
57    "👍🏽 thumbs",
58    "日本語",
59    "",
60    "e\u{301}",
61    "İstanbul",
62    "straße",
63    "ılık ırmak",
64    "👨\u{200D}👩\u{200D}👧 family",
65    "a\u{00A0}b",
66];
67pub(crate) const STDIN_TRAPS: [&str; 4] = [
68    "naïve café 👍🏽\nsecond line\n",
69    "",
70    "日本語 テキスト\r\nline two\r\n",
71    "  spaced   out  \n\n",
72];
73pub(crate) const JSON_TRAPS: [&str; 2] = [
74    r#"{"zebra":1,"apple":2,"10":3,"2":4,"é":5,"Apple":6}"#,
75    r#"{"n":9007199254740993,"f":1e21,"t":0.1,"neg":-7}"#,
76];
77const NOT_APP_NAMES: [&str; 29] = [
78    "node", "nodejs", "python", "python3", "py", "ruby", "java", "go", "deno", "bun", "tsx",
79    "ts-node", "sh", "bash", "zsh", "cargo", "npx", "npm", "pnpm", "yarn", "uv", "poetry",
80    "bundle", "run", "exec", "env", "sudo", "php", "dotnet",
81];
82
83/// `rust/app-cases/rust-anything.json`: how to run the original, and the normalizers.
84#[derive(Debug, Clone, Serialize, Deserialize)]
85pub struct Config {
86    pub schema: String,
87    pub name: String,
88    pub run: Vec<String>,
89    #[serde(default, skip_serializing_if = "Vec::is_empty")]
90    pub normalize: Vec<String>,
91    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
92    pub normalizers: BTreeMap<String, String>,
93    #[serde(default = "default_timeout")]
94    pub timeout_secs: u64,
95    /// Set when the app is a server: cases are requests, in `http/`.
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub http: Option<crate::http::HttpConfig>,
98    /// Numbers in the output match within this relative tolerance.
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub float_tolerance: Option<f64>,
101    /// Written files holding raw floats, by path: compared value by value (`f32le`, `f64le`).
102    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
103    pub float_files: BTreeMap<String, String>,
104    /// Outputs whose line order the original's own runs disagreed on, by case: their lines must
105    /// match in any order.
106    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
107    pub unordered: BTreeMap<String, Vec<String>>,
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub effects: Option<crate::effects::EffectsConfig>,
110    /// CLIs: repository paths copied (from the snapshot in `files/`) into the working directory
111    /// before every case; a path ending in `/` gives its contents.
112    #[serde(default, skip_serializing_if = "Vec::is_empty")]
113    pub fresh: Vec<String>,
114    /// The cases the last `app record` wrote, so the next one can remove those it no longer
115    /// writes without touching cases written by hand.
116    #[serde(default, skip_serializing_if = "Vec::is_empty")]
117    pub recorded: Vec<String>,
118}
119
120pub(crate) fn default_timeout() -> u64 {
121    30
122}
123
124impl Config {
125    pub fn load(repo: &Path) -> Result<Option<Config>> {
126        let path = cases_dir(repo).join(CONFIG_FILE);
127        if !path.exists() {
128            return Ok(None);
129        }
130        let text = std::fs::read_to_string(&path)
131            .with_context(|| format!("reading {}", path.display()))?;
132        Ok(Some(
133            serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))?,
134        ))
135    }
136}
137
138pub fn cases_dir(repo: &Path) -> PathBuf {
139    repo.join(CASES_DIR)
140}
141
142/// One line of an `--inputs` file.
143#[derive(Debug, Clone, Default, Deserialize)]
144#[serde(deny_unknown_fields)]
145pub struct Input {
146    #[serde(default)]
147    pub name: Option<String>,
148    #[serde(default)]
149    pub args: Vec<String>,
150    #[serde(default)]
151    pub stdin: Option<String>,
152    #[serde(default)]
153    pub env: BTreeMap<String, String>,
154    #[serde(default)]
155    pub files: BTreeMap<String, String>,
156    #[serde(default)]
157    pub remove: Vec<String>,
158}
159
160#[derive(Debug, Clone)]
161struct Case {
162    args: Vec<String>,
163    stdin: Option<Vec<u8>>,
164    env: BTreeMap<String, String>,
165    env_remove: Vec<String>,
166    inherit_env: bool,
167    files: BTreeMap<PathBuf, Vec<u8>>,
168    remove: Vec<PathBuf>,
169}
170
171impl Case {
172    fn new(args: Vec<String>) -> Self {
173        Case {
174            args,
175            stdin: None,
176            env: BTreeMap::new(),
177            env_remove: Vec::new(),
178            inherit_env: true,
179            files: BTreeMap::new(),
180            remove: Vec::new(),
181        }
182    }
183
184    fn key(&self) -> String {
185        serde_json::json!([self.args, self.stdin, self.env, self.files, self.remove]).to_string()
186    }
187}
188
189#[derive(Debug, Clone, PartialEq, Eq)]
190enum Status {
191    Code(i32),
192    Killed,
193    Timeout,
194}
195
196impl std::fmt::Display for Status {
197    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
198        match self {
199            Status::Code(c) => write!(f, "exit code {c}"),
200            Status::Killed => write!(f, "killed by a signal"),
201            Status::Timeout => write!(f, "timed out"),
202        }
203    }
204}
205
206struct Run {
207    stdout: Vec<u8>,
208    stderr: Vec<u8>,
209    status: Status,
210    files: BTreeMap<PathBuf, Vec<u8>>,
211    removed: Vec<PathBuf>,
212    fallback: Option<bool>,
213    effects: Option<Vec<u8>>,
214}
215
216impl Run {
217    fn written(&self, case: &Case) -> BTreeMap<PathBuf, Vec<u8>> {
218        self.files
219            .iter()
220            .filter(|(path, bytes)| case.files.get(*path) != Some(*bytes))
221            .map(|(p, b)| (p.clone(), b.clone()))
222            .collect()
223    }
224}
225
226pub(crate) struct Normalizers {
227    patterns: Vec<Regex>,
228    key_order: bool,
229    float_tolerance: Option<f64>,
230    float_files: BTreeMap<PathBuf, usize>,
231    unordered: BTreeMap<String, Vec<String>>,
232}
233
234impl Normalizers {
235    fn new(config: &Config) -> Result<Self> {
236        let mut sources: Vec<(&str, &str)> = Vec::new();
237        let mut key_order = false;
238        for name in &config.normalize {
239            match name.as_str() {
240                "timestamps" => sources.push((name, TIMESTAMP)),
241                "uuids" => sources.push((name, UUID)),
242                "key-order" => key_order = true,
243                other => bail!(
244                    "unknown normalizer `{other}`: use {} or define it as `name=regex`",
245                    BUILTIN_NORMALIZERS.join(", ")
246                ),
247            }
248        }
249        sources.extend(
250            config
251                .normalizers
252                .iter()
253                .map(|(n, p)| (n.as_str(), p.as_str())),
254        );
255        let patterns = sources
256            .iter()
257            .map(|(name, pattern)| {
258                Regex::new(pattern).with_context(|| format!("normalizer `{name}`: {pattern}"))
259            })
260            .collect::<Result<Vec<_>>>()?;
261        let float_tolerance = config
262            .float_tolerance
263            .map(crate::tolerance::check)
264            .transpose()?;
265        let float_files = config
266            .float_files
267            .iter()
268            .map(|(path, format)| Ok((PathBuf::from(path), float_width(format)?)))
269            .collect::<Result<_>>()?;
270        Ok(Normalizers {
271            patterns,
272            key_order,
273            float_tolerance,
274            float_files,
275            unordered: config.unordered.clone(),
276        })
277    }
278
279    /// Whether the original's runs disagreed on the line order of this case's `field`.
280    pub(crate) fn unordered(&self, case: &str, field: &str) -> bool {
281        self.unordered
282            .get(case)
283            .is_some_and(|fields| fields.iter().any(|f| f == field))
284    }
285
286    pub(crate) fn apply(&self, text: &str) -> String {
287        let mut out = text.to_string();
288        for p in &self.patterns {
289            out = p.replace_all(&out, "[..]").into_owned();
290        }
291        out
292    }
293
294    fn canonical(&self, text: &str) -> String {
295        if self.key_order {
296            sort_json_text(text)
297        } else {
298            text.to_string()
299        }
300    }
301}
302
303fn sort_value(v: Value) -> Value {
304    match v {
305        Value::Object(map) => {
306            let sorted: BTreeMap<String, Value> =
307                map.into_iter().map(|(k, v)| (k, sort_value(v))).collect();
308            Value::Object(sorted.into_iter().collect())
309        }
310        Value::Array(items) => Value::Array(items.into_iter().map(sort_value).collect()),
311        other => other,
312    }
313}
314
315fn sort_json_text(text: &str) -> String {
316    let trimmed = text.trim();
317    if trimmed.starts_with(['{', '['])
318        && let Ok(v) = serde_json::from_str::<Value>(trimmed)
319    {
320        return serde_json::to_string_pretty(&sort_value(v)).unwrap_or_default() + "\n";
321    }
322    text.split('\n')
323        .map(|line| {
324            let t = line.trim();
325            if t.starts_with(['{', '['])
326                && let Ok(v) = serde_json::from_str::<Value>(t)
327            {
328                return sort_value(v).to_string();
329            }
330            line.to_string()
331        })
332        .collect::<Vec<_>>()
333        .join("\n")
334}
335
336pub(crate) fn temp_dir(tag: &str) -> Result<PathBuf> {
337    static NEXT: AtomicUsize = AtomicUsize::new(0);
338    let dir = std::env::temp_dir().join(format!(
339        "rust-anything-app-{tag}-{}-{}",
340        std::process::id(),
341        NEXT.fetch_add(1, Ordering::SeqCst)
342    ));
343    let _ = std::fs::remove_dir_all(&dir);
344    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
345    Ok(dir)
346}
347
348pub(crate) fn resolve_word(repo: &Path, word: &str) -> String {
349    if word.starts_with('-') {
350        return word.to_string();
351    }
352    let path = repo.join(word);
353    let looks_like_path = word.contains('/') || word.contains('\\') || path.is_file();
354    if looks_like_path && path.exists() {
355        return path
356            .canonical()
357            .unwrap_or(path)
358            .to_string_lossy()
359            .into_owned();
360    }
361    word.to_string()
362}
363
364#[cfg(any(windows, test))]
365fn is_python_program(program: &str) -> bool {
366    Path::new(program)
367        .file_stem()
368        .and_then(|name| name.to_str())
369        .is_some_and(|name| {
370            ["python", "python3", "py"]
371                .iter()
372                .any(|candidate| name.eq_ignore_ascii_case(candidate))
373        })
374}
375
376fn run_case(
377    command: &[String],
378    repo: &Path,
379    case: &Case,
380    timeout: Duration,
381    effects: Option<&crate::effects::EffectsConfig>,
382    base: Option<&Path>,
383) -> Result<Run> {
384    let sandbox = temp_dir("run")?;
385    let result = run_in(command, repo, case, timeout, &sandbox, effects, base);
386    let _ = std::fs::remove_dir_all(&sandbox);
387    result
388}
389
390fn run_in(
391    command: &[String],
392    repo: &Path,
393    case: &Case,
394    timeout: Duration,
395    sandbox: &Path,
396    effects: Option<&crate::effects::EffectsConfig>,
397    base: Option<&Path>,
398) -> Result<Run> {
399    let work = sandbox.join("cwd");
400    std::fs::create_dir_all(&work)?;
401    if let Some(base) = base {
402        crate::http::copy_tree(base, &work)?;
403    }
404    for path in &case.remove {
405        let target = work.join(path);
406        if target.is_dir() {
407            std::fs::remove_dir_all(&target)?;
408        } else if target.exists() {
409            std::fs::remove_file(&target)?;
410        }
411    }
412    for (path, bytes) in &case.files {
413        let target = work.join(path);
414        if let Some(parent) = target.parent() {
415            std::fs::create_dir_all(parent)?;
416        }
417        std::fs::write(&target, bytes)?;
418    }
419    // The database lives where the case runs, so reset it there, before taking the snapshot that
420    // tells the case's own writes apart.
421    let sinks = effects
422        .map(|config| -> Result<_> {
423            let sinks = crate::effects::Sinks::start(config)?;
424            sinks.reset(&work, repo)?;
425            Ok(sinks)
426        })
427        .transpose()?;
428    let before: BTreeMap<PathBuf, FileStamp> = walk_files(&work)
429        .into_iter()
430        .filter_map(|path| {
431            let stamp = FileStamp::of(&path)?;
432            Some((path.strip_prefix(&work).ok()?.to_path_buf(), stamp))
433        })
434        .collect();
435    let log = sandbox.join("fallback.log");
436    let (program, rest) = command.split_first().context("empty command")?;
437    let mut cmd = Command::new(resolve_word(repo, program));
438    cmd.args(rest.iter().map(|w| resolve_word(repo, w)))
439        .args(&case.args)
440        .current_dir(&work)
441        .stdin(Stdio::piped())
442        .stdout(Stdio::piped())
443        .stderr(Stdio::piped());
444    if !case.inherit_env {
445        cmd.env_clear();
446    }
447    #[cfg(windows)]
448    if is_python_program(program)
449        && (!case.inherit_env || std::env::var_os("PYTHONIOENCODING").is_none())
450    {
451        // Python otherwise inherits the legacy Windows console code page even though its stdio
452        // is piped. UTF-8 keeps generated Unicode traps recordable; a case can still override it.
453        cmd.env("PYTHONIOENCODING", "utf-8");
454    }
455    for key in &case.env_remove {
456        cmd.env_remove(key);
457    }
458    if let Some(sinks) = &sinks {
459        cmd.envs(sinks.env());
460    }
461    cmd.envs(&case.env).env(FALLBACK_ENV, &log);
462    #[cfg(unix)]
463    {
464        use std::os::unix::process::CommandExt as _;
465        cmd.process_group(0);
466    }
467    let mut child = cmd
468        .spawn()
469        .with_context(|| format!("running `{}`", command.join(" ")))?;
470    let stdin = child.stdin.take();
471    let input = case.stdin.clone().unwrap_or_default();
472    let writer = std::thread::spawn(move || {
473        if let Some(mut pipe) = stdin {
474            let _ = pipe.write_all(&input);
475        }
476    });
477    let mut out_pipe = child.stdout.take().context("no stdout pipe")?;
478    let mut err_pipe = child.stderr.take().context("no stderr pipe")?;
479    let out_reader = std::thread::spawn(move || {
480        let mut buf = Vec::new();
481        let _ = out_pipe.read_to_end(&mut buf);
482        buf
483    });
484    let err_reader = std::thread::spawn(move || {
485        let mut buf = Vec::new();
486        let _ = err_pipe.read_to_end(&mut buf);
487        buf
488    });
489    let start = Instant::now();
490    let status = loop {
491        if let Some(s) = child.try_wait()? {
492            #[cfg(unix)]
493            let pipes_done =
494                writer.is_finished() && out_reader.is_finished() && err_reader.is_finished();
495            #[cfg(not(unix))]
496            let pipes_done = true;
497            if pipes_done {
498                break s.code().map_or(Status::Killed, Status::Code);
499            }
500        }
501        if start.elapsed() > timeout {
502            #[cfg(unix)]
503            {
504                let _ = Command::new("/bin/kill")
505                    .args(["-KILL", "--", &format!("-{}", child.id())])
506                    .stderr(Stdio::null())
507                    .status();
508            }
509            let _ = child.kill();
510            let _ = child.wait();
511            break Status::Timeout;
512        }
513        std::thread::sleep(Duration::from_millis(2));
514    };
515    let _ = writer.join();
516    let stdout = out_reader.join().unwrap_or_default();
517    let stderr = err_reader.join().unwrap_or_default();
518
519    let mut cwd_forms = vec![work.to_string_lossy().into_owned()];
520    if let Ok(real) = work.canonical() {
521        cwd_forms.insert(0, real.to_string_lossy().into_owned());
522    }
523    let redact = |bytes: Vec<u8>| -> Vec<u8> {
524        match String::from_utf8(bytes) {
525            Ok(mut text) => {
526                for form in &cwd_forms {
527                    text = text.replace(form.as_str(), "[CWD]");
528                }
529                text.into_bytes()
530            }
531            Err(e) => e.into_bytes(),
532        }
533    };
534    let mut files = BTreeMap::new();
535    let mut present = BTreeSet::new();
536    for path in walk_files(&work) {
537        let rel = path.strip_prefix(&work).unwrap_or(&path).to_path_buf();
538        present.insert(rel.clone());
539        let stamp = before.get(&rel);
540        if stamp.is_some() && stamp == FileStamp::of(&path).as_ref() {
541            continue;
542        }
543        let bytes = std::fs::read(&path).unwrap_or_default();
544        if stamp.is_some()
545            && !case.files.contains_key(&rel)
546            && let Some(base) = base
547            && std::fs::read(base.join(&rel)).is_ok_and(|b| b == bytes)
548        {
549            continue;
550        }
551        files.insert(rel, redact(bytes));
552    }
553    let removed = before
554        .keys()
555        .filter(|rel| !present.contains(*rel))
556        .cloned()
557        .collect();
558    let fallback = std::fs::metadata(&log).ok().map(|m| m.len() > 0);
559    let effects = sinks.map(|s| redact(s.take(&work, repo)));
560    Ok(Run {
561        stdout: redact(stdout),
562        stderr: redact(stderr),
563        status,
564        files,
565        removed,
566        fallback,
567        effects,
568    })
569}
570
571#[derive(PartialEq, Eq)]
572struct FileStamp {
573    len: u64,
574    modified: Option<std::time::SystemTime>,
575}
576
577impl FileStamp {
578    fn of(path: &Path) -> Option<Self> {
579        let meta = std::fs::metadata(path).ok()?;
580        Some(FileStamp {
581            len: meta.len(),
582            modified: meta.modified().ok(),
583        })
584    }
585}
586
587fn walk_files(root: &Path) -> Vec<PathBuf> {
588    let mut out = Vec::new();
589    let mut stack = vec![root.to_path_buf()];
590    while let Some(dir) = stack.pop() {
591        let Ok(entries) = std::fs::read_dir(&dir) else {
592            continue;
593        };
594        for entry in entries.flatten() {
595            let Ok(kind) = entry.file_type() else {
596                continue;
597            };
598            if kind.is_dir() {
599                stack.push(entry.path());
600            } else if kind.is_file() {
601                out.push(entry.path());
602            }
603        }
604    }
605    out.sort();
606    out
607}
608
609fn par_map<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> R + Sync) -> Vec<R> {
610    let threads = std::thread::available_parallelism()
611        .map_or(4, |n| n.get())
612        .clamp(1, 8);
613    let next = AtomicUsize::new(0);
614    let results: Vec<Mutex<Option<R>>> = items.iter().map(|_| Mutex::new(None)).collect();
615    std::thread::scope(|s| {
616        for _ in 0..threads {
617            s.spawn(|| {
618                loop {
619                    let i = next.fetch_add(1, Ordering::SeqCst);
620                    let Some(item) = items.get(i) else { break };
621                    let r = f(item);
622                    if let Ok(mut slot) = results[i].lock() {
623                        *slot = Some(r);
624                    }
625                }
626            });
627        }
628    });
629    results
630        .into_iter()
631        .filter_map(|m| m.into_inner().ok().flatten())
632        .collect()
633}
634
635#[derive(Debug, Clone, PartialEq, Eq)]
636pub(crate) struct Tok {
637    pub(crate) text: String,
638    pub(crate) op: bool,
639}
640
641pub(crate) fn shell_tokens(line: &str) -> Option<Vec<Tok>> {
642    let mut toks = Vec::new();
643    let mut cur = String::new();
644    let mut in_tok = false;
645    let mut chars = line.chars().peekable();
646    let flush = |toks: &mut Vec<Tok>, cur: &mut String, in_tok: &mut bool| {
647        if *in_tok {
648            toks.push(Tok {
649                text: std::mem::take(cur),
650                op: false,
651            });
652            *in_tok = false;
653        }
654    };
655    while let Some(c) = chars.next() {
656        match c {
657            ' ' | '\t' => flush(&mut toks, &mut cur, &mut in_tok),
658            '\'' => {
659                in_tok = true;
660                loop {
661                    match chars.next()? {
662                        '\'' => break,
663                        x => cur.push(x),
664                    }
665                }
666            }
667            '"' => {
668                in_tok = true;
669                loop {
670                    match chars.next()? {
671                        '"' => break,
672                        '\\' => match chars.next()? {
673                            x @ ('"' | '\\' | '$' | '`') => cur.push(x),
674                            x => {
675                                cur.push('\\');
676                                cur.push(x);
677                            }
678                        },
679                        '`' => return None,
680                        '$' if chars.peek() == Some(&'(') => return None,
681                        x => cur.push(x),
682                    }
683                }
684            }
685            '\\' => {
686                in_tok = true;
687                let mut following = chars.clone();
688                let next = following.next();
689                let after_next = following.next();
690                let escaped_substitution = next == Some('$') && after_next == Some('(');
691                let unc_prefix = cur.is_empty()
692                    && next == Some('\\')
693                    && after_next
694                        .is_some_and(|c| !c.is_whitespace() && !"'\"\\|<>&;$`".contains(c));
695                if cfg!(windows)
696                    && (unc_prefix
697                        || (!escaped_substitution
698                            && !chars
699                                .peek()
700                                .is_some_and(|c| c.is_whitespace() || "'\"\\|<>&;`".contains(*c))))
701                {
702                    cur.push('\\');
703                } else if let Some(x) = chars.next() {
704                    cur.push(x);
705                }
706            }
707            '|' | '<' | '>' | ';' | '&' => {
708                flush(&mut toks, &mut cur, &mut in_tok);
709                let mut op = c.to_string();
710                while let Some(&n) = chars.peek() {
711                    if !"|<>&".contains(n) {
712                        break;
713                    }
714                    op.push(n);
715                    chars.next();
716                }
717                toks.push(Tok { text: op, op: true });
718            }
719            '#' if !in_tok => break,
720            '`' => return None,
721            '$' if chars.peek() == Some(&'(') => return None,
722            _ => {
723                in_tok = true;
724                cur.push(c);
725            }
726        }
727    }
728    flush(&mut toks, &mut cur, &mut in_tok);
729    Some(toks)
730}
731
732/// Splits a command line into words, shell-style quoting, no shell operators.
733pub fn shell_split(line: &str) -> Result<Vec<String>> {
734    let toks = shell_tokens(line).with_context(|| format!("cannot split `{line}`"))?;
735    if let Some(op) = toks.iter().find(|t| t.op) {
736        bail!(
737            "`{line}` uses the shell operator `{}`: put the pipeline in a script and give its path",
738            op.text
739        );
740    }
741    Ok(toks.into_iter().map(|t| t.text).collect())
742}
743
744pub(crate) fn shell_quote(word: &str) -> String {
745    let plain = !word.is_empty()
746        && word
747            .chars()
748            .all(|c| c.is_alphanumeric() || "-_./=:,+@%".contains(c));
749    if plain {
750        word.to_string()
751    } else {
752        format!("'{}'", word.replace('\'', r"'\''"))
753    }
754}
755
756fn lines(text: &str) -> Vec<&str> {
757    let text = text.strip_suffix('\n').unwrap_or(text);
758    if text.is_empty() {
759        return Vec::new();
760    }
761    text.split('\n')
762        .map(|l| l.strip_suffix('\r').unwrap_or(l))
763        .collect()
764}
765
766#[derive(Debug, Clone, Copy, PartialEq, Eq)]
767enum Op {
768    Equal(usize, usize),
769    Delete(usize),
770    Insert(usize),
771}
772
773fn diff_ops<A, B>(a: &[A], b: &[B], eq: impl Fn(&A, &B) -> bool) -> Vec<Op> {
774    let mut head = 0;
775    while head < a.len() && head < b.len() && eq(&a[head], &b[head]) {
776        head += 1;
777    }
778    let mut tail = 0;
779    while tail < a.len() - head
780        && tail < b.len() - head
781        && eq(&a[a.len() - 1 - tail], &b[b.len() - 1 - tail])
782    {
783        tail += 1;
784    }
785    let (am, bm) = (&a[head..a.len() - tail], &b[head..b.len() - tail]);
786    let mut ops: Vec<Op> = (0..head).map(|i| Op::Equal(i, i)).collect();
787    let (n, m) = (am.len(), bm.len());
788    if n * m <= 4_000_000 {
789        let mut lcs = vec![vec![0u32; m + 1]; n + 1];
790        for i in (0..n).rev() {
791            for j in (0..m).rev() {
792                lcs[i][j] = if eq(&am[i], &bm[j]) {
793                    lcs[i + 1][j + 1] + 1
794                } else {
795                    lcs[i + 1][j].max(lcs[i][j + 1])
796                };
797            }
798        }
799        let (mut i, mut j) = (0, 0);
800        while i < n || j < m {
801            if i < n && j < m && eq(&am[i], &bm[j]) {
802                ops.push(Op::Equal(head + i, head + j));
803                i += 1;
804                j += 1;
805            } else if i < n && (j == m || lcs[i + 1][j] >= lcs[i][j + 1]) {
806                ops.push(Op::Delete(head + i));
807                i += 1;
808            } else {
809                ops.push(Op::Insert(head + j));
810                j += 1;
811            }
812        }
813    } else {
814        ops.extend((0..n).map(|i| Op::Delete(head + i)));
815        ops.extend((0..m).map(|j| Op::Insert(head + j)));
816    }
817    ops.extend((0..tail).map(|k| Op::Equal(a.len() - tail + k, b.len() - tail + k)));
818    ops
819}
820
821pub(crate) fn line_matches(expected: &str, actual: &str) -> bool {
822    if !expected.contains("[..]") {
823        return expected == actual;
824    }
825    let parts: Vec<&str> = expected.split("[..]").collect();
826    let (first, last) = (parts[0], parts[parts.len() - 1]);
827    let Some(rest) = actual.strip_prefix(first) else {
828        return false;
829    };
830    let Some(mut rest) = rest.strip_suffix(last) else {
831        return false;
832    };
833    for mid in &parts[1..parts.len() - 1] {
834        match rest.find(mid) {
835            Some(i) => rest = &rest[i + mid.len()..],
836            None => return false,
837        }
838    }
839    true
840}
841
842/// Whether a line can match a line it is not equal to: `[..]` stands for any text, and with a
843/// tolerance a number can meet a nearby number. Any other line matches its own text and nothing
844/// else, so comparing the sorted sides already settles those.
845fn can_match_beyond_its_text(line: &str, tol: Option<f64>) -> bool {
846    line.contains("[..]") || (tol.is_some() && line.bytes().any(|b| b.is_ascii_digit()))
847}
848
849/// Expected lines against actual lines in any order: every expected line paired with a distinct
850/// actual line. Sorting both sides and pairing by position cannot do this once a line matches
851/// more than its own text, because no order agrees with a match that is not transitive -- `10.0`
852/// has to meet `9.999999999999999` while sorting before `2.0`. So identical lines are paired off
853/// first, and the lines that are left get a search that gives a line up when another line needs
854/// it.
855fn lines_match_in_any_order(expected: &[&str], actual: &[&str], tol: Option<f64>) -> bool {
856    if expected.len() != actual.len() {
857        return false;
858    }
859    let (mut sorted_e, mut sorted_a) = (expected.to_vec(), actual.to_vec());
860    sorted_e.sort_unstable();
861    sorted_a.sort_unstable();
862    if sorted_e == sorted_a {
863        return true;
864    }
865    if !expected.iter().any(|l| can_match_beyond_its_text(l, tol)) {
866        return false;
867    }
868    let mut spare: HashMap<&str, usize> = HashMap::new();
869    for line in actual {
870        *spare.entry(*line).or_default() += 1;
871    }
872    let mut rest_expected = Vec::new();
873    for line in expected {
874        match spare.get_mut(line) {
875            Some(count) if *count > 0 => *count -= 1,
876            _ => rest_expected.push(*line),
877        }
878    }
879    let rest_actual: Vec<&str> = spare
880        .into_iter()
881        .flat_map(|(line, count)| std::iter::repeat_n(line, count))
882        .collect();
883    let mut holder: Vec<Option<usize>> = vec![None; rest_actual.len()];
884    for want in 0..rest_expected.len() {
885        let mut tried = vec![false; rest_actual.len()];
886        if !take_a_line(
887            want,
888            &rest_expected,
889            &rest_actual,
890            tol,
891            &mut tried,
892            &mut holder,
893        ) {
894            return false;
895        }
896    }
897    true
898}
899
900/// One augmenting step: find a line for `want`, moving the expected lines that already hold one
901/// along to another line they also match.
902fn take_a_line(
903    want: usize,
904    expected: &[&str],
905    actual: &[&str],
906    tol: Option<f64>,
907    tried: &mut [bool],
908    holder: &mut [Option<usize>],
909) -> bool {
910    for i in 0..actual.len() {
911        if tried[i] || !line_matches_within(expected[want], actual[i], tol) {
912            continue;
913        }
914        tried[i] = true;
915        if holder[i].is_none_or(|held| take_a_line(held, expected, actual, tol, tried, holder)) {
916            holder[i] = Some(want);
917            return true;
918        }
919    }
920    false
921}
922
923/// A line within the float tolerance, for lines without wildcards.
924fn line_matches_within(expected: &str, actual: &str, tol: Option<f64>) -> bool {
925    line_matches(expected, actual)
926        || tol.is_some_and(|t| {
927            !expected.contains("[..]") && crate::tolerance::line_close(expected, actual, t)
928        })
929}
930
931/// trycmd's matching: `[..]` is any text within a line, a `...` line is any number of lines.
932fn text_matches(expected: &str, actual: &str, tol: Option<f64>) -> bool {
933    let (e, a) = (lines(expected), lines(actual));
934    let m = a.len();
935    let mut next = vec![false; m + 1];
936    next[m] = true;
937    for line in e.iter().rev() {
938        let mut cur = vec![false; m + 1];
939        for j in (0..=m).rev() {
940            cur[j] = if *line == "..." {
941                next[j] || (j < m && cur[j + 1])
942            } else {
943                j < m && line_matches_within(line, a[j], tol) && next[j + 1]
944            };
945        }
946        next = cur;
947    }
948    next[0]
949}
950
951fn render_diff(expected: &str, actual: &str, tol: Option<f64>) -> String {
952    let (e, a) = (lines(expected), lines(actual));
953    let ops = diff_ops(&e, &a, |x, y| line_matches_within(x, y, tol));
954    let changed: Vec<bool> = ops.iter().map(|op| !matches!(op, Op::Equal(..))).collect();
955    let near = |k: usize| {
956        let lo = k.saturating_sub(3);
957        let hi = (k + 4).min(ops.len());
958        changed[lo..hi].iter().any(|c| *c)
959    };
960    let mut out = String::new();
961    let mut skipped = false;
962    for (k, op) in ops.iter().enumerate() {
963        match op {
964            Op::Equal(_, j) if near(k) => {
965                skipped = false;
966                out += &format!("  {}\n", a[*j]);
967            }
968            Op::Equal(..) => {
969                if !skipped {
970                    out += "  ⋮\n";
971                    skipped = true;
972                }
973            }
974            Op::Delete(i) => {
975                skipped = false;
976                out += &format!("- {}\n", e[*i]);
977            }
978            Op::Insert(j) => {
979                skipped = false;
980                out += &format!("+ {}\n", a[*j]);
981            }
982        }
983    }
984    let trail = |s: &str| s.ends_with('\n') || s.is_empty();
985    if out.is_empty() || trail(expected) != trail(actual) {
986        out += &format!(
987            "(trailing newline: expected {}, got {})\n",
988            trail(expected),
989            trail(actual)
990        );
991    }
992    out
993}
994
995fn tokens(line: &str) -> Vec<&str> {
996    let mut out = Vec::new();
997    let mut start = None;
998    for (i, c) in line.char_indices() {
999        if c.is_alphanumeric() {
1000            start.get_or_insert(i);
1001        } else {
1002            if let Some(s) = start.take() {
1003                out.push(&line[s..i]);
1004            }
1005            out.push(&line[i..i + c.len_utf8()]);
1006        }
1007    }
1008    if let Some(s) = start {
1009        out.push(&line[s..]);
1010    }
1011    out
1012}
1013
1014pub(crate) fn merge_line(a: &str, b: &str) -> String {
1015    let (ta, tb) = (tokens(a), tokens(b));
1016    if ta.len() != tb.len() {
1017        return "[..]".to_string();
1018    }
1019    let mut out = String::new();
1020    for (x, y) in ta.iter().zip(&tb) {
1021        if x == y {
1022            out += x;
1023        } else if !out.ends_with("[..]") {
1024            out += "[..]";
1025        }
1026    }
1027    out
1028}
1029
1030/// Two runs of the original: what they agree on stays, what differs becomes a wildcard.
1031fn merge_noise(a: &str, b: &str) -> String {
1032    if a == b {
1033        return a.to_string();
1034    }
1035    let (la, lb): (Vec<&str>, Vec<&str>) = (a.split('\n').collect(), b.split('\n').collect());
1036    let ops = diff_ops(&la, &lb, |x, y| x == y);
1037    let mut out: Vec<String> = Vec::new();
1038    let (mut dels, mut ins): (Vec<&str>, Vec<&str>) = (Vec::new(), Vec::new());
1039    let flush = |out: &mut Vec<String>, dels: &mut Vec<&str>, ins: &mut Vec<&str>| {
1040        if dels.is_empty() && ins.is_empty() {
1041            return;
1042        }
1043        if dels.len() == ins.len() {
1044            for (x, y) in dels.iter().zip(ins.iter()) {
1045                out.push(merge_line(x, y));
1046            }
1047        } else if out.last().map(String::as_str) != Some("...") {
1048            out.push("...".to_string());
1049        }
1050        dels.clear();
1051        ins.clear();
1052    };
1053    for op in ops {
1054        match op {
1055            Op::Equal(i, _) => {
1056                flush(&mut out, &mut dels, &mut ins);
1057                out.push(la[i].to_string());
1058            }
1059            Op::Delete(i) => dels.push(la[i]),
1060            Op::Insert(j) => ins.push(lb[j]),
1061        }
1062    }
1063    flush(&mut out, &mut dels, &mut ins);
1064    out.join("\n")
1065}
1066
1067fn stem(word: &str) -> String {
1068    Path::new(word)
1069        .file_stem()
1070        .map(|s| s.to_string_lossy().to_lowercase())
1071        .unwrap_or_default()
1072}
1073
1074/// Names the app is invoked by, most specific first.
1075fn app_names(repo: &Path, run: &[String], explicit: Option<&str>) -> Vec<String> {
1076    let mut names: Vec<String> = Vec::new();
1077    let mut add = |name: &str| {
1078        let name = name.rsplit('/').next().unwrap_or(name).to_lowercase();
1079        if !name.is_empty() && !NOT_APP_NAMES.contains(&name.as_str()) && !names.contains(&name) {
1080            names.push(name);
1081        }
1082    };
1083    if let Some(name) = explicit {
1084        add(name);
1085    }
1086    for word in run {
1087        let path = repo.join(word);
1088        if word.starts_with('-') || path.is_dir() || Path::new(word).is_dir() {
1089            continue;
1090        }
1091        add(&stem(word));
1092    }
1093    if let Ok(text) = std::fs::read_to_string(repo.join("package.json"))
1094        && let Ok(pkg) = serde_json::from_str::<Value>(&text)
1095    {
1096        match &pkg["bin"] {
1097            Value::String(_) => add(pkg["name"].as_str().unwrap_or_default()),
1098            Value::Object(map) => map.keys().for_each(|k| add(k)),
1099            _ => {}
1100        }
1101    }
1102    if let Ok(text) = std::fs::read_to_string(repo.join("pyproject.toml"))
1103        && let Ok(doc) = text.parse::<DocumentMut>()
1104    {
1105        for table in [
1106            doc.get("project").and_then(|p| p.get("scripts")),
1107            doc.get("tool")
1108                .and_then(|t| t.get("poetry"))
1109                .and_then(|p| p.get("scripts")),
1110        ]
1111        .into_iter()
1112        .flatten()
1113        {
1114            if let Some(t) = table.as_table_like() {
1115                t.iter().for_each(|(k, _)| add(k));
1116            }
1117        }
1118    }
1119    for (dir, dirs_only) in [("cmd", true), ("bin", false), ("exe", false)] {
1120        let Ok(entries) = std::fs::read_dir(repo.join(dir)) else {
1121            continue;
1122        };
1123        let mut found: Vec<String> = entries
1124            .flatten()
1125            .filter(|e| e.file_type().is_ok_and(|t| t.is_dir() == dirs_only))
1126            .map(|e| stem(&e.file_name().to_string_lossy()))
1127            .collect();
1128        found.sort();
1129        found.iter().for_each(|n| add(n));
1130    }
1131    names
1132}
1133
1134fn safe_relative(arg: &str) -> bool {
1135    let p = Path::new(arg);
1136    !arg.is_empty()
1137        && !arg.starts_with('-')
1138        && p.components().all(|c| matches!(c, Component::Normal(_)))
1139}
1140
1141fn read_input_file(candidates: &[PathBuf]) -> Option<Vec<u8>> {
1142    candidates
1143        .iter()
1144        .find(|p| p.is_file() && std::fs::metadata(p).is_ok_and(|m| m.len() <= MAX_INPUT_FILE))
1145        .and_then(|p| std::fs::read(p).ok())
1146}
1147
1148fn parse_example(line: &str, names: &[String], repo: &Path, doc_dir: &Path) -> Option<Case> {
1149    let toks = shell_tokens(line)?;
1150    let ops: Vec<usize> = (0..toks.len()).filter(|&i| toks[i].op).collect();
1151    let words = |range: &[Tok]| -> Vec<String> { range.iter().map(|t| t.text.clone()).collect() };
1152    let lookup = |arg: &str| -> Option<Vec<u8>> {
1153        if !safe_relative(arg) {
1154            return None;
1155        }
1156        read_input_file(&[repo.join(arg), doc_dir.join(arg)])
1157    };
1158    let (main, stdin): (Vec<String>, Option<Vec<u8>>) = match ops.as_slice() {
1159        [] => (words(&toks), None),
1160        [i] if toks[*i].text == "|" => {
1161            let feed = words(&toks[..*i]);
1162            let stdin = match feed.first().map(String::as_str) {
1163                Some("echo") => {
1164                    let newline = feed.get(1).map(String::as_str) != Some("-n");
1165                    let text: Vec<&str> = feed[1..]
1166                        .iter()
1167                        .map(String::as_str)
1168                        .filter(|w| !matches!(*w, "-n" | "-e"))
1169                        .collect();
1170                    let mut text = text.join(" ");
1171                    if newline {
1172                        text.push('\n');
1173                    }
1174                    text.into_bytes()
1175                }
1176                Some("printf") if feed.len() == 2 => feed[1]
1177                    .replace("\\n", "\n")
1178                    .replace("\\t", "\t")
1179                    .into_bytes(),
1180                Some("cat") if feed.len() == 2 => lookup(&feed[1])?,
1181                _ => return None,
1182            };
1183            (words(&toks[*i + 1..]), Some(stdin))
1184        }
1185        [i] if toks[*i].text == "<" && *i + 2 == toks.len() => {
1186            (words(&toks[..*i]), Some(lookup(&toks[*i + 1].text)?))
1187        }
1188        _ => return None,
1189    };
1190    let mut env = BTreeMap::new();
1191    let mut rest = main.as_slice();
1192    while let Some((first, tail)) = rest.split_first() {
1193        let Some((k, v)) = first.split_once('=') else {
1194            break;
1195        };
1196        if k.is_empty() || !k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
1197            break;
1198        }
1199        env.insert(k.to_string(), v.to_string());
1200        rest = tail;
1201    }
1202    let (prog, args) = rest.split_first()?;
1203    if !names.contains(&stem(prog)) {
1204        return None;
1205    }
1206    let mut case = Case::new(args.to_vec());
1207    case.env = env;
1208    case.stdin = stdin;
1209    for arg in args {
1210        if let Some(bytes) = lookup(arg) {
1211            case.files.insert(PathBuf::from(arg), bytes);
1212        }
1213    }
1214    Some(case)
1215}
1216
1217fn find_examples(repo: &Path, names: &[String]) -> Vec<Case> {
1218    if names.is_empty() {
1219        return Vec::new();
1220    }
1221    scan_examples(repo, |line, doc_dir| {
1222        parse_example(line, names, repo, doc_dir)
1223    })
1224}
1225
1226/// Shell lines in the repository's Markdown code blocks and `.sh` files, each given to `parse`
1227/// with the folder of the file it came from.
1228pub(crate) fn scan_examples<T>(repo: &Path, parse: impl Fn(&str, &Path) -> Option<T>) -> Vec<T> {
1229    let skip = ["node_modules", "target", "vendor", ".git"];
1230    let walker = crate::walk::filtered(repo, move |e| {
1231        let name = e.file_name().to_string_lossy();
1232        !skip.contains(&name.as_ref())
1233    })
1234    .max_depth(Some(4))
1235    .sort_by_file_name(|a, b| a.cmp(b))
1236    .build();
1237    let rust_dir = repo.join("rust");
1238    let mut out = Vec::new();
1239    for entry in walker.flatten() {
1240        let path = entry.path();
1241        if path.starts_with(&rust_dir) || !path.is_file() {
1242            continue;
1243        }
1244        let ext = path
1245            .extension()
1246            .map(|e| e.to_string_lossy().to_lowercase())
1247            .unwrap_or_default();
1248        let markdown = matches!(ext.as_str(), "md" | "markdown");
1249        if !markdown && ext != "sh" {
1250            continue;
1251        }
1252        let Ok(text) = std::fs::read_to_string(path) else {
1253            continue;
1254        };
1255        let doc_dir = path.parent().unwrap_or(repo);
1256        let mut fence: Option<String> = None;
1257        // A command wrapped with trailing backslashes, joined so far.
1258        let mut pending = String::new();
1259        for raw in text.lines() {
1260            let line = raw.trim();
1261            let candidate = if markdown {
1262                if line.starts_with("```") || line.starts_with("~~~") {
1263                    pending.clear();
1264                    fence = match fence {
1265                        Some(_) => None,
1266                        None => Some(
1267                            line.trim_start_matches(['`', '~'])
1268                                .split_whitespace()
1269                                .next()
1270                                .unwrap_or_default()
1271                                .to_lowercase(),
1272                        ),
1273                    };
1274                    continue;
1275                }
1276                let Some(lang) = &fence else { continue };
1277                // Continuation lines carry no `$ ` prompt, and keep their indentation: it is what
1278                // separates them from the previous word, as the shell adds no space when joining.
1279                if !pending.is_empty() {
1280                    raw
1281                } else {
1282                    let start = raw.trim_start();
1283                    match start.strip_prefix("$ ") {
1284                        Some(rest) => rest,
1285                        None if matches!(lang.as_str(), "sh" | "bash" | "shell" | "zsh") => start,
1286                        None => continue,
1287                    }
1288                }
1289            } else if !pending.is_empty() {
1290                raw
1291            } else {
1292                let start = raw.trim_start();
1293                start.strip_prefix("$ ").unwrap_or(start)
1294            };
1295            // The line's end is untrimmed, so `\ ` (an escaped space) does not continue.
1296            if !ends_in_comment(candidate)
1297                && let Some(head) = continued(candidate)
1298            {
1299                pending.push_str(head);
1300                continue;
1301            }
1302            pending.push_str(candidate);
1303            let command = std::mem::take(&mut pending);
1304            if let Some(case) = parse(&command, doc_dir) {
1305                out.push(case);
1306            }
1307        }
1308    }
1309    out
1310}
1311
1312/// Whether a shell line ends inside a comment: an unquoted `#` that starts a word. A `\` at the
1313/// end of a comment is part of the comment, not a continuation.
1314fn ends_in_comment(line: &str) -> bool {
1315    let (mut single, mut double, mut escaped, mut word_start) = (false, false, false, true);
1316    for c in line.chars() {
1317        if escaped {
1318            escaped = false;
1319            word_start = false;
1320            continue;
1321        }
1322        match c {
1323            '\\' if !single => escaped = true,
1324            '\'' if !double => single = !single,
1325            '"' if !single => double = !double,
1326            '#' if word_start && !single && !double => return true,
1327            _ => {}
1328        }
1329        word_start = c.is_whitespace() && !single && !double;
1330    }
1331    false
1332}
1333
1334/// The line without its trailing `\` when the shell would join it with the next line. An even
1335/// number of trailing backslashes ends in a literal one (`C:\\`), not a continuation.
1336fn continued(line: &str) -> Option<&str> {
1337    let head = line.strip_suffix('\\')?;
1338    let escaped = (head.len() - head.trim_end_matches('\\').len()) % 2 == 1;
1339    (!escaped).then_some(head)
1340}
1341
1342fn read_inputs(path: &Path) -> Result<Vec<(Option<String>, Case)>> {
1343    let text =
1344        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
1345    let mut out = Vec::new();
1346    for (n, line) in text.lines().enumerate() {
1347        if line.trim().is_empty() {
1348            continue;
1349        }
1350        let input: Input = serde_json::from_str(line)
1351            .with_context(|| format!("{}:{}: expected {{\"args\": [...], \"stdin\": ..., \"env\": {{...}}, \"files\": {{path: text}}}}", path.display(), n + 1))?;
1352        let mut case = Case::new(input.args);
1353        case.stdin = input.stdin.map(String::into_bytes);
1354        case.env = input.env;
1355        for (file, content) in input.files {
1356            ensure!(
1357                safe_relative(&file),
1358                "{}:{}: file `{file}` must be a relative path inside the sandbox",
1359                path.display(),
1360                n + 1
1361            );
1362            case.files.insert(PathBuf::from(file), content.into_bytes());
1363        }
1364        for file in input.remove {
1365            ensure!(
1366                safe_relative(&file),
1367                "{}:{}: removed `{file}` must be a relative path inside the sandbox",
1368                path.display(),
1369                n + 1
1370            );
1371            case.remove.push(PathBuf::from(file));
1372        }
1373        out.push((input.name, case));
1374    }
1375    Ok(out)
1376}
1377
1378pub(crate) fn is_word(arg: &str) -> bool {
1379    let mut chars = arg.chars();
1380    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
1381        && chars.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
1382}
1383
1384fn trap_cases(bases: &[Case]) -> Vec<Case> {
1385    let mut out = Vec::new();
1386    for base in bases {
1387        for (i, arg) in base.args.iter().enumerate() {
1388            if i == 0 && is_word(arg) {
1389                continue;
1390            }
1391            let number = arg.parse::<f64>().is_ok();
1392            if arg.starts_with('-') && !number {
1393                continue;
1394            }
1395            let values: Vec<&str> = if arg.parse::<i128>().is_ok() {
1396                INT_TRAPS.to_vec()
1397            } else if number && arg.contains(['.', 'e', 'E']) {
1398                FLOAT_TRAPS.to_vec()
1399            } else if base.files.contains_key(Path::new(arg)) {
1400                vec!["missing-input.txt"]
1401            } else {
1402                STRING_TRAPS.to_vec()
1403            };
1404            for v in values.into_iter().filter(|v| v != arg) {
1405                let mut case = base.clone();
1406                case.args[i] = v.to_string();
1407                out.push(case);
1408            }
1409        }
1410        if let Some(stdin) = &base.stdin {
1411            let json = std::str::from_utf8(stdin)
1412                .ok()
1413                .and_then(|t| serde_json::from_str::<Value>(t).ok())
1414                .is_some_and(|v| v.is_object() || v.is_array());
1415            let values: &[&str] = if json { &JSON_TRAPS } else { &STDIN_TRAPS };
1416            for v in values {
1417                let mut case = base.clone();
1418                case.stdin = Some(v.as_bytes().to_vec());
1419                out.push(case);
1420            }
1421        }
1422    }
1423    out.truncate(MAX_TRAPS);
1424    out
1425}
1426
1427pub(crate) fn slug(text: &str) -> String {
1428    slug_max(text, 24)
1429}
1430
1431/// A case name the user gave in `--inputs`: longer than a generated one, so names that differ
1432/// only past the 24th character stay apart.
1433pub(crate) fn given_slug(text: &str) -> String {
1434    slug_max(text, 96)
1435}
1436
1437fn slug_max(text: &str, max: usize) -> String {
1438    let mut out = String::new();
1439    for c in text.chars() {
1440        if c.is_ascii_alphanumeric() {
1441            out.push(c.to_ascii_lowercase());
1442        } else if !out.ends_with('-') && !out.is_empty() {
1443            out.push('-');
1444        }
1445    }
1446    out.truncate(max);
1447    out.trim_end_matches('-').to_string()
1448}
1449
1450pub struct RecordOptions<'a> {
1451    pub repo: &'a Path,
1452    /// The command that runs the original; taken from the saved config when empty.
1453    pub run: &'a [String],
1454    pub inputs: Option<&'a Path>,
1455    /// Built-in normalizer names, or `name=regex` for your own.
1456    pub normalize: &'a [String],
1457    pub name: Option<&'a str>,
1458    pub traps: bool,
1459    pub timeout_secs: Option<u64>,
1460    /// The app is a server: record requests instead of command lines.
1461    pub http: bool,
1462    /// The port a server always listens on (implies `http`); unset, it gets a free one through
1463    /// `PORT` and `{port}`.
1464    pub port: Option<u16>,
1465    /// Servers: arguments every start gets after its command, the original's and every build's
1466    /// (implies `http`); kept from the last recording when empty.
1467    pub server_args: &'a [String],
1468    /// Servers: repository files or folders copied into a fresh working directory before every
1469    /// start (implies `http`); kept from the last recording when empty.
1470    pub fresh: &'a [String],
1471    /// Servers: milliseconds to wait after each response, for work the server does after
1472    /// answering (a file watcher, a write-behind); kept from the last recording when `None`.
1473    pub pace_ms: Option<u64>,
1474    /// Numbers in the output match within this tolerance; kept from the last recording when
1475    /// `None`, removed with 0.
1476    pub float_tolerance: Option<f64>,
1477    /// Written files of raw floats, `path=f32le` or `path=f64le`; kept from the last recording
1478    /// when empty.
1479    pub float_files: &'a [String],
1480    pub effects: Option<crate::effects::EffectsConfig>,
1481}
1482
1483#[derive(Debug, Serialize)]
1484pub struct RecordOutcome {
1485    pub dir: PathBuf,
1486    pub run: Vec<String>,
1487    pub cases: usize,
1488    pub examples: usize,
1489    pub inputs: usize,
1490    pub traps: usize,
1491    /// Cases where the two runs of the original differed.
1492    pub noisy: Vec<String>,
1493    /// What differed in each noisy case, and how: `values` became wildcards, `order` is compared
1494    /// in any order, `lines` became a `...` that matches anything.
1495    pub noise: Vec<Noise>,
1496    /// Cases whose exit code or written files differed between the two runs.
1497    pub unstable: Vec<String>,
1498    /// Cases not written: the original timed out or did not answer.
1499    pub timed_out: Vec<String>,
1500    /// The cases this recording wrote.
1501    pub recorded: Vec<String>,
1502    /// Cases the last recording in this folder wrote and this one did not (a timeout included):
1503    /// removed, apart from files a case that stays reads (`fs.base`).
1504    pub stale: Vec<String>,
1505    /// Cases in the folder that no recording wrote (by hand, or before the list was kept):
1506    /// left in place.
1507    pub kept: Vec<String>,
1508}
1509
1510/// What each case's files are called after its name.
1511const CASE_FILES: [&str; 9] = [
1512    "toml",
1513    "stdin",
1514    "stdout",
1515    "stderr",
1516    REMOVED_EXT,
1517    crate::effects::EXT,
1518    "body",
1519    "in",
1520    "out",
1521];
1522
1523/// Removes the cases the last recording in this folder wrote (`previous`) that this one did not
1524/// write, and names the cases in the folder that did not come from a recording, which it keeps.
1525/// Only `previous` marks a case as a recording's: a case written by hand stays even when an input
1526/// of its name timed out now. Files a case that stays reads through `fs.base` (that folder, or one
1527/// inside it) stay too.
1528pub(crate) fn drop_stale(outcome: &mut RecordOutcome, previous: &[String]) -> Result<()> {
1529    let written: BTreeSet<&str> = outcome.recorded.iter().map(String::as_str).collect();
1530    let ours: BTreeSet<&str> = previous
1531        .iter()
1532        .map(String::as_str)
1533        .filter(|name| !written.contains(name))
1534        .collect();
1535    let read = bases_read(&outcome.dir, &ours);
1536    let mut stale = Vec::new();
1537    for name in &ours {
1538        if outcome.dir.join(format!("{name}.toml")).is_file() {
1539            stale.push((*name).to_string());
1540        }
1541        for ext in CASE_FILES {
1542            let path = outcome.dir.join(format!("{name}.{ext}"));
1543            // A folder a case that stays reads, holds one it reads, or is on the way to it as
1544            // written: `two.in/sub`, `../app-cases/two.in/sub` (resolved) and `two.in/../shared`
1545            // (on Unix only found while `two.in` exists) all keep `two.in`.
1546            let resolved = path.canonicalize().ok();
1547            if read.iter().any(|base| {
1548                base.starts_with(&path) || resolved.as_ref().is_some_and(|r| base.starts_with(r))
1549            }) {
1550                continue;
1551            }
1552            if path.is_dir() {
1553                std::fs::remove_dir_all(&path)
1554                    .with_context(|| format!("removing {}", path.display()))?;
1555            } else if path.is_file() {
1556                std::fs::remove_file(&path)
1557                    .with_context(|| format!("removing {}", path.display()))?;
1558            }
1559        }
1560    }
1561    let mut kept: Vec<String> = std::fs::read_dir(&outcome.dir)?
1562        .flatten()
1563        .filter_map(|entry| {
1564            let name = entry.file_name().to_string_lossy().into_owned();
1565            name.strip_suffix(".toml").map(str::to_string)
1566        })
1567        .filter(|name| !written.contains(name.as_str()))
1568        .collect();
1569    kept.sort();
1570    outcome.stale = stale;
1571    outcome.kept = kept;
1572    Ok(())
1573}
1574
1575/// The `fs.base` folders that the cases in `dir` other than `going` read, each as written (joined
1576/// to `dir`) and, when it exists, resolved.
1577fn bases_read(dir: &Path, going: &BTreeSet<&str>) -> BTreeSet<PathBuf> {
1578    let Ok(entries) = std::fs::read_dir(dir) else {
1579        return BTreeSet::new();
1580    };
1581    entries
1582        .flatten()
1583        .map(|entry| entry.path())
1584        .filter(|path| {
1585            path.extension().is_some_and(|e| e == "toml")
1586                && path
1587                    .file_stem()
1588                    .and_then(|s| s.to_str())
1589                    .is_some_and(|stem| !going.contains(stem))
1590        })
1591        .filter_map(|path| std::fs::read_to_string(path).ok())
1592        .filter_map(|text| text.parse::<DocumentMut>().ok())
1593        .filter_map(|doc| {
1594            doc.get("fs")
1595                .and_then(|f| f.get("base"))
1596                .and_then(Item::as_str)
1597                .map(|base| dir.join(base))
1598        })
1599        .flat_map(|base| {
1600            let resolved = base.canonicalize().ok();
1601            std::iter::once(base).chain(resolved)
1602        })
1603        .collect()
1604}
1605
1606struct Recorded {
1607    stdout: Vec<u8>,
1608    stderr: Vec<u8>,
1609    effects: Option<Vec<u8>>,
1610    status: Status,
1611    written: BTreeMap<PathBuf, Vec<u8>>,
1612    removed: Vec<PathBuf>,
1613    binary: bool,
1614    noise: Vec<(String, NoiseKind)>,
1615    unstable: bool,
1616}
1617
1618/// How two runs of the original disagreed.
1619#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1620#[serde(rename_all = "lowercase")]
1621pub enum NoiseKind {
1622    /// Values within lines changed (times, ids): those parts are wildcards now.
1623    Values,
1624    /// The same lines came out in another order (hash maps, concurrency): replay compares them
1625    /// in any order, and a port must produce exactly those lines.
1626    Order,
1627    /// A different number of lines came out: that stretch is a `...` wildcard, which matches
1628    /// anything. Look at these first.
1629    Lines,
1630}
1631
1632#[derive(Debug, Clone, Serialize)]
1633pub struct Noise {
1634    pub case: String,
1635    pub field: String,
1636    pub kind: NoiseKind,
1637}
1638
1639fn same_lines_any_order(a: &str, b: &str) -> bool {
1640    let (mut la, mut lb) = (lines(a), lines(b));
1641    la.sort_unstable();
1642    lb.sort_unstable();
1643    la == lb
1644}
1645
1646pub(crate) fn settle_text(
1647    norm: &Normalizers,
1648    a: &[u8],
1649    b: &[u8],
1650) -> (Vec<u8>, Option<NoiseKind>, bool) {
1651    match (std::str::from_utf8(a), std::str::from_utf8(b)) {
1652        (Ok(a), Ok(b)) => {
1653            let (a, b) = (norm.apply(a), norm.apply(b));
1654            if a == b || (norm.key_order && norm.canonical(&a) == norm.canonical(&b)) {
1655                (a.into_bytes(), None, false)
1656            } else if same_lines_any_order(&a, &b) {
1657                (a.into_bytes(), Some(NoiseKind::Order), false)
1658            } else {
1659                let merged = merge_noise(&a, &b);
1660                let kind = if merged.split('\n').any(|l| l == "...") {
1661                    NoiseKind::Lines
1662                } else {
1663                    NoiseKind::Values
1664                };
1665                (merged.into_bytes(), Some(kind), false)
1666            }
1667        }
1668        _ => (a.to_vec(), (a != b).then_some(NoiseKind::Values), true),
1669    }
1670}
1671
1672fn settle(norm: &Normalizers, case: &Case, one: &Run, two: &Run) -> Recorded {
1673    let binary = [&one.stdout, &one.stderr, &two.stdout, &two.stderr]
1674        .iter()
1675        .any(|bytes| std::str::from_utf8(bytes).is_err());
1676    let settle_stream = |a: &[u8], b: &[u8]| {
1677        if binary {
1678            (a.to_vec(), (a != b).then_some(NoiseKind::Values))
1679        } else {
1680            let (bytes, noise, _) = settle_text(norm, a, b);
1681            (bytes, noise)
1682        }
1683    };
1684    let (stdout, out_noise) = settle_stream(&one.stdout, &two.stdout);
1685    let (stderr, err_noise) = settle_stream(&one.stderr, &two.stderr);
1686    let (effects, fx_noise) = match (&one.effects, &two.effects) {
1687        (Some(a), Some(b)) => {
1688            let (bytes, noise, _) = settle_text(norm, a, b);
1689            (Some(bytes), noise)
1690        }
1691        _ => (None, None),
1692    };
1693    let (w1, w2) = (one.written(case), two.written(case));
1694    let mut unstable = one.status != two.status
1695        || one.removed != two.removed
1696        || !w1.keys().eq(w2.keys())
1697        || (binary && (out_noise.is_some() || err_noise.is_some()));
1698    let mut noise: Vec<(String, NoiseKind)> = [
1699        ("stdout", out_noise),
1700        ("stderr", err_noise),
1701        (crate::effects::EXT, fx_noise),
1702    ]
1703    .into_iter()
1704    .filter_map(|(f, k)| Some((f.to_string(), k?)))
1705    .collect();
1706    let mut written = BTreeMap::new();
1707    for (path, a) in &w1 {
1708        let b = w2.get(path).unwrap_or(a);
1709        let (bytes, file_noise, file_bin) = settle_text(norm, a, b);
1710        unstable |= file_bin && file_noise.is_some();
1711        if let Some(kind) = file_noise {
1712            noise.push((format!("file {}", path.display()), kind));
1713        }
1714        written.insert(path.clone(), bytes);
1715    }
1716    Recorded {
1717        stdout,
1718        stderr,
1719        effects,
1720        status: one.status.clone(),
1721        written,
1722        removed: one.removed.clone(),
1723        binary,
1724        noise,
1725        unstable,
1726    }
1727}
1728
1729fn dotted() -> Table {
1730    let mut t = Table::new();
1731    t.set_dotted(true);
1732    t
1733}
1734
1735fn write_case(dir: &Path, bin: &str, name: &str, case: &Case, rec: &Recorded) -> Result<()> {
1736    for ext in [
1737        "stdin",
1738        "stdout",
1739        "stderr",
1740        REMOVED_EXT,
1741        crate::effects::EXT,
1742    ] {
1743        let _ = std::fs::remove_file(dir.join(format!("{name}.{ext}")));
1744    }
1745    for ext in ["in", "out"] {
1746        let _ = std::fs::remove_dir_all(dir.join(format!("{name}.{ext}")));
1747    }
1748    let mut doc = DocumentMut::new();
1749    let mut bin_t = dotted();
1750    bin_t["name"] = value(bin);
1751    doc["bin"] = Item::Table(bin_t);
1752    let mut args = toml_edit::Array::new();
1753    for a in &case.args {
1754        args.push(a.as_str());
1755    }
1756    doc["args"] = value(args);
1757    if !case.env.is_empty() {
1758        let mut add = dotted();
1759        for (k, v) in &case.env {
1760            add[k.as_str()] = value(v.as_str());
1761        }
1762        let mut env = dotted();
1763        env.insert("add", Item::Table(add));
1764        doc["env"] = Item::Table(env);
1765    }
1766    match rec.status {
1767        Status::Code(code) => {
1768            let mut status = dotted();
1769            status["code"] = value(i64::from(code));
1770            doc["status"] = Item::Table(status);
1771        }
1772        _ => doc["status"] = value("interrupted"),
1773    }
1774    let mut fs = dotted();
1775    fs["sandbox"] = value(true);
1776    if !case.files.is_empty() {
1777        fs["base"] = value(format!("{name}.in"));
1778    }
1779    if !case.remove.is_empty() {
1780        let mut remove = toml_edit::Array::new();
1781        for path in &case.remove {
1782            remove.push(path.to_string_lossy().as_ref());
1783        }
1784        fs["remove"] = value(remove);
1785    }
1786    doc["fs"] = Item::Table(fs);
1787    if rec.binary {
1788        doc["binary"] = value(true);
1789    }
1790    std::fs::write(dir.join(format!("{name}.toml")), doc.to_string())?;
1791    if let Some(stdin) = &case.stdin {
1792        std::fs::write(dir.join(format!("{name}.stdin")), stdin)?;
1793    }
1794    std::fs::write(dir.join(format!("{name}.stdout")), &rec.stdout)?;
1795    std::fs::write(dir.join(format!("{name}.stderr")), &rec.stderr)?;
1796    if !rec.removed.is_empty() {
1797        let list: String = rec
1798            .removed
1799            .iter()
1800            .map(|p| format!("{}\n", p.display()))
1801            .collect();
1802        std::fs::write(dir.join(format!("{name}.{REMOVED_EXT}")), list)?;
1803    }
1804    if let Some(effects) = &rec.effects {
1805        std::fs::write(dir.join(format!("{name}.{}", crate::effects::EXT)), effects)?;
1806    }
1807    for (sub, files) in [("in", &case.files), ("out", &rec.written)] {
1808        for (path, bytes) in files {
1809            let target = dir.join(format!("{name}.{sub}")).join(path);
1810            if let Some(parent) = target.parent() {
1811                std::fs::create_dir_all(parent)?;
1812            }
1813            std::fs::write(&target, bytes)?;
1814        }
1815    }
1816    Ok(())
1817}
1818
1819pub(crate) fn reserve_case_name(
1820    taken: &mut BTreeSet<String>,
1821    base: String,
1822    mut suffix: usize,
1823) -> String {
1824    let mut name = base.clone();
1825    while !taken.insert(name.clone()) {
1826        name = format!("{base}-{suffix}");
1827        suffix += 1;
1828    }
1829    name
1830}
1831
1832pub fn record(opts: &RecordOptions) -> Result<RecordOutcome> {
1833    let repo = opts
1834        .repo
1835        .canonical()
1836        .with_context(|| format!("no folder {}", opts.repo.display()))?;
1837    let existing = Config::load(&repo)?;
1838    // The names the last recording wrote, and whether it wrote them to `http/` or to the CLI
1839    // folder: they are a recording's only in that folder.
1840    let (previous, previous_http) = existing
1841        .as_ref()
1842        .map(|c| (c.recorded.clone(), c.http.is_some()))
1843        .unwrap_or_default();
1844    let run = if !opts.run.is_empty() {
1845        opts.run.to_vec()
1846    } else if let Some(c) = &existing {
1847        c.run.clone()
1848    } else {
1849        bail!(
1850            "give the command that runs the original after `--`, e.g. `rust-anything app record . -- python3 cli.py`"
1851        );
1852    };
1853    let mut normalize = existing
1854        .as_ref()
1855        .map(|c| c.normalize.clone())
1856        .unwrap_or_default();
1857    let mut normalizers = existing
1858        .as_ref()
1859        .map(|c| c.normalizers.clone())
1860        .unwrap_or_default();
1861    for n in opts.normalize {
1862        if let Some((name, pattern)) = n.split_once('=') {
1863            normalizers.insert(name.to_string(), pattern.to_string());
1864        } else if !normalize.contains(n) {
1865            normalize.push(n.clone());
1866        }
1867    }
1868    let explicit = opts
1869        .name
1870        .map(str::to_string)
1871        .or_else(|| existing.as_ref().map(|c| c.name.clone()));
1872    let names = app_names(&repo, &run, explicit.as_deref());
1873    let mut config = Config {
1874        schema: SCHEMA.to_string(),
1875        name: explicit
1876            .or_else(|| names.first().cloned())
1877            .unwrap_or_else(|| "app".to_string()),
1878        run,
1879        normalize,
1880        normalizers,
1881        timeout_secs: opts
1882            .timeout_secs
1883            .or(existing.as_ref().map(|c| c.timeout_secs))
1884            .unwrap_or_else(default_timeout),
1885        http: crate::http::merge_config(existing.as_ref().and_then(|c| c.http.clone()), opts),
1886        float_tolerance: match opts.float_tolerance {
1887            Some(t) => (crate::tolerance::check(t)? > 0.0).then_some(t),
1888            None => existing.as_ref().and_then(|c| c.float_tolerance),
1889        },
1890        float_files: if opts.float_files.is_empty() {
1891            existing
1892                .as_ref()
1893                .map(|c| c.float_files.clone())
1894                .unwrap_or_default()
1895        } else {
1896            opts.float_files
1897                .iter()
1898                .map(|spec| {
1899                    let (path, format) = spec.rsplit_once('=').with_context(|| {
1900                        format!("--float-file `{spec}`: use PATH=f32le or PATH=f64le")
1901                    })?;
1902                    float_width(format)?;
1903                    Ok((path.to_string(), format.to_string()))
1904                })
1905                .collect::<Result<_>>()?
1906        },
1907        unordered: BTreeMap::new(),
1908        effects: crate::effects::EffectsConfig::merge(
1909            existing.as_ref().and_then(|c| c.effects.clone()),
1910            opts.effects.clone(),
1911        ),
1912        fresh: Vec::new(),
1913        recorded: Vec::new(),
1914    };
1915    if let Some(http) = config.http.as_mut() {
1916        if !opts.fresh.is_empty() {
1917            http.fresh = opts.fresh.to_vec();
1918        }
1919    } else if !opts.fresh.is_empty() {
1920        config.fresh = opts.fresh.to_vec();
1921    } else if let Some(c) = &existing {
1922        config.fresh = c.fresh.clone();
1923    }
1924    let norm = Normalizers::new(&config)?;
1925    if config.http.is_some() {
1926        let mut outcome = crate::http::record(&repo, &config, &norm, opts)?;
1927        config.unordered = unordered_of(&outcome.noise);
1928        drop_stale(&mut outcome, if previous_http { &previous } else { &[] })?;
1929        config.recorded = outcome.recorded.clone();
1930        std::fs::write(
1931            cases_dir(&repo).join(CONFIG_FILE),
1932            serde_json::to_string_pretty(&config)? + "\n",
1933        )?;
1934        return Ok(outcome);
1935    }
1936
1937    let examples = find_examples(&repo, &names);
1938    let inputs = match opts.inputs {
1939        Some(path) => read_inputs(path)?,
1940        None => Vec::new(),
1941    };
1942    let mut planned: Vec<(String, Case)> = Vec::new();
1943    let mut seen = BTreeSet::new();
1944    let mut taken = BTreeSet::new();
1945    let mut push = |prefix: &str, n: usize, given: Option<String>, case: Case| {
1946        if !seen.insert(case.key()) {
1947            return false;
1948        }
1949        let base_name = match given {
1950            Some(g) if !given_slug(&g).is_empty() => given_slug(&g),
1951            _ => match case.args.first().map(|a| slug(a)).filter(|s| !s.is_empty()) {
1952                Some(s) => format!("{prefix}-{n:03}-{s}"),
1953                None => format!("{prefix}-{n:03}"),
1954            },
1955        };
1956        let name = reserve_case_name(&mut taken, base_name, n);
1957        planned.push((name, case));
1958        true
1959    };
1960    let mut bases = Vec::new();
1961    let mut counts = [0usize; 3];
1962    for case in examples {
1963        if push("example", counts[0] + 1, None, case.clone()) {
1964            counts[0] += 1;
1965            bases.push(case);
1966        }
1967    }
1968    for (given, case) in inputs {
1969        if push("input", counts[1] + 1, given, case.clone()) {
1970            counts[1] += 1;
1971            bases.push(case);
1972        }
1973    }
1974    if bases.is_empty() {
1975        let case = Case::new(Vec::new());
1976        push("example", 1, Some("no-args".to_string()), case.clone());
1977        bases.push(case);
1978    }
1979    if opts.traps {
1980        for case in trap_cases(&bases) {
1981            if push("trap", counts[2] + 1, None, case) {
1982                counts[2] += 1;
1983            }
1984        }
1985    }
1986
1987    let timeout = Duration::from_secs(config.timeout_secs);
1988    let effects = config.effects.as_ref();
1989    let base = crate::http::snapshot_to(&repo, &config.fresh, &cases_dir(&repo).join(FRESH_DIR))?;
1990    let base = base.as_deref();
1991    let run_twice = |(_, case): &(String, Case)| -> Result<(Run, Run)> {
1992        let one = run_case(&config.run, &repo, case, timeout, effects, base)?;
1993        let two = run_case(&config.run, &repo, case, timeout, effects, base)?;
1994        Ok((one, two))
1995    };
1996    let runs = if effects.is_some_and(crate::effects::EffectsConfig::serial) {
1997        planned.iter().map(run_twice).collect()
1998    } else {
1999        par_map(&planned, run_twice)
2000    };
2001    let dir = cases_dir(&repo);
2002    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
2003    let mut outcome = RecordOutcome {
2004        dir: dir.clone(),
2005        run: config.run.clone(),
2006        cases: 0,
2007        examples: counts[0],
2008        inputs: counts[1],
2009        traps: counts[2],
2010        noisy: Vec::new(),
2011        noise: Vec::new(),
2012        unstable: Vec::new(),
2013        timed_out: Vec::new(),
2014        recorded: Vec::new(),
2015        stale: Vec::new(),
2016        kept: Vec::new(),
2017    };
2018    for ((name, case), runs) in planned.iter().zip(runs) {
2019        let (one, two) = runs?;
2020        if one.status == Status::Timeout || two.status == Status::Timeout {
2021            outcome.timed_out.push(name.clone());
2022            continue;
2023        }
2024        let rec = settle(&norm, case, &one, &two);
2025        write_case(&dir, &config.name, name, case, &rec)?;
2026        outcome.cases += 1;
2027        outcome.recorded.push(name.clone());
2028        if !rec.noise.is_empty() {
2029            outcome.noisy.push(name.clone());
2030        }
2031        outcome
2032            .noise
2033            .extend(rec.noise.iter().map(|(field, kind)| Noise {
2034                case: name.clone(),
2035                field: field.clone(),
2036                kind: *kind,
2037            }));
2038        if rec.unstable {
2039            outcome.unstable.push(name.clone());
2040        }
2041    }
2042    config.unordered = unordered_of(&outcome.noise);
2043    drop_stale(&mut outcome, if previous_http { &[] } else { &previous })?;
2044    config.recorded = outcome.recorded.clone();
2045    std::fs::write(
2046        dir.join(CONFIG_FILE),
2047        serde_json::to_string_pretty(&config)? + "\n",
2048    )?;
2049    Ok(outcome)
2050}
2051
2052fn unordered_of(noise: &[Noise]) -> BTreeMap<String, Vec<String>> {
2053    let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new();
2054    for n in noise.iter().filter(|n| n.kind == NoiseKind::Order) {
2055        out.entry(n.case.clone()).or_default().push(n.field.clone());
2056    }
2057    out
2058}
2059
2060enum Expect {
2061    Code(i32),
2062    Failed,
2063    Killed,
2064    Skip,
2065}
2066
2067struct Spec {
2068    name: String,
2069    case: Case,
2070    stdout: Option<Vec<u8>>,
2071    stderr: Option<Vec<u8>>,
2072    effects: Option<Vec<u8>>,
2073    status: Expect,
2074    out_dir: Option<PathBuf>,
2075    removed: Option<Vec<PathBuf>>,
2076    binary: bool,
2077}
2078
2079fn read_files(base: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
2080    walk_files(base)
2081        .into_iter()
2082        .map(|p| {
2083            let rel = p.strip_prefix(base).unwrap_or(&p).to_path_buf();
2084            let bytes = std::fs::read(&p).unwrap_or_default();
2085            (rel, bytes)
2086        })
2087        .collect()
2088}
2089
2090fn load_spec(dir: &Path, path: &Path) -> Result<Spec> {
2091    let name = path
2092        .file_stem()
2093        .map(|s| s.to_string_lossy().into_owned())
2094        .unwrap_or_default();
2095    let text =
2096        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
2097    let doc: DocumentMut = text
2098        .parse()
2099        .with_context(|| format!("parsing {}", path.display()))?;
2100    let args = match doc.get("args") {
2101        Some(item) if item.as_array().is_some() => item
2102            .as_array()
2103            .into_iter()
2104            .flatten()
2105            .map(|v| {
2106                v.as_str()
2107                    .map(str::to_string)
2108                    .unwrap_or_else(|| v.to_string())
2109            })
2110            .collect(),
2111        Some(item) => shell_split(item.as_str().unwrap_or_default())?,
2112        None => Vec::new(),
2113    };
2114    let mut case = Case::new(args);
2115    let side = |key: &str| -> Result<Option<Vec<u8>>> {
2116        if let Some(s) = doc.get(key).and_then(Item::as_str) {
2117            return Ok(Some(s.as_bytes().to_vec()));
2118        }
2119        let file = dir.join(format!("{name}.{key}"));
2120        Ok(if file.exists() {
2121            Some(std::fs::read(&file).with_context(|| format!("reading {}", file.display()))?)
2122        } else {
2123            None
2124        })
2125    };
2126    case.stdin = side("stdin")?;
2127    if let Some(env) = doc.get("env") {
2128        case.inherit_env = env.get("inherit").and_then(Item::as_bool).unwrap_or(true);
2129        if let Some(add) = env.get("add").and_then(Item::as_table_like) {
2130            for (k, v) in add.iter() {
2131                case.env
2132                    .insert(k.to_string(), v.as_str().unwrap_or_default().to_string());
2133            }
2134        }
2135        if let Some(remove) = env.get("remove").and_then(Item::as_array) {
2136            case.env_remove = remove
2137                .iter()
2138                .filter_map(|v| v.as_str().map(str::to_string))
2139                .collect();
2140        }
2141    }
2142    let base = doc
2143        .get("fs")
2144        .and_then(|f| f.get("base"))
2145        .and_then(Item::as_str)
2146        .map(|b| dir.join(b))
2147        .unwrap_or_else(|| dir.join(format!("{name}.in")));
2148    if base.is_dir() {
2149        case.files = read_files(&base);
2150    }
2151    if let Some(remove) = doc
2152        .get("fs")
2153        .and_then(|f| f.get("remove"))
2154        .and_then(Item::as_array)
2155    {
2156        case.remove = remove
2157            .iter()
2158            .filter_map(|v| v.as_str().map(PathBuf::from))
2159            .collect();
2160    }
2161    let status = match doc.get("status") {
2162        None => Expect::Code(0),
2163        Some(item) => match (item.as_str(), item.get("code").and_then(Item::as_integer)) {
2164            (Some("success"), _) => Expect::Code(0),
2165            (Some("failed"), _) => Expect::Failed,
2166            (Some("interrupted"), _) => Expect::Killed,
2167            (Some("skipped"), _) => Expect::Skip,
2168            (_, Some(code)) => Expect::Code(i32::try_from(code).unwrap_or(i32::MAX)),
2169            _ => bail!("{}: unknown `status`", path.display()),
2170        },
2171    };
2172    let out_dir = dir.join(format!("{name}.out"));
2173    Ok(Spec {
2174        stdout: side("stdout")?,
2175        stderr: side("stderr")?,
2176        effects: side(crate::effects::EXT)?,
2177        status,
2178        out_dir: out_dir.is_dir().then_some(out_dir),
2179        removed: side(REMOVED_EXT)?.map(|bytes| {
2180            String::from_utf8_lossy(&bytes)
2181                .lines()
2182                .filter(|l| !l.is_empty())
2183                .map(PathBuf::from)
2184                .collect()
2185        }),
2186        binary: doc.get("binary").and_then(Item::as_bool).unwrap_or(false),
2187        name,
2188        case,
2189    })
2190}
2191
2192fn float_width(format: &str) -> Result<usize> {
2193    match format {
2194        "f32le" => Ok(4),
2195        "f64le" => Ok(8),
2196        other => bail!("float file format `{other}`: use f32le or f64le"),
2197    }
2198}
2199
2200fn floats(bytes: &[u8], width: usize) -> Vec<f64> {
2201    bytes
2202        .chunks_exact(width)
2203        .map(|c| match c.try_into() {
2204            Ok(b) if width == 4 => f64::from(f32::from_le_bytes(b)),
2205            _ => c.try_into().map_or(f64::NAN, f64::from_le_bytes),
2206        })
2207        .collect()
2208}
2209
2210fn compare_floats(
2211    expected: &[u8],
2212    actual: &[u8],
2213    width: usize,
2214    tol: Option<f64>,
2215) -> Option<String> {
2216    if !expected.len().is_multiple_of(width) || expected.len() != actual.len() {
2217        return Some(format!(
2218            "{} values expected, {} bytes got ({} bytes per value)\n",
2219            expected.len() / width,
2220            actual.len(),
2221            width
2222        ));
2223    }
2224    let (e, a) = (floats(expected, width), floats(actual, width));
2225    let tol = tol.unwrap_or(0.0);
2226    let same =
2227        |x: f64, y: f64| x == y || (x.is_nan() && y.is_nan()) || crate::tolerance::near(x, y, tol);
2228    let off: Vec<usize> = (0..e.len()).filter(|&i| !same(e[i], a[i])).collect();
2229    let first = *off.first()?;
2230    let (mut abs, mut rel) = (0.0f64, 0.0f64);
2231    for &i in &off {
2232        let d = (e[i] - a[i]).abs();
2233        abs = abs.max(d);
2234        rel = rel.max(d / e[i].abs().max(a[i].abs()).max(f64::MIN_POSITIVE));
2235    }
2236    Some(format!(
2237        "{} of {} values differ beyond the tolerance ({tol}); first at index {first}: {} expected, {} got; max abs diff {abs:e}, max rel diff {rel:e}\n",
2238        off.len(),
2239        e.len(),
2240        e[first],
2241        a[first]
2242    ))
2243}
2244
2245pub(crate) fn compare(
2246    norm: &Normalizers,
2247    expected: &[u8],
2248    actual: &[u8],
2249    binary: bool,
2250    unordered: bool,
2251) -> Option<String> {
2252    if !binary && let (Ok(e), Ok(a)) = (std::str::from_utf8(expected), std::str::from_utf8(actual))
2253    {
2254        let e = norm.canonical(&norm.apply(e));
2255        let a = norm.canonical(&norm.apply(a));
2256        let tol = norm.float_tolerance;
2257        if unordered {
2258            let (mut el, mut al) = (lines(&e), lines(&a));
2259            let same = lines_match_in_any_order(&el, &al, tol);
2260            el.sort_unstable();
2261            al.sort_unstable();
2262            return (!same).then(|| {
2263                format!(
2264                    "(lines compared in any order: the original's own runs disagreed on it)\n{}",
2265                    render_diff(&el.join("\n"), &al.join("\n"), tol)
2266                )
2267            });
2268        }
2269        return (!text_matches(&e, &a, tol)).then(|| render_diff(&e, &a, tol));
2270    }
2271    (expected != actual).then(|| {
2272        format!(
2273            "binary content differs ({} bytes expected, {} bytes got)\n",
2274            expected.len(),
2275            actual.len()
2276        )
2277    })
2278}
2279
2280pub struct ReplayOptions<'a> {
2281    pub repo: &'a Path,
2282    /// Command line of the build to test; the original's command when `None`.
2283    pub build: Option<&'a str>,
2284    pub timeout_secs: Option<u64>,
2285    /// Servers: the port the build listens on, when it is fixed.
2286    pub port: Option<u16>,
2287    /// Replay only this case (a library: only this unit).
2288    pub case: Option<&'a str>,
2289}
2290
2291pub(crate) fn only_case<T>(
2292    items: Vec<T>,
2293    case: Option<&str>,
2294    name: impl Fn(&T) -> &str,
2295) -> Result<Vec<T>> {
2296    let Some(case) = case else {
2297        return Ok(items);
2298    };
2299    let names: Vec<String> = items.iter().map(|i| name(i).to_string()).collect();
2300    let kept: Vec<T> = items.into_iter().filter(|i| name(i) == case).collect();
2301    ensure!(
2302        !kept.is_empty(),
2303        "no case named {case}; the cases are: {}",
2304        names.join(", ")
2305    );
2306    Ok(kept)
2307}
2308
2309#[derive(Debug, Serialize)]
2310pub struct Problem {
2311    pub field: String,
2312    pub detail: String,
2313}
2314
2315#[derive(Debug, Serialize)]
2316pub struct Failure {
2317    pub case: String,
2318    pub args: Vec<String>,
2319    pub problems: Vec<Problem>,
2320}
2321
2322/// Cases the build handed to the original: the front door appends a line to the file named by
2323/// `RUST_ANYTHING_FALLBACK_LOG` for every fallback (and may create it empty to report none).
2324#[derive(Debug, Serialize)]
2325pub struct Fallback {
2326    pub cases: usize,
2327    pub total: usize,
2328    pub rate: f64,
2329    /// The cases that fell back.
2330    pub names: Vec<String>,
2331}
2332
2333#[derive(Debug, Serialize)]
2334pub struct ReplayOutcome {
2335    pub build: Vec<String>,
2336    pub passed: usize,
2337    pub total: usize,
2338    pub skipped: usize,
2339    pub failures: Vec<Failure>,
2340    pub fallback: Option<Fallback>,
2341    pub report: PathBuf,
2342}
2343
2344fn check(
2345    norm: &Normalizers,
2346    command: &[String],
2347    repo: &Path,
2348    spec: &Spec,
2349    timeout: Duration,
2350    effects: Option<&crate::effects::EffectsConfig>,
2351    base: Option<&Path>,
2352) -> Result<(Vec<Problem>, Option<bool>)> {
2353    let run = run_case(command, repo, &spec.case, timeout, effects, base)?;
2354    let mut problems = Vec::new();
2355    let status_ok = match (&spec.status, &run.status) {
2356        (Expect::Code(e), Status::Code(a)) => e == a,
2357        (Expect::Failed, Status::Code(a)) => *a != 0,
2358        (Expect::Killed, Status::Killed) | (Expect::Skip, _) => true,
2359        _ => false,
2360    };
2361    if !status_ok {
2362        let expected = match &spec.status {
2363            Expect::Code(c) => format!("exit code {c}"),
2364            Expect::Failed => "a non-zero exit code".to_string(),
2365            Expect::Killed => "killed by a signal".to_string(),
2366            Expect::Skip => String::new(),
2367        };
2368        problems.push(Problem {
2369            field: "status".to_string(),
2370            detail: format!("expected {expected}, got {}\n", run.status),
2371        });
2372    }
2373    let no_effects = Vec::new();
2374    for (field, expected, actual) in [
2375        ("stdout", &spec.stdout, &run.stdout),
2376        ("stderr", &spec.stderr, &run.stderr),
2377        (
2378            crate::effects::EXT,
2379            &spec.effects,
2380            run.effects.as_ref().unwrap_or(&no_effects),
2381        ),
2382    ] {
2383        if let Some(expected) = expected
2384            && let Some(detail) = compare(
2385                norm,
2386                expected,
2387                actual,
2388                spec.binary,
2389                norm.unordered(&spec.name, field),
2390            )
2391        {
2392            problems.push(Problem {
2393                field: field.to_string(),
2394                detail,
2395            });
2396        }
2397    }
2398    if let Some(expected) = &spec.removed
2399        && *expected != run.removed
2400    {
2401        let list = |paths: &[PathBuf]| -> String {
2402            paths
2403                .iter()
2404                .map(|p| format!("  {}\n", p.display()))
2405                .collect()
2406        };
2407        problems.push(Problem {
2408            field: "removed files".to_string(),
2409            detail: format!(
2410                "expected removed:\n{}got removed:\n{}",
2411                list(expected),
2412                list(&run.removed)
2413            ),
2414        });
2415    }
2416    if let Some(out_dir) = &spec.out_dir {
2417        for (path, expected) in read_files(out_dir) {
2418            let field = format!("file {}", path.display());
2419            match run.files.get(&path) {
2420                None => problems.push(Problem {
2421                    field,
2422                    detail: "not written\n".to_string(),
2423                }),
2424                Some(actual) => {
2425                    let unordered = norm.unordered(&spec.name, &field);
2426                    let detail = match norm.float_files.get(&path) {
2427                        Some(&width) => {
2428                            compare_floats(&expected, actual, width, norm.float_tolerance)
2429                        }
2430                        None => compare(norm, &expected, actual, false, unordered),
2431                    };
2432                    if let Some(detail) = detail {
2433                        problems.push(Problem { field, detail });
2434                    }
2435                }
2436            }
2437        }
2438    }
2439    Ok((problems, run.fallback))
2440}
2441
2442pub(crate) fn report_markdown(outcome: &ReplayOutcome) -> String {
2443    stable_paths(&report_body(outcome))
2444}
2445
2446/// The report with the per-run sandbox paths replaced, so two replays of the same build write the
2447/// same file and CI can commit it and fail on `git diff --exit-code`.
2448fn stable_paths(text: &str) -> String {
2449    static SANDBOX: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
2450    let tmp = std::env::temp_dir();
2451    let tmp = tmp.to_string_lossy();
2452    let tmp = tmp.trim_end_matches(['/', '\\']);
2453    let text = if tmp.len() > 1 {
2454        text.replace(tmp, "$TMPDIR")
2455    } else {
2456        text.to_string()
2457    };
2458    SANDBOX
2459        .get_or_init(|| regex::Regex::new(r"rust-anything-app-(\w+)-\d+-\d+").expect("valid regex"))
2460        .replace_all(&text, "rust-anything-app-$1")
2461        .into_owned()
2462}
2463
2464fn report_body(outcome: &ReplayOutcome) -> String {
2465    let mut out = String::from("# App replay\n\n");
2466    out += &format!(
2467        "Build: `{}`\n\n",
2468        outcome
2469            .build
2470            .iter()
2471            .map(|w| shell_quote(w))
2472            .collect::<Vec<_>>()
2473            .join(" ")
2474    );
2475    out += &format!("Passed: {}/{}\n\n", outcome.passed, outcome.total);
2476    if outcome.skipped > 0 {
2477        out += &format!("Skipped: {}\n\n", outcome.skipped);
2478    }
2479    out += &match &outcome.fallback {
2480        Some(f) => format!(
2481            "Fallback rate: {:.1}% ({}/{} cases answered by the original)\n\n",
2482            f.rate * 100.0,
2483            f.cases,
2484            f.total
2485        ),
2486        None => "Fallback rate: not reported by this build\n\n".to_string(),
2487    };
2488    if outcome.failures.is_empty() {
2489        out += "Every case matches.\n";
2490        return out;
2491    }
2492    out += "## Failing cases\n";
2493    for f in &outcome.failures {
2494        out += &format!(
2495            "\n### {}\n\nArguments: `{}`\n",
2496            f.case,
2497            f.args
2498                .iter()
2499                .map(|w| shell_quote(w))
2500                .collect::<Vec<_>>()
2501                .join(" ")
2502        );
2503        for p in &f.problems {
2504            out += &format!(
2505                "\n{}:\n\n```diff\n{}```\n",
2506                p.field,
2507                p.detail.replace("```", "`\u{200b}``")
2508            );
2509        }
2510    }
2511    out
2512}
2513
2514fn load_specs(dir: &Path) -> Result<Vec<Spec>> {
2515    let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
2516        .with_context(|| {
2517            format!(
2518                "no cases in {}: run `rust-anything app record` first",
2519                dir.display()
2520            )
2521        })?
2522        .flatten()
2523        .map(|e| e.path())
2524        .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "toml"))
2525        .collect();
2526    paths.sort();
2527    let specs = paths
2528        .iter()
2529        .map(|p| load_spec(dir, p))
2530        .collect::<Result<Vec<_>>>()?;
2531    ensure!(
2532        !specs.is_empty(),
2533        "no cases in {}: run `rust-anything app record` first",
2534        dir.display()
2535    );
2536    Ok(specs)
2537}
2538
2539/// The recorded cases' arguments, each with whether the original exited 0.
2540pub(crate) fn recorded_args(repo: &Path) -> Result<Vec<(Vec<String>, bool)>> {
2541    Ok(load_specs(&cases_dir(repo))?
2542        .into_iter()
2543        .map(|s| (s.case.args, matches!(s.status, Expect::Code(0))))
2544        .collect())
2545}
2546
2547pub fn replay(opts: &ReplayOptions) -> Result<ReplayOutcome> {
2548    let repo = opts
2549        .repo
2550        .canonical()
2551        .with_context(|| format!("no folder {}", opts.repo.display()))?;
2552    let dir = cases_dir(&repo);
2553    let config = Config::load(&repo)?;
2554    if config.is_none()
2555        && let Ok(state) = crate::front_door::State::load(&repo)
2556        && state.kind == crate::front_door::AppKind::Library
2557    {
2558        ensure!(
2559            opts.build.is_none(),
2560            "{} is a library: its cases replay through each unit's bindings, so --build does not apply",
2561            state.name
2562        );
2563        return crate::library::replay(&repo, &state, opts.case);
2564    }
2565    let command = match (opts.build, &config) {
2566        (Some(build), _) => shell_split(build)?,
2567        (None, Some(c)) => c.run.clone(),
2568        (None, None) => bail!(
2569            "no {} in {}: run `rust-anything app record` first, or pass --build",
2570            CONFIG_FILE,
2571            dir.display()
2572        ),
2573    };
2574    ensure!(!command.is_empty(), "the build command is empty");
2575    let config = config.unwrap_or_else(|| Config {
2576        schema: SCHEMA.to_string(),
2577        name: "app".to_string(),
2578        run: Vec::new(),
2579        normalize: Vec::new(),
2580        normalizers: BTreeMap::new(),
2581        timeout_secs: default_timeout(),
2582        http: None,
2583        float_tolerance: None,
2584        float_files: BTreeMap::new(),
2585        unordered: BTreeMap::new(),
2586        effects: None,
2587        fresh: Vec::new(),
2588        recorded: Vec::new(),
2589    });
2590    let norm = Normalizers::new(&config)?;
2591    let timeout = Duration::from_secs(opts.timeout_secs.unwrap_or(config.timeout_secs));
2592    if config.http.is_some() {
2593        return crate::http::replay(
2594            &repo, &config, &norm, &command, opts.port, opts.case, timeout,
2595        );
2596    }
2597    let specs = only_case(load_specs(&dir)?, opts.case, |s| &s.name)?;
2598    let effects = config.effects.as_ref();
2599    let base = if config.fresh.is_empty() {
2600        None
2601    } else {
2602        let base = dir.join(FRESH_DIR);
2603        ensure!(
2604            base.is_dir(),
2605            "no {}: record again to snapshot the fresh files",
2606            base.display()
2607        );
2608        Some(base)
2609    };
2610    let check_one = |spec: &Spec| {
2611        if matches!(spec.status, Expect::Skip) {
2612            return Ok((Vec::new(), None));
2613        }
2614        check(
2615            &norm,
2616            &command,
2617            &repo,
2618            spec,
2619            timeout,
2620            effects,
2621            base.as_deref(),
2622        )
2623    };
2624    let results: Vec<Result<_>> = if effects.is_some_and(crate::effects::EffectsConfig::serial) {
2625        specs.iter().map(check_one).collect()
2626    } else {
2627        par_map(&specs, check_one)
2628    };
2629    let mut outcome = ReplayOutcome {
2630        build: command.clone(),
2631        passed: 0,
2632        total: 0,
2633        skipped: 0,
2634        failures: Vec::new(),
2635        fallback: None,
2636        report: dir.join(REPORT_FILE),
2637    };
2638    let (mut reported, mut fell_back) = (false, Vec::new());
2639    for (spec, result) in specs.iter().zip(results) {
2640        if matches!(spec.status, Expect::Skip) {
2641            outcome.skipped += 1;
2642            continue;
2643        }
2644        let (problems, fallback) = result?;
2645        outcome.total += 1;
2646        reported |= fallback.is_some();
2647        if fallback == Some(true) {
2648            fell_back.push(spec.name.clone());
2649        }
2650        if problems.is_empty() {
2651            outcome.passed += 1;
2652        } else {
2653            outcome.failures.push(Failure {
2654                case: spec.name.clone(),
2655                args: spec.case.args.clone(),
2656                problems,
2657            });
2658        }
2659    }
2660    if reported {
2661        outcome.fallback = Some(Fallback {
2662            cases: fell_back.len(),
2663            total: outcome.total,
2664            rate: fell_back.len() as f64 / outcome.total.max(1) as f64,
2665            names: fell_back,
2666        });
2667    }
2668    std::fs::write(&outcome.report, report_markdown(&outcome))
2669        .with_context(|| format!("writing {}", outcome.report.display()))?;
2670    Ok(outcome)
2671}
2672
2673#[cfg(test)]
2674mod tests {
2675    use super::*;
2676
2677    #[test]
2678    fn given_names_keep_their_tail() {
2679        let a = given_slug("tests/format/typescript/conformance/types/never/never.ts");
2680        let b = given_slug("tests/format/typescript/conformance/types/tuple/tuple.ts");
2681        assert_ne!(a, b);
2682        assert_eq!(
2683            a,
2684            "tests-format-typescript-conformance-types-never-never-ts"
2685        );
2686        assert_eq!(slug(&a).len(), 23);
2687    }
2688
2689    #[test]
2690    fn reports_do_not_carry_sandbox_paths() {
2691        let tmp = std::env::temp_dir();
2692        let line = format!(
2693            "-cwd {}\n",
2694            tmp.join("rust-anything-app-run-4242-7")
2695                .join("cwd")
2696                .display()
2697        );
2698        let stable = stable_paths(&line);
2699        assert!(!stable.contains("4242"), "{stable}");
2700        assert!(stable.contains("$TMPDIR"), "{stable}");
2701        assert_eq!(
2702            stable,
2703            stable_paths(&line.replace("4242-7", "99-0")),
2704            "{stable}"
2705        );
2706    }
2707
2708    fn text_matches_exact(e: &str, a: &str) -> bool {
2709        text_matches(e, a, None)
2710    }
2711
2712    fn norm_with_tolerance(tol: Option<f64>) -> Normalizers {
2713        Normalizers::new(&Config {
2714            schema: SCHEMA.to_string(),
2715            name: "app".to_string(),
2716            run: Vec::new(),
2717            normalize: Vec::new(),
2718            normalizers: BTreeMap::new(),
2719            timeout_secs: default_timeout(),
2720            http: None,
2721            float_tolerance: tol,
2722            float_files: BTreeMap::new(),
2723            unordered: BTreeMap::new(),
2724            effects: None,
2725            fresh: Vec::new(),
2726            recorded: Vec::new(),
2727        })
2728        .unwrap()
2729    }
2730
2731    #[test]
2732    fn unordered_lines_pair_up_by_value_within_the_tolerance() {
2733        let norm = norm_with_tolerance(Some(1e-9));
2734        // `2.0` meets `2.0` and `10.0` meets `9.999999999999999`, but `10.0` sorts before `2.0`
2735        // as text, so pairing the sorted lines by position compared `10.0` against `2.0`.
2736        let expected = b"n 2.0\nn 10.0\n";
2737        let actual = b"n 2.0\nn 9.999999999999999\n";
2738        assert!(compare(&norm, expected, actual, false, false).is_none());
2739        assert!(compare(&norm, expected, actual, false, true).is_none());
2740        // A line that is genuinely different is still reported.
2741        let changed = b"n 2.0\nn 11.0\n";
2742        assert!(compare(&norm, expected, changed, false, true).is_some());
2743        // The order the lines arrive in does not matter.
2744        let swapped = b"n 9.999999999999999\nn 2.0\n";
2745        assert!(compare(&norm, expected, swapped, false, true).is_none());
2746    }
2747
2748    #[test]
2749    fn unordered_lines_pair_up_around_a_wildcard() {
2750        let norm = norm_with_tolerance(Some(1e-9));
2751        // `[..]` takes the line the numeric pairing does not want, so a tolerance and a wildcard
2752        // in the same output do not fight over the ordering.
2753        let expected = b"n 10.0\nn [..]\n";
2754        assert!(compare(&norm, expected, b"n 10.0\nn 2.0\n", false, true).is_none());
2755        assert!(compare(&norm, expected, b"n 2.0\nn 10.0\n", false, true).is_none());
2756        assert!(
2757            compare(
2758                &norm,
2759                expected,
2760                b"n 2.0\nn 9.999999999999999\n",
2761                false,
2762                true
2763            )
2764            .is_none()
2765        );
2766        // Nothing to take the 10.0: both actual lines are far from it.
2767        assert!(compare(&norm, expected, b"n 2.0\nn 3.0\n", false, true).is_some());
2768    }
2769
2770    #[test]
2771    fn unordered_lines_keep_a_plain_permutation_matching() {
2772        let norm = norm_with_tolerance(Some(1e-9));
2773        // The same lines in another order match whatever the numbers look like, and a value
2774        // written two ways stays a difference rather than becoming one by being re-sorted.
2775        assert!(compare(&norm, b"n 2\nn 2.0\n", b"n 2.0\nn 2\n", false, true).is_none());
2776        assert!(compare(&norm, b"n 2\nn 2\n", b"n 2.0\nn 2.0\n", false, true).is_some());
2777    }
2778
2779    #[test]
2780    fn unordered_lines_without_a_tolerance_still_compare_as_text() {
2781        let norm = norm_with_tolerance(None);
2782        let expected = b"b\na\n";
2783        assert!(compare(&norm, expected, b"a\nb\n", false, true).is_none());
2784        assert!(compare(&norm, expected, b"a\nc\n", false, true).is_some());
2785        assert!(compare(&norm, expected, b"a\n", false, true).is_some());
2786        // Without a tolerance a number is text like any other, so this stays a mismatch.
2787        let numeric = b"n 10.0\nn 2.0\n";
2788        assert!(compare(&norm, numeric, b"n 2.0\nn 9.999999999999999\n", false, true).is_some());
2789    }
2790
2791    #[cfg(unix)]
2792    #[test]
2793    fn replay_deadline_covers_descendants_that_keep_pipes_open() {
2794        for script in ["sleep 6 & wait", "sleep 6 & exit 0"] {
2795            let command = ["/bin/sh".into(), "-c".into(), script.into()];
2796            let start = Instant::now();
2797            let run = run_case(
2798                &command,
2799                Path::new("."),
2800                &Case::new(Vec::new()),
2801                Duration::from_millis(200),
2802                None,
2803                None,
2804            )
2805            .unwrap();
2806            assert!(start.elapsed() < Duration::from_secs(3), "{script}");
2807            assert!(run.status == Status::Timeout, "{script}: {}", run.status);
2808        }
2809    }
2810
2811    #[test]
2812    fn matching_follows_trycmd() {
2813        assert!(text_matches_exact("a\nb\n", "a\nb\n"));
2814        assert!(text_matches_exact("now: [..]\n", "now: 1234\n"));
2815        assert!(text_matches_exact("x [..] y [..] z\n", "x 1 y 2 y 3 z\n"));
2816        assert!(!text_matches_exact("x [..] z\n", "x 1 y\n"));
2817        assert!(text_matches_exact(
2818            "head\n...\ntail\n",
2819            "head\n1\n2\ntail\n"
2820        ));
2821        assert!(text_matches_exact("head\n...\ntail\n", "head\ntail\n"));
2822        assert!(!text_matches_exact("head\ntail\n", "head\nmid\ntail\n"));
2823        assert!(text_matches_exact("a\r\nb", "a\nb\n"));
2824    }
2825
2826    #[test]
2827    fn numbers_match_within_the_tolerance() {
2828        let e = "step 1\nenergy 0.3\nat [..]\n";
2829        let a = "step 1\nenergy 0.30000000000000004\nat 12:00\n";
2830        assert!(!text_matches(e, a, None));
2831        assert!(text_matches(e, a, Some(1e-9)));
2832        assert!(!text_matches(
2833            e,
2834            "step 2\nenergy 0.3\nat 12:00\n",
2835            Some(1e-9)
2836        ));
2837        assert!(!render_diff(e, a, Some(1e-9)).contains("energy"));
2838    }
2839
2840    #[cfg(unix)]
2841    #[test]
2842    fn binary_capture_replays_its_text_companion_byte_for_byte() {
2843        let repo = temp_dir("binary-stream-pair").unwrap();
2844        let run = [
2845            "/bin/sh".to_string(),
2846            "-c".to_string(),
2847            r"printf '\377'; printf 'at 2026-11-16T10:00:00Z\n' >&2".to_string(),
2848        ];
2849        let recorded = record(&RecordOptions {
2850            repo: &repo,
2851            run: &run,
2852            inputs: None,
2853            normalize: &["timestamps".into()],
2854            name: None,
2855            traps: false,
2856            timeout_secs: None,
2857            http: false,
2858            server_args: &[],
2859            fresh: &[],
2860            pace_ms: None,
2861            port: None,
2862            float_tolerance: None,
2863            float_files: &[],
2864            effects: None,
2865        })
2866        .unwrap();
2867        assert_eq!(recorded.cases, 1);
2868        let replayed = replay(&ReplayOptions {
2869            repo: &repo,
2870            build: None,
2871            timeout_secs: None,
2872            port: None,
2873            case: None,
2874        })
2875        .unwrap();
2876        assert_eq!(
2877            (replayed.passed, replayed.total),
2878            (1, 1),
2879            "{:?}",
2880            replayed.failures
2881        );
2882        std::fs::remove_dir_all(repo).unwrap();
2883    }
2884
2885    #[test]
2886    fn noise_is_classified() {
2887        let norm = Normalizers::new(&Config {
2888            schema: SCHEMA.to_string(),
2889            name: "app".to_string(),
2890            run: Vec::new(),
2891            normalize: Vec::new(),
2892            normalizers: BTreeMap::new(),
2893            timeout_secs: 30,
2894            http: None,
2895            float_tolerance: None,
2896            float_files: BTreeMap::new(),
2897            unordered: BTreeMap::new(),
2898            effects: None,
2899            fresh: Vec::new(),
2900            recorded: Vec::new(),
2901        })
2902        .unwrap();
2903        let kind = |a: &str, b: &str| settle_text(&norm, a.as_bytes(), b.as_bytes()).1;
2904        assert_eq!(kind("a\nb\n", "a\nb\n"), None);
2905        assert_eq!(kind("x=1\ny=2\n", "y=2\nx=1\n"), Some(NoiseKind::Order));
2906        assert_eq!(kind("at 10:01\n", "at 10:02\n"), Some(NoiseKind::Values));
2907        assert_eq!(kind("a\nz\n", "a\nb\nc\nz\n"), Some(NoiseKind::Lines));
2908        let (kept, _, _) = settle_text(&norm, b"x=1\ny=2\n", b"y=2\nx=1\n");
2909        assert_eq!(kept, b"x=1\ny=2\n", "order noise keeps the lines exactly");
2910    }
2911
2912    #[test]
2913    fn unordered_output_matches_in_any_order_but_not_other_lines() {
2914        let norm = Normalizers::new(&Config {
2915            schema: SCHEMA.to_string(),
2916            name: "app".to_string(),
2917            run: Vec::new(),
2918            normalize: Vec::new(),
2919            normalizers: BTreeMap::new(),
2920            timeout_secs: 30,
2921            http: None,
2922            float_tolerance: None,
2923            float_files: BTreeMap::new(),
2924            unordered: BTreeMap::from([("c".to_string(), vec!["stdout".to_string()])]),
2925            effects: None,
2926            fresh: Vec::new(),
2927            recorded: Vec::new(),
2928        })
2929        .unwrap();
2930        assert!(norm.unordered("c", "stdout"));
2931        assert!(!norm.unordered("c", "stderr"));
2932        let e = b"x=1\ny=2\n";
2933        assert!(compare(&norm, e, b"y=2\nx=1\n", false, true).is_none());
2934        assert!(compare(&norm, e, b"y=2\nx=2\n", false, true).is_some());
2935        assert!(compare(&norm, e, b"x=1\n", false, true).is_some());
2936        assert!(compare(&norm, e, b"y=2\nx=1\n", false, false).is_some());
2937    }
2938
2939    #[test]
2940    fn timestamps_cover_javascript_date_strings() {
2941        let re = Regex::new(TIMESTAMP).unwrap();
2942        let line = "Generated on Sat Nov 21 2026 01:30:12 GMT+0300 (Türkiye Standard Time) - ok";
2943        assert_eq!(re.replace_all(line, "[..]"), "Generated on [..] - ok");
2944        assert_eq!(
2945            re.replace_all("Mon Jan 05 2026 09:00:00 GMT-0800", "[..]"),
2946            "[..]"
2947        );
2948        assert_eq!(re.replace_all("at 2026-11-16T10:00:00Z", "[..]"), "at [..]");
2949        assert_eq!(re.replace_all("Saturday 12", "[..]"), "Saturday 12");
2950    }
2951
2952    #[test]
2953    fn noise_becomes_wildcards() {
2954        assert_eq!(
2955            merge_noise(
2956                "start\nnow: 2026-11-16 10:00:01\nend\n",
2957                "start\nnow: 2026-11-16 10:00:02\nend\n"
2958            ),
2959            "start\nnow: 2026-11-16 10:00:[..]\nend\n"
2960        );
2961        assert_eq!(merge_noise("a\nb\nz\n", "a\nc\nd\nz\n"), "a\n...\nz\n");
2962        assert_eq!(merge_line("id=ab12 ok", "id=cd34 ok"), "id=[..] ok");
2963        let merged = merge_noise("x 1\n", "x 2\n");
2964        assert!(text_matches_exact(&merged, "x 3\n"));
2965    }
2966
2967    #[test]
2968    fn normalizers_by_name() {
2969        let mut config = Config {
2970            schema: SCHEMA.to_string(),
2971            name: "app".to_string(),
2972            run: Vec::new(),
2973            normalize: vec!["timestamps".into(), "uuids".into(), "key-order".into()],
2974            normalizers: BTreeMap::from([("req".to_string(), r"req-\d+".to_string())]),
2975            timeout_secs: 30,
2976            http: None,
2977            float_tolerance: None,
2978            float_files: BTreeMap::new(),
2979            unordered: BTreeMap::new(),
2980            effects: None,
2981            fresh: Vec::new(),
2982            recorded: Vec::new(),
2983        };
2984        let norm = Normalizers::new(&config).unwrap();
2985        assert_eq!(
2986            norm.apply(
2987                "at 2026-11-16T10:00:00.123Z id 123e4567-e89b-12d3-a456-426614174000 req-77"
2988            ),
2989            "at [..] id [..] [..]"
2990        );
2991        assert_eq!(
2992            norm.canonical("{\"b\":1,\"a\":{\"d\":2,\"c\":3}}\nplain"),
2993            "{\"a\":{\"c\":3,\"d\":2},\"b\":1}\nplain"
2994        );
2995        config.normalize.push("nope".into());
2996        assert!(Normalizers::new(&config).is_err());
2997    }
2998
2999    #[test]
3000    fn examples_become_cases() {
3001        let repo = temp_dir("examples").unwrap();
3002        std::fs::write(repo.join("in.txt"), "hello\n").unwrap();
3003        std::fs::write(
3004            repo.join("README.md"),
3005            "# tool\n\n```console\n$ tool count in.txt\n3\n$ echo \"a b\" | tool words\n$ git status\n```\n\n```sh\nLANG=C tool upper 'x y'\ntool sort < in.txt\ntool a | grep b\n```\n",
3006        )
3007        .unwrap();
3008        let names = vec!["tool".to_string()];
3009        let cases = find_examples(&repo, &names);
3010        let args: Vec<Vec<String>> = cases.iter().map(|c| c.args.clone()).collect();
3011        assert_eq!(
3012            args,
3013            [
3014                vec!["count", "in.txt"],
3015                vec!["words"],
3016                vec!["upper", "x y"],
3017                vec!["sort"],
3018            ]
3019        );
3020        assert_eq!(cases[0].files[Path::new("in.txt")], b"hello\n");
3021        assert_eq!(cases[1].stdin.as_deref(), Some(&b"a b\n"[..]));
3022        assert_eq!(cases[2].env["LANG"], "C");
3023        assert_eq!(cases[3].stdin.as_deref(), Some(&b"hello\n"[..]));
3024        std::fs::remove_dir_all(&repo).unwrap();
3025    }
3026
3027    #[test]
3028    fn examples_continued_with_a_backslash_are_joined() {
3029        let repo = temp_dir("continued-examples").unwrap();
3030        std::fs::write(
3031            repo.join("README.md"),
3032            "```console\n$ tool upper \\\n    --loud \\\n    'x y'\n$ tool path C:\\\\\n$ tool count in.txt\n$ tool upper --mode=lo\\\nud\n$ tool echo a\\ \n$ tool count b.txt\n```\n",
3033        )
3034        .unwrap();
3035        std::fs::write(
3036            repo.join("demo.sh"),
3037            "tool sort \\\n  --reverse\n# tool hidden \\\ntool count c.txt\n",
3038        )
3039        .unwrap();
3040        let names = vec!["tool".to_string()];
3041        let args: Vec<Vec<String>> = find_examples(&repo, &names)
3042            .iter()
3043            .map(|c| c.args.clone())
3044            .collect();
3045        std::fs::remove_dir_all(&repo).unwrap();
3046        // Not continuations: a doubled backslash (a literal one), a backslash followed by a space,
3047        // and a backslash at the end of a comment. Joining adds no space of its own (`--mode=loud`).
3048        assert_eq!(
3049            args,
3050            [
3051                vec!["upper", "--loud", "x y"],
3052                vec!["path", "C:\\"],
3053                vec!["count", "in.txt"],
3054                vec!["upper", "--mode=loud"],
3055                vec!["echo", "a "],
3056                vec!["count", "b.txt"],
3057                vec!["sort", "--reverse"],
3058                vec!["count", "c.txt"],
3059            ]
3060        );
3061    }
3062
3063    #[test]
3064    fn traps_keep_the_shape_of_the_case() {
3065        let mut base = Case::new(vec!["div".into(), "7".into(), "2".into()]);
3066        base.stdin = Some(b"{\"a\":1}".to_vec());
3067        let traps = trap_cases(&[base]);
3068        assert!(traps.iter().all(|c| c.args[0] == "div"));
3069        assert!(traps.iter().any(|c| c.args == ["div", "-7", "2"]));
3070        assert!(traps.iter().any(|c| c.args == ["div", "7", "0"]));
3071        assert!(
3072            traps
3073                .iter()
3074                .any(|c| c.stdin.as_deref() == Some(JSON_TRAPS[0].as_bytes()))
3075        );
3076        let text = trap_cases(&[Case::new(vec!["upper".into(), "hi".into()])]);
3077        assert!(text.iter().any(|c| c.args[1] == "👍🏽 thumbs"));
3078    }
3079
3080    #[cfg(unix)]
3081    #[test]
3082    fn recording_keeps_all_cases_when_a_generated_name_is_already_used() {
3083        let repo = temp_dir("case-name-collisions").unwrap();
3084        let inputs = repo.join("cases.jsonl");
3085        std::fs::write(
3086            &inputs,
3087            concat!(
3088                "{\"name\":\"x\",\"args\":[\"one\"]}\n",
3089                "{\"name\":\"x-3\",\"args\":[\"two\"]}\n",
3090                "{\"name\":\"x\",\"args\":[\"three\"]}\n"
3091            ),
3092        )
3093        .unwrap();
3094        let recorded = record(&RecordOptions {
3095            repo: &repo,
3096            run: &["/bin/echo".into()],
3097            inputs: Some(&inputs),
3098            normalize: &[],
3099            name: None,
3100            traps: false,
3101            timeout_secs: None,
3102            http: false,
3103            server_args: &[],
3104            fresh: &[],
3105            pace_ms: None,
3106            port: None,
3107            float_tolerance: None,
3108            float_files: &[],
3109            effects: None,
3110        })
3111        .unwrap();
3112        let read = |name: &str| std::fs::read_to_string(recorded.dir.join(name)).unwrap();
3113        assert_eq!(recorded.cases, 3);
3114        assert_eq!(read("x.stdout"), "one\n");
3115        assert_eq!(read("x-3.stdout"), "two\n");
3116        assert_eq!(read("x-4.stdout"), "three\n");
3117        std::fs::remove_dir_all(repo).unwrap();
3118    }
3119
3120    #[test]
3121    fn names_come_from_the_run_command_and_manifests() {
3122        let repo = temp_dir("names").unwrap();
3123        std::fs::create_dir_all(repo.join("out")).unwrap();
3124        std::fs::write(
3125            repo.join("package.json"),
3126            r#"{"name":"x","bin":{"mytool":"b.js"}}"#,
3127        )
3128        .unwrap();
3129        let run: Vec<String> = ["java", "-cp", "out", "Tcli"].map(String::from).to_vec();
3130        assert_eq!(app_names(&repo, &run, None), ["tcli", "mytool"]);
3131        std::fs::remove_dir_all(&repo).unwrap();
3132    }
3133
3134    #[test]
3135    fn python_program_names_are_case_insensitive() {
3136        assert!(is_python_program("PYTHON"));
3137        assert!(is_python_program("/tools/Python3.exe"));
3138        assert!(is_python_program("Py.cmd"));
3139        assert!(!is_python_program("pythonw.exe"));
3140    }
3141
3142    #[test]
3143    fn shell_words() {
3144        assert_eq!(
3145            shell_split(r#"cargo run -q -- "a b" 'c d' e\ f"#).unwrap(),
3146            ["cargo", "run", "-q", "--", "a b", "c d", "e f"]
3147        );
3148        assert!(shell_split("a | b").is_err());
3149        assert!(shell_tokens("echo $(date)").is_none());
3150        assert!(shell_tokens("echo `date`").is_none());
3151        assert_eq!(
3152            shell_split(r"echo \$(date) \`date\`").unwrap(),
3153            ["echo", "$(date)", "`date`"]
3154        );
3155        #[cfg(windows)]
3156        assert_eq!(
3157            shell_split(r"C:\tools\rust-anything\app.exe --flag").unwrap(),
3158            [r"C:\tools\rust-anything\app.exe", "--flag"]
3159        );
3160        #[cfg(windows)]
3161        assert_eq!(
3162            shell_split(r"run C:\$cache\tool.exe").unwrap(),
3163            ["run", r"C:\$cache\tool.exe"]
3164        );
3165        #[cfg(windows)]
3166        assert_eq!(
3167            shell_split(r"\\server\share\tool.exe --flag").unwrap(),
3168            [r"\\server\share\tool.exe", "--flag"]
3169        );
3170        assert_eq!(shell_split(r"echo one\\two").unwrap(), ["echo", r"one\two"]);
3171    }
3172}