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};
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;
29const MAX_INPUT_FILE: u64 = 1 << 20;
30const TIMESTAMP: &str = r"\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";
31const UUID: &str =
32    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";
33
34pub(crate) const INT_TRAPS: [&str; 8] = [
35    "-7",
36    "0",
37    "-1",
38    "2147483648",
39    "9007199254740993",
40    "9223372036854775807",
41    "-9223372036854775808",
42    "18446744073709551616",
43];
44pub(crate) const FLOAT_TRAPS: [&str; 7] = [
45    "-0.0",
46    "0.1",
47    "0.30000000000000004",
48    "1e21",
49    "1e-7",
50    "5e-324",
51    "1.7976931348623157e308",
52];
53pub(crate) const STRING_TRAPS: [&str; 10] = [
54    "héllo wörld",
55    "👍🏽 thumbs",
56    "日本語",
57    "",
58    "e\u{301}",
59    "İstanbul",
60    "straße",
61    "ılık ırmak",
62    "👨\u{200D}👩\u{200D}👧 family",
63    "a\u{00A0}b",
64];
65pub(crate) const STDIN_TRAPS: [&str; 4] = [
66    "naïve café 👍🏽\nsecond line\n",
67    "",
68    "日本語 テキスト\r\nline two\r\n",
69    "  spaced   out  \n\n",
70];
71pub(crate) const JSON_TRAPS: [&str; 2] = [
72    r#"{"zebra":1,"apple":2,"10":3,"2":4,"é":5,"Apple":6}"#,
73    r#"{"n":9007199254740993,"f":1e21,"t":0.1,"neg":-7}"#,
74];
75const NOT_APP_NAMES: [&str; 29] = [
76    "node", "nodejs", "python", "python3", "py", "ruby", "java", "go", "deno", "bun", "tsx",
77    "ts-node", "sh", "bash", "zsh", "cargo", "npx", "npm", "pnpm", "yarn", "uv", "poetry",
78    "bundle", "run", "exec", "env", "sudo", "php", "dotnet",
79];
80
81/// `rust/app-cases/rust-anything.json`: how to run the original, and the normalizers.
82#[derive(Debug, Clone, Serialize, Deserialize)]
83pub struct Config {
84    pub schema: String,
85    pub name: String,
86    pub run: Vec<String>,
87    #[serde(default, skip_serializing_if = "Vec::is_empty")]
88    pub normalize: Vec<String>,
89    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
90    pub normalizers: BTreeMap<String, String>,
91    #[serde(default = "default_timeout")]
92    pub timeout_secs: u64,
93    /// Set when the app is a server: cases are requests, in `http/`.
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub http: Option<crate::http::HttpConfig>,
96    /// Numbers in the output match within this relative tolerance.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub float_tolerance: Option<f64>,
99    /// Outputs whose line order the original's own runs disagreed on, by case: their lines must
100    /// match in any order.
101    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
102    pub unordered: BTreeMap<String, Vec<String>>,
103}
104
105pub(crate) fn default_timeout() -> u64 {
106    30
107}
108
109impl Config {
110    pub fn load(repo: &Path) -> Result<Option<Config>> {
111        let path = cases_dir(repo).join(CONFIG_FILE);
112        if !path.exists() {
113            return Ok(None);
114        }
115        let text = std::fs::read_to_string(&path)
116            .with_context(|| format!("reading {}", path.display()))?;
117        Ok(Some(
118            serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))?,
119        ))
120    }
121}
122
123pub fn cases_dir(repo: &Path) -> PathBuf {
124    repo.join(CASES_DIR)
125}
126
127/// One line of an `--inputs` file.
128#[derive(Debug, Clone, Default, Deserialize)]
129#[serde(deny_unknown_fields)]
130pub struct Input {
131    #[serde(default)]
132    pub name: Option<String>,
133    #[serde(default)]
134    pub args: Vec<String>,
135    #[serde(default)]
136    pub stdin: Option<String>,
137    #[serde(default)]
138    pub env: BTreeMap<String, String>,
139    #[serde(default)]
140    pub files: BTreeMap<String, String>,
141}
142
143#[derive(Debug, Clone)]
144struct Case {
145    args: Vec<String>,
146    stdin: Option<Vec<u8>>,
147    env: BTreeMap<String, String>,
148    env_remove: Vec<String>,
149    inherit_env: bool,
150    files: BTreeMap<PathBuf, Vec<u8>>,
151}
152
153impl Case {
154    fn new(args: Vec<String>) -> Self {
155        Case {
156            args,
157            stdin: None,
158            env: BTreeMap::new(),
159            env_remove: Vec::new(),
160            inherit_env: true,
161            files: BTreeMap::new(),
162        }
163    }
164
165    fn key(&self) -> String {
166        serde_json::json!([self.args, self.stdin, self.env, self.files]).to_string()
167    }
168}
169
170#[derive(Debug, Clone, PartialEq, Eq)]
171enum Status {
172    Code(i32),
173    Killed,
174    Timeout,
175}
176
177impl std::fmt::Display for Status {
178    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
179        match self {
180            Status::Code(c) => write!(f, "exit code {c}"),
181            Status::Killed => write!(f, "killed by a signal"),
182            Status::Timeout => write!(f, "timed out"),
183        }
184    }
185}
186
187struct Run {
188    stdout: Vec<u8>,
189    stderr: Vec<u8>,
190    status: Status,
191    files: BTreeMap<PathBuf, Vec<u8>>,
192    fallback: Option<bool>,
193}
194
195impl Run {
196    fn written(&self, case: &Case) -> BTreeMap<PathBuf, Vec<u8>> {
197        self.files
198            .iter()
199            .filter(|(path, bytes)| case.files.get(*path) != Some(*bytes))
200            .map(|(p, b)| (p.clone(), b.clone()))
201            .collect()
202    }
203}
204
205pub(crate) struct Normalizers {
206    patterns: Vec<Regex>,
207    key_order: bool,
208    float_tolerance: Option<f64>,
209    unordered: BTreeMap<String, Vec<String>>,
210}
211
212impl Normalizers {
213    fn new(config: &Config) -> Result<Self> {
214        let mut sources: Vec<(&str, &str)> = Vec::new();
215        let mut key_order = false;
216        for name in &config.normalize {
217            match name.as_str() {
218                "timestamps" => sources.push((name, TIMESTAMP)),
219                "uuids" => sources.push((name, UUID)),
220                "key-order" => key_order = true,
221                other => bail!(
222                    "unknown normalizer `{other}`: use {} or define it as `name=regex`",
223                    BUILTIN_NORMALIZERS.join(", ")
224                ),
225            }
226        }
227        sources.extend(
228            config
229                .normalizers
230                .iter()
231                .map(|(n, p)| (n.as_str(), p.as_str())),
232        );
233        let patterns = sources
234            .iter()
235            .map(|(name, pattern)| {
236                Regex::new(pattern).with_context(|| format!("normalizer `{name}`: {pattern}"))
237            })
238            .collect::<Result<Vec<_>>>()?;
239        let float_tolerance = config
240            .float_tolerance
241            .map(crate::tolerance::check)
242            .transpose()?;
243        Ok(Normalizers {
244            patterns,
245            key_order,
246            float_tolerance,
247            unordered: config.unordered.clone(),
248        })
249    }
250
251    /// Whether the original's runs disagreed on the line order of this case's `field`.
252    pub(crate) fn unordered(&self, case: &str, field: &str) -> bool {
253        self.unordered
254            .get(case)
255            .is_some_and(|fields| fields.iter().any(|f| f == field))
256    }
257
258    pub(crate) fn apply(&self, text: &str) -> String {
259        let mut out = text.to_string();
260        for p in &self.patterns {
261            out = p.replace_all(&out, "[..]").into_owned();
262        }
263        out
264    }
265
266    fn canonical(&self, text: &str) -> String {
267        if self.key_order {
268            sort_json_text(text)
269        } else {
270            text.to_string()
271        }
272    }
273}
274
275fn sort_value(v: Value) -> Value {
276    match v {
277        Value::Object(map) => {
278            let sorted: BTreeMap<String, Value> =
279                map.into_iter().map(|(k, v)| (k, sort_value(v))).collect();
280            Value::Object(sorted.into_iter().collect())
281        }
282        Value::Array(items) => Value::Array(items.into_iter().map(sort_value).collect()),
283        other => other,
284    }
285}
286
287fn sort_json_text(text: &str) -> String {
288    let trimmed = text.trim();
289    if trimmed.starts_with(['{', '['])
290        && let Ok(v) = serde_json::from_str::<Value>(trimmed)
291    {
292        return serde_json::to_string_pretty(&sort_value(v)).unwrap_or_default() + "\n";
293    }
294    text.split('\n')
295        .map(|line| {
296            let t = line.trim();
297            if t.starts_with(['{', '['])
298                && let Ok(v) = serde_json::from_str::<Value>(t)
299            {
300                return sort_value(v).to_string();
301            }
302            line.to_string()
303        })
304        .collect::<Vec<_>>()
305        .join("\n")
306}
307
308pub(crate) fn temp_dir(tag: &str) -> Result<PathBuf> {
309    static NEXT: AtomicUsize = AtomicUsize::new(0);
310    let dir = std::env::temp_dir().join(format!(
311        "rust-anything-app-{tag}-{}-{}",
312        std::process::id(),
313        NEXT.fetch_add(1, Ordering::SeqCst)
314    ));
315    let _ = std::fs::remove_dir_all(&dir);
316    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
317    Ok(dir)
318}
319
320pub(crate) fn resolve_word(repo: &Path, word: &str) -> String {
321    if word.starts_with('-') {
322        return word.to_string();
323    }
324    let path = repo.join(word);
325    let looks_like_path = word.contains('/') || word.contains('\\') || path.is_file();
326    if looks_like_path && path.exists() {
327        return path
328            .canonical()
329            .unwrap_or(path)
330            .to_string_lossy()
331            .into_owned();
332    }
333    word.to_string()
334}
335
336#[cfg(any(windows, test))]
337fn is_python_program(program: &str) -> bool {
338    Path::new(program)
339        .file_stem()
340        .and_then(|name| name.to_str())
341        .is_some_and(|name| {
342            ["python", "python3", "py"]
343                .iter()
344                .any(|candidate| name.eq_ignore_ascii_case(candidate))
345        })
346}
347
348fn run_case(command: &[String], repo: &Path, case: &Case, timeout: Duration) -> Result<Run> {
349    let sandbox = temp_dir("run")?;
350    let result = run_in(command, repo, case, timeout, &sandbox);
351    let _ = std::fs::remove_dir_all(&sandbox);
352    result
353}
354
355fn run_in(
356    command: &[String],
357    repo: &Path,
358    case: &Case,
359    timeout: Duration,
360    sandbox: &Path,
361) -> Result<Run> {
362    let work = sandbox.join("cwd");
363    std::fs::create_dir_all(&work)?;
364    for (path, bytes) in &case.files {
365        let target = work.join(path);
366        if let Some(parent) = target.parent() {
367            std::fs::create_dir_all(parent)?;
368        }
369        std::fs::write(&target, bytes)?;
370    }
371    let log = sandbox.join("fallback.log");
372    let (program, rest) = command.split_first().context("empty command")?;
373    let mut cmd = Command::new(resolve_word(repo, program));
374    cmd.args(rest.iter().map(|w| resolve_word(repo, w)))
375        .args(&case.args)
376        .current_dir(&work)
377        .stdin(Stdio::piped())
378        .stdout(Stdio::piped())
379        .stderr(Stdio::piped());
380    if !case.inherit_env {
381        cmd.env_clear();
382    }
383    #[cfg(windows)]
384    if is_python_program(program)
385        && (!case.inherit_env || std::env::var_os("PYTHONIOENCODING").is_none())
386    {
387        // Python otherwise inherits the legacy Windows console code page even though its stdio
388        // is piped. UTF-8 keeps generated Unicode traps recordable; a case can still override it.
389        cmd.env("PYTHONIOENCODING", "utf-8");
390    }
391    for key in &case.env_remove {
392        cmd.env_remove(key);
393    }
394    cmd.envs(&case.env).env(FALLBACK_ENV, &log);
395    #[cfg(unix)]
396    {
397        use std::os::unix::process::CommandExt as _;
398        cmd.process_group(0);
399    }
400    let mut child = cmd
401        .spawn()
402        .with_context(|| format!("running `{}`", command.join(" ")))?;
403    let stdin = child.stdin.take();
404    let input = case.stdin.clone().unwrap_or_default();
405    let writer = std::thread::spawn(move || {
406        if let Some(mut pipe) = stdin {
407            let _ = pipe.write_all(&input);
408        }
409    });
410    let mut out_pipe = child.stdout.take().context("no stdout pipe")?;
411    let mut err_pipe = child.stderr.take().context("no stderr pipe")?;
412    let out_reader = std::thread::spawn(move || {
413        let mut buf = Vec::new();
414        let _ = out_pipe.read_to_end(&mut buf);
415        buf
416    });
417    let err_reader = std::thread::spawn(move || {
418        let mut buf = Vec::new();
419        let _ = err_pipe.read_to_end(&mut buf);
420        buf
421    });
422    let start = Instant::now();
423    let status = loop {
424        if let Some(s) = child.try_wait()? {
425            #[cfg(unix)]
426            let pipes_done =
427                writer.is_finished() && out_reader.is_finished() && err_reader.is_finished();
428            #[cfg(not(unix))]
429            let pipes_done = true;
430            if pipes_done {
431                break s.code().map_or(Status::Killed, Status::Code);
432            }
433        }
434        if start.elapsed() > timeout {
435            #[cfg(unix)]
436            {
437                let _ = Command::new("/bin/kill")
438                    .args(["-KILL", "--", &format!("-{}", child.id())])
439                    .stderr(Stdio::null())
440                    .status();
441            }
442            let _ = child.kill();
443            let _ = child.wait();
444            break Status::Timeout;
445        }
446        std::thread::sleep(Duration::from_millis(2));
447    };
448    let _ = writer.join();
449    let stdout = out_reader.join().unwrap_or_default();
450    let stderr = err_reader.join().unwrap_or_default();
451
452    let mut cwd_forms = vec![work.to_string_lossy().into_owned()];
453    if let Ok(real) = work.canonical() {
454        cwd_forms.insert(0, real.to_string_lossy().into_owned());
455    }
456    let redact = |bytes: Vec<u8>| -> Vec<u8> {
457        match String::from_utf8(bytes) {
458            Ok(mut text) => {
459                for form in &cwd_forms {
460                    text = text.replace(form.as_str(), "[CWD]");
461                }
462                text.into_bytes()
463            }
464            Err(e) => e.into_bytes(),
465        }
466    };
467    let mut files = BTreeMap::new();
468    for path in walk_files(&work) {
469        let rel = path.strip_prefix(&work).unwrap_or(&path).to_path_buf();
470        files.insert(rel, redact(std::fs::read(&path).unwrap_or_default()));
471    }
472    let fallback = std::fs::metadata(&log).ok().map(|m| m.len() > 0);
473    Ok(Run {
474        stdout: redact(stdout),
475        stderr: redact(stderr),
476        status,
477        files,
478        fallback,
479    })
480}
481
482fn walk_files(root: &Path) -> Vec<PathBuf> {
483    let mut out = Vec::new();
484    let mut stack = vec![root.to_path_buf()];
485    while let Some(dir) = stack.pop() {
486        let Ok(entries) = std::fs::read_dir(&dir) else {
487            continue;
488        };
489        for entry in entries.flatten() {
490            let Ok(kind) = entry.file_type() else {
491                continue;
492            };
493            if kind.is_dir() {
494                stack.push(entry.path());
495            } else if kind.is_file() {
496                out.push(entry.path());
497            }
498        }
499    }
500    out.sort();
501    out
502}
503
504fn par_map<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> R + Sync) -> Vec<R> {
505    let threads = std::thread::available_parallelism()
506        .map_or(4, |n| n.get())
507        .clamp(1, 8);
508    let next = AtomicUsize::new(0);
509    let results: Vec<Mutex<Option<R>>> = items.iter().map(|_| Mutex::new(None)).collect();
510    std::thread::scope(|s| {
511        for _ in 0..threads {
512            s.spawn(|| {
513                loop {
514                    let i = next.fetch_add(1, Ordering::SeqCst);
515                    let Some(item) = items.get(i) else { break };
516                    let r = f(item);
517                    if let Ok(mut slot) = results[i].lock() {
518                        *slot = Some(r);
519                    }
520                }
521            });
522        }
523    });
524    results
525        .into_iter()
526        .filter_map(|m| m.into_inner().ok().flatten())
527        .collect()
528}
529
530#[derive(Debug, Clone, PartialEq, Eq)]
531pub(crate) struct Tok {
532    pub(crate) text: String,
533    pub(crate) op: bool,
534}
535
536pub(crate) fn shell_tokens(line: &str) -> Option<Vec<Tok>> {
537    let mut toks = Vec::new();
538    let mut cur = String::new();
539    let mut in_tok = false;
540    let mut chars = line.chars().peekable();
541    let flush = |toks: &mut Vec<Tok>, cur: &mut String, in_tok: &mut bool| {
542        if *in_tok {
543            toks.push(Tok {
544                text: std::mem::take(cur),
545                op: false,
546            });
547            *in_tok = false;
548        }
549    };
550    while let Some(c) = chars.next() {
551        match c {
552            ' ' | '\t' => flush(&mut toks, &mut cur, &mut in_tok),
553            '\'' => {
554                in_tok = true;
555                loop {
556                    match chars.next()? {
557                        '\'' => break,
558                        x => cur.push(x),
559                    }
560                }
561            }
562            '"' => {
563                in_tok = true;
564                loop {
565                    match chars.next()? {
566                        '"' => break,
567                        '\\' => match chars.next()? {
568                            x @ ('"' | '\\' | '$' | '`') => cur.push(x),
569                            x => {
570                                cur.push('\\');
571                                cur.push(x);
572                            }
573                        },
574                        '`' => return None,
575                        '$' if chars.peek() == Some(&'(') => return None,
576                        x => cur.push(x),
577                    }
578                }
579            }
580            '\\' => {
581                in_tok = true;
582                let mut following = chars.clone();
583                let next = following.next();
584                let after_next = following.next();
585                let escaped_substitution = next == Some('$') && after_next == Some('(');
586                let unc_prefix = cur.is_empty()
587                    && next == Some('\\')
588                    && after_next
589                        .is_some_and(|c| !c.is_whitespace() && !"'\"\\|<>&;$`".contains(c));
590                if cfg!(windows)
591                    && (unc_prefix
592                        || (!escaped_substitution
593                            && !chars
594                                .peek()
595                                .is_some_and(|c| c.is_whitespace() || "'\"\\|<>&;`".contains(*c))))
596                {
597                    cur.push('\\');
598                } else if let Some(x) = chars.next() {
599                    cur.push(x);
600                }
601            }
602            '|' | '<' | '>' | ';' | '&' => {
603                flush(&mut toks, &mut cur, &mut in_tok);
604                let mut op = c.to_string();
605                while let Some(&n) = chars.peek() {
606                    if !"|<>&".contains(n) {
607                        break;
608                    }
609                    op.push(n);
610                    chars.next();
611                }
612                toks.push(Tok { text: op, op: true });
613            }
614            '#' if !in_tok => break,
615            '`' => return None,
616            '$' if chars.peek() == Some(&'(') => return None,
617            _ => {
618                in_tok = true;
619                cur.push(c);
620            }
621        }
622    }
623    flush(&mut toks, &mut cur, &mut in_tok);
624    Some(toks)
625}
626
627/// Splits a command line into words, shell-style quoting, no shell operators.
628pub fn shell_split(line: &str) -> Result<Vec<String>> {
629    let toks = shell_tokens(line).with_context(|| format!("cannot split `{line}`"))?;
630    if let Some(op) = toks.iter().find(|t| t.op) {
631        bail!(
632            "`{line}` uses the shell operator `{}`: put the pipeline in a script and give its path",
633            op.text
634        );
635    }
636    Ok(toks.into_iter().map(|t| t.text).collect())
637}
638
639pub(crate) fn shell_quote(word: &str) -> String {
640    let plain = !word.is_empty()
641        && word
642            .chars()
643            .all(|c| c.is_alphanumeric() || "-_./=:,+@%".contains(c));
644    if plain {
645        word.to_string()
646    } else {
647        format!("'{}'", word.replace('\'', r"'\''"))
648    }
649}
650
651fn lines(text: &str) -> Vec<&str> {
652    let text = text.strip_suffix('\n').unwrap_or(text);
653    if text.is_empty() {
654        return Vec::new();
655    }
656    text.split('\n')
657        .map(|l| l.strip_suffix('\r').unwrap_or(l))
658        .collect()
659}
660
661#[derive(Debug, Clone, Copy, PartialEq, Eq)]
662enum Op {
663    Equal(usize, usize),
664    Delete(usize),
665    Insert(usize),
666}
667
668fn diff_ops<A, B>(a: &[A], b: &[B], eq: impl Fn(&A, &B) -> bool) -> Vec<Op> {
669    let mut head = 0;
670    while head < a.len() && head < b.len() && eq(&a[head], &b[head]) {
671        head += 1;
672    }
673    let mut tail = 0;
674    while tail < a.len() - head
675        && tail < b.len() - head
676        && eq(&a[a.len() - 1 - tail], &b[b.len() - 1 - tail])
677    {
678        tail += 1;
679    }
680    let (am, bm) = (&a[head..a.len() - tail], &b[head..b.len() - tail]);
681    let mut ops: Vec<Op> = (0..head).map(|i| Op::Equal(i, i)).collect();
682    let (n, m) = (am.len(), bm.len());
683    if n * m <= 4_000_000 {
684        let mut lcs = vec![vec![0u32; m + 1]; n + 1];
685        for i in (0..n).rev() {
686            for j in (0..m).rev() {
687                lcs[i][j] = if eq(&am[i], &bm[j]) {
688                    lcs[i + 1][j + 1] + 1
689                } else {
690                    lcs[i + 1][j].max(lcs[i][j + 1])
691                };
692            }
693        }
694        let (mut i, mut j) = (0, 0);
695        while i < n || j < m {
696            if i < n && j < m && eq(&am[i], &bm[j]) {
697                ops.push(Op::Equal(head + i, head + j));
698                i += 1;
699                j += 1;
700            } else if i < n && (j == m || lcs[i + 1][j] >= lcs[i][j + 1]) {
701                ops.push(Op::Delete(head + i));
702                i += 1;
703            } else {
704                ops.push(Op::Insert(head + j));
705                j += 1;
706            }
707        }
708    } else {
709        ops.extend((0..n).map(|i| Op::Delete(head + i)));
710        ops.extend((0..m).map(|j| Op::Insert(head + j)));
711    }
712    ops.extend((0..tail).map(|k| Op::Equal(a.len() - tail + k, b.len() - tail + k)));
713    ops
714}
715
716pub(crate) fn line_matches(expected: &str, actual: &str) -> bool {
717    if !expected.contains("[..]") {
718        return expected == actual;
719    }
720    let parts: Vec<&str> = expected.split("[..]").collect();
721    let (first, last) = (parts[0], parts[parts.len() - 1]);
722    let Some(rest) = actual.strip_prefix(first) else {
723        return false;
724    };
725    let Some(mut rest) = rest.strip_suffix(last) else {
726        return false;
727    };
728    for mid in &parts[1..parts.len() - 1] {
729        match rest.find(mid) {
730            Some(i) => rest = &rest[i + mid.len()..],
731            None => return false,
732        }
733    }
734    true
735}
736
737/// A line within the float tolerance, for lines without wildcards.
738fn line_matches_within(expected: &str, actual: &str, tol: Option<f64>) -> bool {
739    line_matches(expected, actual)
740        || tol.is_some_and(|t| {
741            !expected.contains("[..]") && crate::tolerance::line_close(expected, actual, t)
742        })
743}
744
745/// trycmd's matching: `[..]` is any text within a line, a `...` line is any number of lines.
746fn text_matches(expected: &str, actual: &str, tol: Option<f64>) -> bool {
747    let (e, a) = (lines(expected), lines(actual));
748    let m = a.len();
749    let mut next = vec![false; m + 1];
750    next[m] = true;
751    for line in e.iter().rev() {
752        let mut cur = vec![false; m + 1];
753        for j in (0..=m).rev() {
754            cur[j] = if *line == "..." {
755                next[j] || (j < m && cur[j + 1])
756            } else {
757                j < m && line_matches_within(line, a[j], tol) && next[j + 1]
758            };
759        }
760        next = cur;
761    }
762    next[0]
763}
764
765fn render_diff(expected: &str, actual: &str, tol: Option<f64>) -> String {
766    let (e, a) = (lines(expected), lines(actual));
767    let ops = diff_ops(&e, &a, |x, y| line_matches_within(x, y, tol));
768    let changed: Vec<bool> = ops.iter().map(|op| !matches!(op, Op::Equal(..))).collect();
769    let near = |k: usize| {
770        let lo = k.saturating_sub(3);
771        let hi = (k + 4).min(ops.len());
772        changed[lo..hi].iter().any(|c| *c)
773    };
774    let mut out = String::new();
775    let mut skipped = false;
776    for (k, op) in ops.iter().enumerate() {
777        match op {
778            Op::Equal(_, j) if near(k) => {
779                skipped = false;
780                out += &format!("  {}\n", a[*j]);
781            }
782            Op::Equal(..) => {
783                if !skipped {
784                    out += "  ⋮\n";
785                    skipped = true;
786                }
787            }
788            Op::Delete(i) => {
789                skipped = false;
790                out += &format!("- {}\n", e[*i]);
791            }
792            Op::Insert(j) => {
793                skipped = false;
794                out += &format!("+ {}\n", a[*j]);
795            }
796        }
797    }
798    let trail = |s: &str| s.ends_with('\n') || s.is_empty();
799    if out.is_empty() || trail(expected) != trail(actual) {
800        out += &format!(
801            "(trailing newline: expected {}, got {})\n",
802            trail(expected),
803            trail(actual)
804        );
805    }
806    out
807}
808
809fn tokens(line: &str) -> Vec<&str> {
810    let mut out = Vec::new();
811    let mut start = None;
812    for (i, c) in line.char_indices() {
813        if c.is_alphanumeric() {
814            start.get_or_insert(i);
815        } else {
816            if let Some(s) = start.take() {
817                out.push(&line[s..i]);
818            }
819            out.push(&line[i..i + c.len_utf8()]);
820        }
821    }
822    if let Some(s) = start {
823        out.push(&line[s..]);
824    }
825    out
826}
827
828pub(crate) fn merge_line(a: &str, b: &str) -> String {
829    let (ta, tb) = (tokens(a), tokens(b));
830    if ta.len() != tb.len() {
831        return "[..]".to_string();
832    }
833    let mut out = String::new();
834    for (x, y) in ta.iter().zip(&tb) {
835        if x == y {
836            out += x;
837        } else if !out.ends_with("[..]") {
838            out += "[..]";
839        }
840    }
841    out
842}
843
844/// Two runs of the original: what they agree on stays, what differs becomes a wildcard.
845fn merge_noise(a: &str, b: &str) -> String {
846    if a == b {
847        return a.to_string();
848    }
849    let (la, lb): (Vec<&str>, Vec<&str>) = (a.split('\n').collect(), b.split('\n').collect());
850    let ops = diff_ops(&la, &lb, |x, y| x == y);
851    let mut out: Vec<String> = Vec::new();
852    let (mut dels, mut ins): (Vec<&str>, Vec<&str>) = (Vec::new(), Vec::new());
853    let flush = |out: &mut Vec<String>, dels: &mut Vec<&str>, ins: &mut Vec<&str>| {
854        if dels.is_empty() && ins.is_empty() {
855            return;
856        }
857        if dels.len() == ins.len() {
858            for (x, y) in dels.iter().zip(ins.iter()) {
859                out.push(merge_line(x, y));
860            }
861        } else if out.last().map(String::as_str) != Some("...") {
862            out.push("...".to_string());
863        }
864        dels.clear();
865        ins.clear();
866    };
867    for op in ops {
868        match op {
869            Op::Equal(i, _) => {
870                flush(&mut out, &mut dels, &mut ins);
871                out.push(la[i].to_string());
872            }
873            Op::Delete(i) => dels.push(la[i]),
874            Op::Insert(j) => ins.push(lb[j]),
875        }
876    }
877    flush(&mut out, &mut dels, &mut ins);
878    out.join("\n")
879}
880
881fn stem(word: &str) -> String {
882    Path::new(word)
883        .file_stem()
884        .map(|s| s.to_string_lossy().to_lowercase())
885        .unwrap_or_default()
886}
887
888/// Names the app is invoked by, most specific first.
889fn app_names(repo: &Path, run: &[String], explicit: Option<&str>) -> Vec<String> {
890    let mut names: Vec<String> = Vec::new();
891    let mut add = |name: &str| {
892        let name = name.rsplit('/').next().unwrap_or(name).to_lowercase();
893        if !name.is_empty() && !NOT_APP_NAMES.contains(&name.as_str()) && !names.contains(&name) {
894            names.push(name);
895        }
896    };
897    if let Some(name) = explicit {
898        add(name);
899    }
900    for word in run {
901        let path = repo.join(word);
902        if word.starts_with('-') || path.is_dir() || Path::new(word).is_dir() {
903            continue;
904        }
905        add(&stem(word));
906    }
907    if let Ok(text) = std::fs::read_to_string(repo.join("package.json"))
908        && let Ok(pkg) = serde_json::from_str::<Value>(&text)
909    {
910        match &pkg["bin"] {
911            Value::String(_) => add(pkg["name"].as_str().unwrap_or_default()),
912            Value::Object(map) => map.keys().for_each(|k| add(k)),
913            _ => {}
914        }
915    }
916    if let Ok(text) = std::fs::read_to_string(repo.join("pyproject.toml"))
917        && let Ok(doc) = text.parse::<DocumentMut>()
918    {
919        for table in [
920            doc.get("project").and_then(|p| p.get("scripts")),
921            doc.get("tool")
922                .and_then(|t| t.get("poetry"))
923                .and_then(|p| p.get("scripts")),
924        ]
925        .into_iter()
926        .flatten()
927        {
928            if let Some(t) = table.as_table_like() {
929                t.iter().for_each(|(k, _)| add(k));
930            }
931        }
932    }
933    for (dir, dirs_only) in [("cmd", true), ("bin", false), ("exe", false)] {
934        let Ok(entries) = std::fs::read_dir(repo.join(dir)) else {
935            continue;
936        };
937        let mut found: Vec<String> = entries
938            .flatten()
939            .filter(|e| e.file_type().is_ok_and(|t| t.is_dir() == dirs_only))
940            .map(|e| stem(&e.file_name().to_string_lossy()))
941            .collect();
942        found.sort();
943        found.iter().for_each(|n| add(n));
944    }
945    names
946}
947
948fn safe_relative(arg: &str) -> bool {
949    let p = Path::new(arg);
950    !arg.is_empty()
951        && !arg.starts_with('-')
952        && p.components().all(|c| matches!(c, Component::Normal(_)))
953}
954
955fn read_input_file(candidates: &[PathBuf]) -> Option<Vec<u8>> {
956    candidates
957        .iter()
958        .find(|p| p.is_file() && std::fs::metadata(p).is_ok_and(|m| m.len() <= MAX_INPUT_FILE))
959        .and_then(|p| std::fs::read(p).ok())
960}
961
962fn parse_example(line: &str, names: &[String], repo: &Path, doc_dir: &Path) -> Option<Case> {
963    let toks = shell_tokens(line)?;
964    let ops: Vec<usize> = (0..toks.len()).filter(|&i| toks[i].op).collect();
965    let words = |range: &[Tok]| -> Vec<String> { range.iter().map(|t| t.text.clone()).collect() };
966    let lookup = |arg: &str| -> Option<Vec<u8>> {
967        if !safe_relative(arg) {
968            return None;
969        }
970        read_input_file(&[repo.join(arg), doc_dir.join(arg)])
971    };
972    let (main, stdin): (Vec<String>, Option<Vec<u8>>) = match ops.as_slice() {
973        [] => (words(&toks), None),
974        [i] if toks[*i].text == "|" => {
975            let feed = words(&toks[..*i]);
976            let stdin = match feed.first().map(String::as_str) {
977                Some("echo") => {
978                    let newline = feed.get(1).map(String::as_str) != Some("-n");
979                    let text: Vec<&str> = feed[1..]
980                        .iter()
981                        .map(String::as_str)
982                        .filter(|w| !matches!(*w, "-n" | "-e"))
983                        .collect();
984                    let mut text = text.join(" ");
985                    if newline {
986                        text.push('\n');
987                    }
988                    text.into_bytes()
989                }
990                Some("printf") if feed.len() == 2 => feed[1]
991                    .replace("\\n", "\n")
992                    .replace("\\t", "\t")
993                    .into_bytes(),
994                Some("cat") if feed.len() == 2 => lookup(&feed[1])?,
995                _ => return None,
996            };
997            (words(&toks[*i + 1..]), Some(stdin))
998        }
999        [i] if toks[*i].text == "<" && *i + 2 == toks.len() => {
1000            (words(&toks[..*i]), Some(lookup(&toks[*i + 1].text)?))
1001        }
1002        _ => return None,
1003    };
1004    let mut env = BTreeMap::new();
1005    let mut rest = main.as_slice();
1006    while let Some((first, tail)) = rest.split_first() {
1007        let Some((k, v)) = first.split_once('=') else {
1008            break;
1009        };
1010        if k.is_empty() || !k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
1011            break;
1012        }
1013        env.insert(k.to_string(), v.to_string());
1014        rest = tail;
1015    }
1016    let (prog, args) = rest.split_first()?;
1017    if !names.contains(&stem(prog)) {
1018        return None;
1019    }
1020    let mut case = Case::new(args.to_vec());
1021    case.env = env;
1022    case.stdin = stdin;
1023    for arg in args {
1024        if let Some(bytes) = lookup(arg) {
1025            case.files.insert(PathBuf::from(arg), bytes);
1026        }
1027    }
1028    Some(case)
1029}
1030
1031fn find_examples(repo: &Path, names: &[String]) -> Vec<Case> {
1032    if names.is_empty() {
1033        return Vec::new();
1034    }
1035    scan_examples(repo, |line, doc_dir| {
1036        parse_example(line, names, repo, doc_dir)
1037    })
1038}
1039
1040/// Shell lines in the repository's Markdown code blocks and `.sh` files, each given to `parse`
1041/// with the folder of the file it came from.
1042pub(crate) fn scan_examples<T>(repo: &Path, parse: impl Fn(&str, &Path) -> Option<T>) -> Vec<T> {
1043    let skip = ["node_modules", "target", "vendor", ".git"];
1044    let walker = crate::walk::filtered(repo, move |e| {
1045        let name = e.file_name().to_string_lossy();
1046        !skip.contains(&name.as_ref())
1047    })
1048    .max_depth(Some(4))
1049    .sort_by_file_name(|a, b| a.cmp(b))
1050    .build();
1051    let rust_dir = repo.join("rust");
1052    let mut out = Vec::new();
1053    for entry in walker.flatten() {
1054        let path = entry.path();
1055        if path.starts_with(&rust_dir) || !path.is_file() {
1056            continue;
1057        }
1058        let ext = path
1059            .extension()
1060            .map(|e| e.to_string_lossy().to_lowercase())
1061            .unwrap_or_default();
1062        let markdown = matches!(ext.as_str(), "md" | "markdown");
1063        if !markdown && ext != "sh" {
1064            continue;
1065        }
1066        let Ok(text) = std::fs::read_to_string(path) else {
1067            continue;
1068        };
1069        let doc_dir = path.parent().unwrap_or(repo);
1070        let mut fence: Option<String> = None;
1071        for raw in text.lines() {
1072            let line = raw.trim();
1073            if markdown {
1074                if line.starts_with("```") || line.starts_with("~~~") {
1075                    fence = match fence {
1076                        Some(_) => None,
1077                        None => Some(
1078                            line.trim_start_matches(['`', '~'])
1079                                .split_whitespace()
1080                                .next()
1081                                .unwrap_or_default()
1082                                .to_lowercase(),
1083                        ),
1084                    };
1085                    continue;
1086                }
1087                let Some(lang) = &fence else { continue };
1088                let candidate = match line.strip_prefix("$ ") {
1089                    Some(rest) => rest,
1090                    None if matches!(lang.as_str(), "sh" | "bash" | "shell" | "zsh") => line,
1091                    None => continue,
1092                };
1093                if let Some(case) = parse(candidate, doc_dir) {
1094                    out.push(case);
1095                }
1096            } else {
1097                let candidate = line.strip_prefix("$ ").unwrap_or(line);
1098                if let Some(case) = parse(candidate, doc_dir) {
1099                    out.push(case);
1100                }
1101            }
1102        }
1103    }
1104    out
1105}
1106
1107fn read_inputs(path: &Path) -> Result<Vec<(Option<String>, Case)>> {
1108    let text =
1109        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
1110    let mut out = Vec::new();
1111    for (n, line) in text.lines().enumerate() {
1112        if line.trim().is_empty() {
1113            continue;
1114        }
1115        let input: Input = serde_json::from_str(line)
1116            .with_context(|| format!("{}:{}: expected {{\"args\": [...], \"stdin\": ..., \"env\": {{...}}, \"files\": {{path: text}}}}", path.display(), n + 1))?;
1117        let mut case = Case::new(input.args);
1118        case.stdin = input.stdin.map(String::into_bytes);
1119        case.env = input.env;
1120        for (file, content) in input.files {
1121            ensure!(
1122                safe_relative(&file),
1123                "{}:{}: file `{file}` must be a relative path inside the sandbox",
1124                path.display(),
1125                n + 1
1126            );
1127            case.files.insert(PathBuf::from(file), content.into_bytes());
1128        }
1129        out.push((input.name, case));
1130    }
1131    Ok(out)
1132}
1133
1134pub(crate) fn is_word(arg: &str) -> bool {
1135    let mut chars = arg.chars();
1136    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
1137        && chars.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
1138}
1139
1140fn trap_cases(bases: &[Case]) -> Vec<Case> {
1141    let mut out = Vec::new();
1142    for base in bases {
1143        for (i, arg) in base.args.iter().enumerate() {
1144            if i == 0 && is_word(arg) {
1145                continue;
1146            }
1147            let number = arg.parse::<f64>().is_ok();
1148            if arg.starts_with('-') && !number {
1149                continue;
1150            }
1151            let values: Vec<&str> = if arg.parse::<i128>().is_ok() {
1152                INT_TRAPS.to_vec()
1153            } else if number && arg.contains(['.', 'e', 'E']) {
1154                FLOAT_TRAPS.to_vec()
1155            } else if base.files.contains_key(Path::new(arg)) {
1156                vec!["missing-input.txt"]
1157            } else {
1158                STRING_TRAPS.to_vec()
1159            };
1160            for v in values.into_iter().filter(|v| v != arg) {
1161                let mut case = base.clone();
1162                case.args[i] = v.to_string();
1163                out.push(case);
1164            }
1165        }
1166        if let Some(stdin) = &base.stdin {
1167            let json = std::str::from_utf8(stdin)
1168                .ok()
1169                .and_then(|t| serde_json::from_str::<Value>(t).ok())
1170                .is_some_and(|v| v.is_object() || v.is_array());
1171            let values: &[&str] = if json { &JSON_TRAPS } else { &STDIN_TRAPS };
1172            for v in values {
1173                let mut case = base.clone();
1174                case.stdin = Some(v.as_bytes().to_vec());
1175                out.push(case);
1176            }
1177        }
1178    }
1179    out.truncate(MAX_TRAPS);
1180    out
1181}
1182
1183pub(crate) fn slug(text: &str) -> String {
1184    let mut out = String::new();
1185    for c in text.chars() {
1186        if c.is_ascii_alphanumeric() {
1187            out.push(c.to_ascii_lowercase());
1188        } else if !out.ends_with('-') && !out.is_empty() {
1189            out.push('-');
1190        }
1191    }
1192    out.truncate(24);
1193    out.trim_end_matches('-').to_string()
1194}
1195
1196pub struct RecordOptions<'a> {
1197    pub repo: &'a Path,
1198    /// The command that runs the original; taken from the saved config when empty.
1199    pub run: &'a [String],
1200    pub inputs: Option<&'a Path>,
1201    /// Built-in normalizer names, or `name=regex` for your own.
1202    pub normalize: &'a [String],
1203    pub name: Option<&'a str>,
1204    pub traps: bool,
1205    pub timeout_secs: Option<u64>,
1206    /// The app is a server: record requests instead of command lines.
1207    pub http: bool,
1208    /// The port a server always listens on (implies `http`); unset, it gets a free one through
1209    /// `PORT` and `{port}`.
1210    pub port: Option<u16>,
1211    /// Numbers in the output match within this tolerance; kept from the last recording when
1212    /// `None`, removed with 0.
1213    pub float_tolerance: Option<f64>,
1214}
1215
1216#[derive(Debug, Serialize)]
1217pub struct RecordOutcome {
1218    pub dir: PathBuf,
1219    pub run: Vec<String>,
1220    pub cases: usize,
1221    pub examples: usize,
1222    pub inputs: usize,
1223    pub traps: usize,
1224    /// Cases where the two runs of the original differed.
1225    pub noisy: Vec<String>,
1226    /// What differed in each noisy case, and how: `values` became wildcards, `order` is compared
1227    /// in any order, `lines` became a `...` that matches anything.
1228    pub noise: Vec<Noise>,
1229    /// Cases whose exit code or written files differed between the two runs.
1230    pub unstable: Vec<String>,
1231    /// Cases not written: the original timed out or did not answer.
1232    pub timed_out: Vec<String>,
1233}
1234
1235struct Recorded {
1236    stdout: Vec<u8>,
1237    stderr: Vec<u8>,
1238    status: Status,
1239    written: BTreeMap<PathBuf, Vec<u8>>,
1240    binary: bool,
1241    noise: Vec<(String, NoiseKind)>,
1242    unstable: bool,
1243}
1244
1245/// How two runs of the original disagreed.
1246#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1247#[serde(rename_all = "lowercase")]
1248pub enum NoiseKind {
1249    /// Values within lines changed (times, ids): those parts are wildcards now.
1250    Values,
1251    /// The same lines came out in another order (hash maps, concurrency): replay compares them
1252    /// in any order, and a port must produce exactly those lines.
1253    Order,
1254    /// A different number of lines came out: that stretch is a `...` wildcard, which matches
1255    /// anything. Look at these first.
1256    Lines,
1257}
1258
1259#[derive(Debug, Clone, Serialize)]
1260pub struct Noise {
1261    pub case: String,
1262    pub field: String,
1263    pub kind: NoiseKind,
1264}
1265
1266fn same_lines_any_order(a: &str, b: &str) -> bool {
1267    let (mut la, mut lb) = (lines(a), lines(b));
1268    la.sort_unstable();
1269    lb.sort_unstable();
1270    la == lb
1271}
1272
1273pub(crate) fn settle_text(
1274    norm: &Normalizers,
1275    a: &[u8],
1276    b: &[u8],
1277) -> (Vec<u8>, Option<NoiseKind>, bool) {
1278    match (std::str::from_utf8(a), std::str::from_utf8(b)) {
1279        (Ok(a), Ok(b)) => {
1280            let (a, b) = (norm.apply(a), norm.apply(b));
1281            if a == b || (norm.key_order && norm.canonical(&a) == norm.canonical(&b)) {
1282                (a.into_bytes(), None, false)
1283            } else if same_lines_any_order(&a, &b) {
1284                (a.into_bytes(), Some(NoiseKind::Order), false)
1285            } else {
1286                let merged = merge_noise(&a, &b);
1287                let kind = if merged.split('\n').any(|l| l == "...") {
1288                    NoiseKind::Lines
1289                } else {
1290                    NoiseKind::Values
1291                };
1292                (merged.into_bytes(), Some(kind), false)
1293            }
1294        }
1295        _ => (a.to_vec(), (a != b).then_some(NoiseKind::Values), true),
1296    }
1297}
1298
1299fn settle(norm: &Normalizers, case: &Case, one: &Run, two: &Run) -> Recorded {
1300    let binary = [&one.stdout, &one.stderr, &two.stdout, &two.stderr]
1301        .iter()
1302        .any(|bytes| std::str::from_utf8(bytes).is_err());
1303    let settle_stream = |a: &[u8], b: &[u8]| {
1304        if binary {
1305            (a.to_vec(), (a != b).then_some(NoiseKind::Values))
1306        } else {
1307            let (bytes, noise, _) = settle_text(norm, a, b);
1308            (bytes, noise)
1309        }
1310    };
1311    let (stdout, out_noise) = settle_stream(&one.stdout, &two.stdout);
1312    let (stderr, err_noise) = settle_stream(&one.stderr, &two.stderr);
1313    let (w1, w2) = (one.written(case), two.written(case));
1314    let mut unstable = one.status != two.status
1315        || !w1.keys().eq(w2.keys())
1316        || (binary && (out_noise.is_some() || err_noise.is_some()));
1317    let mut noise: Vec<(String, NoiseKind)> = [("stdout", out_noise), ("stderr", err_noise)]
1318        .into_iter()
1319        .filter_map(|(f, k)| Some((f.to_string(), k?)))
1320        .collect();
1321    let mut written = BTreeMap::new();
1322    for (path, a) in &w1 {
1323        let b = w2.get(path).unwrap_or(a);
1324        let (bytes, file_noise, file_bin) = settle_text(norm, a, b);
1325        unstable |= file_bin && file_noise.is_some();
1326        if let Some(kind) = file_noise {
1327            noise.push((format!("file {}", path.display()), kind));
1328        }
1329        written.insert(path.clone(), bytes);
1330    }
1331    Recorded {
1332        stdout,
1333        stderr,
1334        status: one.status.clone(),
1335        written,
1336        binary,
1337        noise,
1338        unstable,
1339    }
1340}
1341
1342fn dotted() -> Table {
1343    let mut t = Table::new();
1344    t.set_dotted(true);
1345    t
1346}
1347
1348fn write_case(dir: &Path, bin: &str, name: &str, case: &Case, rec: &Recorded) -> Result<()> {
1349    for ext in ["stdin", "stdout", "stderr"] {
1350        let _ = std::fs::remove_file(dir.join(format!("{name}.{ext}")));
1351    }
1352    for ext in ["in", "out"] {
1353        let _ = std::fs::remove_dir_all(dir.join(format!("{name}.{ext}")));
1354    }
1355    let mut doc = DocumentMut::new();
1356    let mut bin_t = dotted();
1357    bin_t["name"] = value(bin);
1358    doc["bin"] = Item::Table(bin_t);
1359    let mut args = toml_edit::Array::new();
1360    for a in &case.args {
1361        args.push(a.as_str());
1362    }
1363    doc["args"] = value(args);
1364    if !case.env.is_empty() {
1365        let mut add = dotted();
1366        for (k, v) in &case.env {
1367            add[k.as_str()] = value(v.as_str());
1368        }
1369        let mut env = dotted();
1370        env.insert("add", Item::Table(add));
1371        doc["env"] = Item::Table(env);
1372    }
1373    match rec.status {
1374        Status::Code(code) => {
1375            let mut status = dotted();
1376            status["code"] = value(i64::from(code));
1377            doc["status"] = Item::Table(status);
1378        }
1379        _ => doc["status"] = value("interrupted"),
1380    }
1381    let mut fs = dotted();
1382    fs["sandbox"] = value(true);
1383    if !case.files.is_empty() {
1384        fs["base"] = value(format!("{name}.in"));
1385    }
1386    doc["fs"] = Item::Table(fs);
1387    if rec.binary {
1388        doc["binary"] = value(true);
1389    }
1390    std::fs::write(dir.join(format!("{name}.toml")), doc.to_string())?;
1391    if let Some(stdin) = &case.stdin {
1392        std::fs::write(dir.join(format!("{name}.stdin")), stdin)?;
1393    }
1394    std::fs::write(dir.join(format!("{name}.stdout")), &rec.stdout)?;
1395    std::fs::write(dir.join(format!("{name}.stderr")), &rec.stderr)?;
1396    for (sub, files) in [("in", &case.files), ("out", &rec.written)] {
1397        for (path, bytes) in files {
1398            let target = dir.join(format!("{name}.{sub}")).join(path);
1399            if let Some(parent) = target.parent() {
1400                std::fs::create_dir_all(parent)?;
1401            }
1402            std::fs::write(&target, bytes)?;
1403        }
1404    }
1405    Ok(())
1406}
1407
1408pub(crate) fn reserve_case_name(
1409    taken: &mut BTreeSet<String>,
1410    base: String,
1411    mut suffix: usize,
1412) -> String {
1413    let mut name = base.clone();
1414    while !taken.insert(name.clone()) {
1415        name = format!("{base}-{suffix}");
1416        suffix += 1;
1417    }
1418    name
1419}
1420
1421pub fn record(opts: &RecordOptions) -> Result<RecordOutcome> {
1422    let repo = opts
1423        .repo
1424        .canonical()
1425        .with_context(|| format!("no folder {}", opts.repo.display()))?;
1426    let existing = Config::load(&repo)?;
1427    let run = if !opts.run.is_empty() {
1428        opts.run.to_vec()
1429    } else if let Some(c) = &existing {
1430        c.run.clone()
1431    } else {
1432        bail!(
1433            "give the command that runs the original after `--`, e.g. `rust-anything app record . -- python3 cli.py`"
1434        );
1435    };
1436    let mut normalize = existing
1437        .as_ref()
1438        .map(|c| c.normalize.clone())
1439        .unwrap_or_default();
1440    let mut normalizers = existing
1441        .as_ref()
1442        .map(|c| c.normalizers.clone())
1443        .unwrap_or_default();
1444    for n in opts.normalize {
1445        if let Some((name, pattern)) = n.split_once('=') {
1446            normalizers.insert(name.to_string(), pattern.to_string());
1447        } else if !normalize.contains(n) {
1448            normalize.push(n.clone());
1449        }
1450    }
1451    let explicit = opts
1452        .name
1453        .map(str::to_string)
1454        .or_else(|| existing.as_ref().map(|c| c.name.clone()));
1455    let names = app_names(&repo, &run, explicit.as_deref());
1456    let mut config = Config {
1457        schema: SCHEMA.to_string(),
1458        name: explicit
1459            .or_else(|| names.first().cloned())
1460            .unwrap_or_else(|| "app".to_string()),
1461        run,
1462        normalize,
1463        normalizers,
1464        timeout_secs: opts
1465            .timeout_secs
1466            .or(existing.as_ref().map(|c| c.timeout_secs))
1467            .unwrap_or_else(default_timeout),
1468        http: opts
1469            .port
1470            .map(|port| crate::http::HttpConfig { port: Some(port) })
1471            .or_else(|| existing.as_ref().and_then(|c| c.http.clone()))
1472            .or_else(|| opts.http.then_some(crate::http::HttpConfig { port: None })),
1473        float_tolerance: match opts.float_tolerance {
1474            Some(t) => (crate::tolerance::check(t)? > 0.0).then_some(t),
1475            None => existing.as_ref().and_then(|c| c.float_tolerance),
1476        },
1477        unordered: BTreeMap::new(),
1478    };
1479    let norm = Normalizers::new(&config)?;
1480    if config.http.is_some() {
1481        let outcome = crate::http::record(&repo, &config, &norm, opts)?;
1482        config.unordered = unordered_of(&outcome.noise);
1483        std::fs::write(
1484            cases_dir(&repo).join(CONFIG_FILE),
1485            serde_json::to_string_pretty(&config)? + "\n",
1486        )?;
1487        return Ok(outcome);
1488    }
1489
1490    let examples = find_examples(&repo, &names);
1491    let inputs = match opts.inputs {
1492        Some(path) => read_inputs(path)?,
1493        None => Vec::new(),
1494    };
1495    let mut planned: Vec<(String, Case)> = Vec::new();
1496    let mut seen = BTreeSet::new();
1497    let mut taken = BTreeSet::new();
1498    let mut push = |prefix: &str, n: usize, given: Option<String>, case: Case| {
1499        if !seen.insert(case.key()) {
1500            return false;
1501        }
1502        let base_name = match given {
1503            Some(g) if !slug(&g).is_empty() => slug(&g),
1504            _ => match case.args.first().map(|a| slug(a)).filter(|s| !s.is_empty()) {
1505                Some(s) => format!("{prefix}-{n:03}-{s}"),
1506                None => format!("{prefix}-{n:03}"),
1507            },
1508        };
1509        let name = reserve_case_name(&mut taken, base_name, n);
1510        planned.push((name, case));
1511        true
1512    };
1513    let mut bases = Vec::new();
1514    let mut counts = [0usize; 3];
1515    for case in examples {
1516        if push("example", counts[0] + 1, None, case.clone()) {
1517            counts[0] += 1;
1518            bases.push(case);
1519        }
1520    }
1521    for (given, case) in inputs {
1522        if push("input", counts[1] + 1, given, case.clone()) {
1523            counts[1] += 1;
1524            bases.push(case);
1525        }
1526    }
1527    if bases.is_empty() {
1528        let case = Case::new(Vec::new());
1529        push("example", 1, Some("no-args".to_string()), case.clone());
1530        bases.push(case);
1531    }
1532    if opts.traps {
1533        for case in trap_cases(&bases) {
1534            if push("trap", counts[2] + 1, None, case) {
1535                counts[2] += 1;
1536            }
1537        }
1538    }
1539
1540    let timeout = Duration::from_secs(config.timeout_secs);
1541    let runs = par_map(&planned, |(_, case)| -> Result<(Run, Run)> {
1542        let one = run_case(&config.run, &repo, case, timeout)?;
1543        let two = run_case(&config.run, &repo, case, timeout)?;
1544        Ok((one, two))
1545    });
1546    let dir = cases_dir(&repo);
1547    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
1548    let mut outcome = RecordOutcome {
1549        dir: dir.clone(),
1550        run: config.run.clone(),
1551        cases: 0,
1552        examples: counts[0],
1553        inputs: counts[1],
1554        traps: counts[2],
1555        noisy: Vec::new(),
1556        noise: Vec::new(),
1557        unstable: Vec::new(),
1558        timed_out: Vec::new(),
1559    };
1560    for ((name, case), runs) in planned.iter().zip(runs) {
1561        let (one, two) = runs?;
1562        if one.status == Status::Timeout || two.status == Status::Timeout {
1563            outcome.timed_out.push(name.clone());
1564            continue;
1565        }
1566        let rec = settle(&norm, case, &one, &two);
1567        write_case(&dir, &config.name, name, case, &rec)?;
1568        outcome.cases += 1;
1569        if !rec.noise.is_empty() {
1570            outcome.noisy.push(name.clone());
1571        }
1572        outcome
1573            .noise
1574            .extend(rec.noise.iter().map(|(field, kind)| Noise {
1575                case: name.clone(),
1576                field: field.clone(),
1577                kind: *kind,
1578            }));
1579        if rec.unstable {
1580            outcome.unstable.push(name.clone());
1581        }
1582    }
1583    config.unordered = unordered_of(&outcome.noise);
1584    std::fs::write(
1585        dir.join(CONFIG_FILE),
1586        serde_json::to_string_pretty(&config)? + "\n",
1587    )?;
1588    Ok(outcome)
1589}
1590
1591fn unordered_of(noise: &[Noise]) -> BTreeMap<String, Vec<String>> {
1592    let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new();
1593    for n in noise.iter().filter(|n| n.kind == NoiseKind::Order) {
1594        out.entry(n.case.clone()).or_default().push(n.field.clone());
1595    }
1596    out
1597}
1598
1599enum Expect {
1600    Code(i32),
1601    Failed,
1602    Killed,
1603    Skip,
1604}
1605
1606struct Spec {
1607    name: String,
1608    case: Case,
1609    stdout: Option<Vec<u8>>,
1610    stderr: Option<Vec<u8>>,
1611    status: Expect,
1612    out_dir: Option<PathBuf>,
1613    binary: bool,
1614}
1615
1616fn read_files(base: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
1617    walk_files(base)
1618        .into_iter()
1619        .map(|p| {
1620            let rel = p.strip_prefix(base).unwrap_or(&p).to_path_buf();
1621            let bytes = std::fs::read(&p).unwrap_or_default();
1622            (rel, bytes)
1623        })
1624        .collect()
1625}
1626
1627fn load_spec(dir: &Path, path: &Path) -> Result<Spec> {
1628    let name = path
1629        .file_stem()
1630        .map(|s| s.to_string_lossy().into_owned())
1631        .unwrap_or_default();
1632    let text =
1633        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
1634    let doc: DocumentMut = text
1635        .parse()
1636        .with_context(|| format!("parsing {}", path.display()))?;
1637    let args = match doc.get("args") {
1638        Some(item) if item.as_array().is_some() => item
1639            .as_array()
1640            .into_iter()
1641            .flatten()
1642            .map(|v| {
1643                v.as_str()
1644                    .map(str::to_string)
1645                    .unwrap_or_else(|| v.to_string())
1646            })
1647            .collect(),
1648        Some(item) => shell_split(item.as_str().unwrap_or_default())?,
1649        None => Vec::new(),
1650    };
1651    let mut case = Case::new(args);
1652    let side = |key: &str| -> Result<Option<Vec<u8>>> {
1653        if let Some(s) = doc.get(key).and_then(Item::as_str) {
1654            return Ok(Some(s.as_bytes().to_vec()));
1655        }
1656        let file = dir.join(format!("{name}.{key}"));
1657        Ok(if file.exists() {
1658            Some(std::fs::read(&file).with_context(|| format!("reading {}", file.display()))?)
1659        } else {
1660            None
1661        })
1662    };
1663    case.stdin = side("stdin")?;
1664    if let Some(env) = doc.get("env") {
1665        case.inherit_env = env.get("inherit").and_then(Item::as_bool).unwrap_or(true);
1666        if let Some(add) = env.get("add").and_then(Item::as_table_like) {
1667            for (k, v) in add.iter() {
1668                case.env
1669                    .insert(k.to_string(), v.as_str().unwrap_or_default().to_string());
1670            }
1671        }
1672        if let Some(remove) = env.get("remove").and_then(Item::as_array) {
1673            case.env_remove = remove
1674                .iter()
1675                .filter_map(|v| v.as_str().map(str::to_string))
1676                .collect();
1677        }
1678    }
1679    let base = doc
1680        .get("fs")
1681        .and_then(|f| f.get("base"))
1682        .and_then(Item::as_str)
1683        .map(|b| dir.join(b))
1684        .unwrap_or_else(|| dir.join(format!("{name}.in")));
1685    if base.is_dir() {
1686        case.files = read_files(&base);
1687    }
1688    let status = match doc.get("status") {
1689        None => Expect::Code(0),
1690        Some(item) => match (item.as_str(), item.get("code").and_then(Item::as_integer)) {
1691            (Some("success"), _) => Expect::Code(0),
1692            (Some("failed"), _) => Expect::Failed,
1693            (Some("interrupted"), _) => Expect::Killed,
1694            (Some("skipped"), _) => Expect::Skip,
1695            (_, Some(code)) => Expect::Code(i32::try_from(code).unwrap_or(i32::MAX)),
1696            _ => bail!("{}: unknown `status`", path.display()),
1697        },
1698    };
1699    let out_dir = dir.join(format!("{name}.out"));
1700    Ok(Spec {
1701        stdout: side("stdout")?,
1702        stderr: side("stderr")?,
1703        status,
1704        out_dir: out_dir.is_dir().then_some(out_dir),
1705        binary: doc.get("binary").and_then(Item::as_bool).unwrap_or(false),
1706        name,
1707        case,
1708    })
1709}
1710
1711pub(crate) fn compare(
1712    norm: &Normalizers,
1713    expected: &[u8],
1714    actual: &[u8],
1715    binary: bool,
1716    unordered: bool,
1717) -> Option<String> {
1718    if !binary && let (Ok(e), Ok(a)) = (std::str::from_utf8(expected), std::str::from_utf8(actual))
1719    {
1720        let e = norm.canonical(&norm.apply(e));
1721        let a = norm.canonical(&norm.apply(a));
1722        let tol = norm.float_tolerance;
1723        if unordered {
1724            let (mut el, mut al) = (lines(&e), lines(&a));
1725            el.sort_unstable();
1726            al.sort_unstable();
1727            let same = el.len() == al.len()
1728                && el
1729                    .iter()
1730                    .zip(&al)
1731                    .all(|(x, y)| line_matches_within(x, y, tol));
1732            return (!same).then(|| {
1733                format!(
1734                    "(lines compared in any order: the original's own runs disagreed on it)\n{}",
1735                    render_diff(&el.join("\n"), &al.join("\n"), tol)
1736                )
1737            });
1738        }
1739        return (!text_matches(&e, &a, tol)).then(|| render_diff(&e, &a, tol));
1740    }
1741    (expected != actual).then(|| {
1742        format!(
1743            "binary content differs ({} bytes expected, {} bytes got)\n",
1744            expected.len(),
1745            actual.len()
1746        )
1747    })
1748}
1749
1750pub struct ReplayOptions<'a> {
1751    pub repo: &'a Path,
1752    /// Command line of the build to test; the original's command when `None`.
1753    pub build: Option<&'a str>,
1754    pub timeout_secs: Option<u64>,
1755    /// Servers: the port the build listens on, when it is fixed.
1756    pub port: Option<u16>,
1757    /// Replay only this case (a library: only this unit).
1758    pub case: Option<&'a str>,
1759}
1760
1761pub(crate) fn only_case<T>(
1762    items: Vec<T>,
1763    case: Option<&str>,
1764    name: impl Fn(&T) -> &str,
1765) -> Result<Vec<T>> {
1766    let Some(case) = case else {
1767        return Ok(items);
1768    };
1769    let names: Vec<String> = items.iter().map(|i| name(i).to_string()).collect();
1770    let kept: Vec<T> = items.into_iter().filter(|i| name(i) == case).collect();
1771    ensure!(
1772        !kept.is_empty(),
1773        "no case named {case}; the cases are: {}",
1774        names.join(", ")
1775    );
1776    Ok(kept)
1777}
1778
1779#[derive(Debug, Serialize)]
1780pub struct Problem {
1781    pub field: String,
1782    pub detail: String,
1783}
1784
1785#[derive(Debug, Serialize)]
1786pub struct Failure {
1787    pub case: String,
1788    pub args: Vec<String>,
1789    pub problems: Vec<Problem>,
1790}
1791
1792/// Cases the build handed to the original: the front door appends a line to the file named by
1793/// `RUST_ANYTHING_FALLBACK_LOG` for every fallback (and may create it empty to report none).
1794#[derive(Debug, Serialize)]
1795pub struct Fallback {
1796    pub cases: usize,
1797    pub total: usize,
1798    pub rate: f64,
1799    /// The cases that fell back.
1800    pub names: Vec<String>,
1801}
1802
1803#[derive(Debug, Serialize)]
1804pub struct ReplayOutcome {
1805    pub build: Vec<String>,
1806    pub passed: usize,
1807    pub total: usize,
1808    pub skipped: usize,
1809    pub failures: Vec<Failure>,
1810    pub fallback: Option<Fallback>,
1811    pub report: PathBuf,
1812}
1813
1814fn check(
1815    norm: &Normalizers,
1816    command: &[String],
1817    repo: &Path,
1818    spec: &Spec,
1819    timeout: Duration,
1820) -> Result<(Vec<Problem>, Option<bool>)> {
1821    let run = run_case(command, repo, &spec.case, timeout)?;
1822    let mut problems = Vec::new();
1823    let status_ok = match (&spec.status, &run.status) {
1824        (Expect::Code(e), Status::Code(a)) => e == a,
1825        (Expect::Failed, Status::Code(a)) => *a != 0,
1826        (Expect::Killed, Status::Killed) | (Expect::Skip, _) => true,
1827        _ => false,
1828    };
1829    if !status_ok {
1830        let expected = match &spec.status {
1831            Expect::Code(c) => format!("exit code {c}"),
1832            Expect::Failed => "a non-zero exit code".to_string(),
1833            Expect::Killed => "killed by a signal".to_string(),
1834            Expect::Skip => String::new(),
1835        };
1836        problems.push(Problem {
1837            field: "status".to_string(),
1838            detail: format!("expected {expected}, got {}\n", run.status),
1839        });
1840    }
1841    for (field, expected, actual) in [
1842        ("stdout", &spec.stdout, &run.stdout),
1843        ("stderr", &spec.stderr, &run.stderr),
1844    ] {
1845        if let Some(expected) = expected
1846            && let Some(detail) = compare(
1847                norm,
1848                expected,
1849                actual,
1850                spec.binary,
1851                norm.unordered(&spec.name, field),
1852            )
1853        {
1854            problems.push(Problem {
1855                field: field.to_string(),
1856                detail,
1857            });
1858        }
1859    }
1860    if let Some(out_dir) = &spec.out_dir {
1861        for (path, expected) in read_files(out_dir) {
1862            let field = format!("file {}", path.display());
1863            match run.files.get(&path) {
1864                None => problems.push(Problem {
1865                    field,
1866                    detail: "not written\n".to_string(),
1867                }),
1868                Some(actual) => {
1869                    let unordered = norm.unordered(&spec.name, &field);
1870                    if let Some(detail) = compare(norm, &expected, actual, false, unordered) {
1871                        problems.push(Problem { field, detail });
1872                    }
1873                }
1874            }
1875        }
1876    }
1877    Ok((problems, run.fallback))
1878}
1879
1880pub(crate) fn report_markdown(outcome: &ReplayOutcome) -> String {
1881    let mut out = String::from("# App replay\n\n");
1882    out += &format!(
1883        "Build: `{}`\n\n",
1884        outcome
1885            .build
1886            .iter()
1887            .map(|w| shell_quote(w))
1888            .collect::<Vec<_>>()
1889            .join(" ")
1890    );
1891    out += &format!("Passed: {}/{}\n\n", outcome.passed, outcome.total);
1892    if outcome.skipped > 0 {
1893        out += &format!("Skipped: {}\n\n", outcome.skipped);
1894    }
1895    out += &match &outcome.fallback {
1896        Some(f) => format!(
1897            "Fallback rate: {:.1}% ({}/{} cases answered by the original)\n\n",
1898            f.rate * 100.0,
1899            f.cases,
1900            f.total
1901        ),
1902        None => "Fallback rate: not reported by this build\n\n".to_string(),
1903    };
1904    if outcome.failures.is_empty() {
1905        out += "Every case matches.\n";
1906        return out;
1907    }
1908    out += "## Failing cases\n";
1909    for f in &outcome.failures {
1910        out += &format!(
1911            "\n### {}\n\nArguments: `{}`\n",
1912            f.case,
1913            f.args
1914                .iter()
1915                .map(|w| shell_quote(w))
1916                .collect::<Vec<_>>()
1917                .join(" ")
1918        );
1919        for p in &f.problems {
1920            out += &format!(
1921                "\n{}:\n\n```diff\n{}```\n",
1922                p.field,
1923                p.detail.replace("```", "`\u{200b}``")
1924            );
1925        }
1926    }
1927    out
1928}
1929
1930fn load_specs(dir: &Path) -> Result<Vec<Spec>> {
1931    let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
1932        .with_context(|| {
1933            format!(
1934                "no cases in {}: run `rust-anything app record` first",
1935                dir.display()
1936            )
1937        })?
1938        .flatten()
1939        .map(|e| e.path())
1940        .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "toml"))
1941        .collect();
1942    paths.sort();
1943    let specs = paths
1944        .iter()
1945        .map(|p| load_spec(dir, p))
1946        .collect::<Result<Vec<_>>>()?;
1947    ensure!(
1948        !specs.is_empty(),
1949        "no cases in {}: run `rust-anything app record` first",
1950        dir.display()
1951    );
1952    Ok(specs)
1953}
1954
1955/// The recorded cases' arguments, each with whether the original exited 0.
1956pub(crate) fn recorded_args(repo: &Path) -> Result<Vec<(Vec<String>, bool)>> {
1957    Ok(load_specs(&cases_dir(repo))?
1958        .into_iter()
1959        .map(|s| (s.case.args, matches!(s.status, Expect::Code(0))))
1960        .collect())
1961}
1962
1963pub fn replay(opts: &ReplayOptions) -> Result<ReplayOutcome> {
1964    let repo = opts
1965        .repo
1966        .canonical()
1967        .with_context(|| format!("no folder {}", opts.repo.display()))?;
1968    let dir = cases_dir(&repo);
1969    let config = Config::load(&repo)?;
1970    if config.is_none()
1971        && let Ok(state) = crate::front_door::State::load(&repo)
1972        && state.kind == crate::front_door::AppKind::Library
1973    {
1974        ensure!(
1975            opts.build.is_none(),
1976            "{} is a library: its cases replay through each unit's bindings, so --build does not apply",
1977            state.name
1978        );
1979        return crate::library::replay(&repo, &state, opts.case);
1980    }
1981    let command = match (opts.build, &config) {
1982        (Some(build), _) => shell_split(build)?,
1983        (None, Some(c)) => c.run.clone(),
1984        (None, None) => bail!(
1985            "no {} in {}: run `rust-anything app record` first, or pass --build",
1986            CONFIG_FILE,
1987            dir.display()
1988        ),
1989    };
1990    ensure!(!command.is_empty(), "the build command is empty");
1991    let config = config.unwrap_or_else(|| Config {
1992        schema: SCHEMA.to_string(),
1993        name: "app".to_string(),
1994        run: Vec::new(),
1995        normalize: Vec::new(),
1996        normalizers: BTreeMap::new(),
1997        timeout_secs: default_timeout(),
1998        http: None,
1999        float_tolerance: None,
2000        unordered: BTreeMap::new(),
2001    });
2002    let norm = Normalizers::new(&config)?;
2003    let timeout = Duration::from_secs(opts.timeout_secs.unwrap_or(config.timeout_secs));
2004    if config.http.is_some() {
2005        return crate::http::replay(
2006            &repo, &config, &norm, &command, opts.port, opts.case, timeout,
2007        );
2008    }
2009    let specs = only_case(load_specs(&dir)?, opts.case, |s| &s.name)?;
2010    let results = par_map(&specs, |spec| {
2011        if matches!(spec.status, Expect::Skip) {
2012            return Ok((Vec::new(), None));
2013        }
2014        check(&norm, &command, &repo, spec, timeout)
2015    });
2016    let mut outcome = ReplayOutcome {
2017        build: command.clone(),
2018        passed: 0,
2019        total: 0,
2020        skipped: 0,
2021        failures: Vec::new(),
2022        fallback: None,
2023        report: dir.join(REPORT_FILE),
2024    };
2025    let (mut reported, mut fell_back) = (false, Vec::new());
2026    for (spec, result) in specs.iter().zip(results) {
2027        if matches!(spec.status, Expect::Skip) {
2028            outcome.skipped += 1;
2029            continue;
2030        }
2031        let (problems, fallback) = result?;
2032        outcome.total += 1;
2033        reported |= fallback.is_some();
2034        if fallback == Some(true) {
2035            fell_back.push(spec.name.clone());
2036        }
2037        if problems.is_empty() {
2038            outcome.passed += 1;
2039        } else {
2040            outcome.failures.push(Failure {
2041                case: spec.name.clone(),
2042                args: spec.case.args.clone(),
2043                problems,
2044            });
2045        }
2046    }
2047    if reported {
2048        outcome.fallback = Some(Fallback {
2049            cases: fell_back.len(),
2050            total: outcome.total,
2051            rate: fell_back.len() as f64 / outcome.total.max(1) as f64,
2052            names: fell_back,
2053        });
2054    }
2055    std::fs::write(&outcome.report, report_markdown(&outcome))
2056        .with_context(|| format!("writing {}", outcome.report.display()))?;
2057    Ok(outcome)
2058}
2059
2060#[cfg(test)]
2061mod tests {
2062    use super::*;
2063
2064    fn text_matches_exact(e: &str, a: &str) -> bool {
2065        text_matches(e, a, None)
2066    }
2067
2068    #[cfg(unix)]
2069    #[test]
2070    fn replay_deadline_covers_descendants_that_keep_pipes_open() {
2071        for script in ["sleep 6 & wait", "sleep 6 & exit 0"] {
2072            let command = ["/bin/sh".into(), "-c".into(), script.into()];
2073            let start = Instant::now();
2074            let run = run_case(
2075                &command,
2076                Path::new("."),
2077                &Case::new(Vec::new()),
2078                Duration::from_millis(200),
2079            )
2080            .unwrap();
2081            assert!(start.elapsed() < Duration::from_secs(3), "{script}");
2082            assert!(run.status == Status::Timeout, "{script}: {}", run.status);
2083        }
2084    }
2085
2086    #[test]
2087    fn matching_follows_trycmd() {
2088        assert!(text_matches_exact("a\nb\n", "a\nb\n"));
2089        assert!(text_matches_exact("now: [..]\n", "now: 1234\n"));
2090        assert!(text_matches_exact("x [..] y [..] z\n", "x 1 y 2 y 3 z\n"));
2091        assert!(!text_matches_exact("x [..] z\n", "x 1 y\n"));
2092        assert!(text_matches_exact(
2093            "head\n...\ntail\n",
2094            "head\n1\n2\ntail\n"
2095        ));
2096        assert!(text_matches_exact("head\n...\ntail\n", "head\ntail\n"));
2097        assert!(!text_matches_exact("head\ntail\n", "head\nmid\ntail\n"));
2098        assert!(text_matches_exact("a\r\nb", "a\nb\n"));
2099    }
2100
2101    #[test]
2102    fn numbers_match_within_the_tolerance() {
2103        let e = "step 1\nenergy 0.3\nat [..]\n";
2104        let a = "step 1\nenergy 0.30000000000000004\nat 12:00\n";
2105        assert!(!text_matches(e, a, None));
2106        assert!(text_matches(e, a, Some(1e-9)));
2107        assert!(!text_matches(
2108            e,
2109            "step 2\nenergy 0.3\nat 12:00\n",
2110            Some(1e-9)
2111        ));
2112        assert!(!render_diff(e, a, Some(1e-9)).contains("energy"));
2113    }
2114
2115    #[cfg(unix)]
2116    #[test]
2117    fn binary_capture_replays_its_text_companion_byte_for_byte() {
2118        let repo = temp_dir("binary-stream-pair").unwrap();
2119        let run = [
2120            "/bin/sh".to_string(),
2121            "-c".to_string(),
2122            r"printf '\377'; printf 'at 2026-11-16T10:00:00Z\n' >&2".to_string(),
2123        ];
2124        let recorded = record(&RecordOptions {
2125            repo: &repo,
2126            run: &run,
2127            inputs: None,
2128            normalize: &["timestamps".into()],
2129            name: None,
2130            traps: false,
2131            timeout_secs: None,
2132            http: false,
2133            port: None,
2134            float_tolerance: None,
2135        })
2136        .unwrap();
2137        assert_eq!(recorded.cases, 1);
2138        let replayed = replay(&ReplayOptions {
2139            repo: &repo,
2140            build: None,
2141            timeout_secs: None,
2142            port: None,
2143            case: None,
2144        })
2145        .unwrap();
2146        assert_eq!(
2147            (replayed.passed, replayed.total),
2148            (1, 1),
2149            "{:?}",
2150            replayed.failures
2151        );
2152        std::fs::remove_dir_all(repo).unwrap();
2153    }
2154
2155    #[test]
2156    fn noise_is_classified() {
2157        let norm = Normalizers::new(&Config {
2158            schema: SCHEMA.to_string(),
2159            name: "app".to_string(),
2160            run: Vec::new(),
2161            normalize: Vec::new(),
2162            normalizers: BTreeMap::new(),
2163            timeout_secs: 30,
2164            http: None,
2165            float_tolerance: None,
2166            unordered: BTreeMap::new(),
2167        })
2168        .unwrap();
2169        let kind = |a: &str, b: &str| settle_text(&norm, a.as_bytes(), b.as_bytes()).1;
2170        assert_eq!(kind("a\nb\n", "a\nb\n"), None);
2171        assert_eq!(kind("x=1\ny=2\n", "y=2\nx=1\n"), Some(NoiseKind::Order));
2172        assert_eq!(kind("at 10:01\n", "at 10:02\n"), Some(NoiseKind::Values));
2173        assert_eq!(kind("a\nz\n", "a\nb\nc\nz\n"), Some(NoiseKind::Lines));
2174        let (kept, _, _) = settle_text(&norm, b"x=1\ny=2\n", b"y=2\nx=1\n");
2175        assert_eq!(kept, b"x=1\ny=2\n", "order noise keeps the lines exactly");
2176    }
2177
2178    #[test]
2179    fn unordered_output_matches_in_any_order_but_not_other_lines() {
2180        let norm = Normalizers::new(&Config {
2181            schema: SCHEMA.to_string(),
2182            name: "app".to_string(),
2183            run: Vec::new(),
2184            normalize: Vec::new(),
2185            normalizers: BTreeMap::new(),
2186            timeout_secs: 30,
2187            http: None,
2188            float_tolerance: None,
2189            unordered: BTreeMap::from([("c".to_string(), vec!["stdout".to_string()])]),
2190        })
2191        .unwrap();
2192        assert!(norm.unordered("c", "stdout"));
2193        assert!(!norm.unordered("c", "stderr"));
2194        let e = b"x=1\ny=2\n";
2195        assert!(compare(&norm, e, b"y=2\nx=1\n", false, true).is_none());
2196        assert!(compare(&norm, e, b"y=2\nx=2\n", false, true).is_some());
2197        assert!(compare(&norm, e, b"x=1\n", false, true).is_some());
2198        assert!(compare(&norm, e, b"y=2\nx=1\n", false, false).is_some());
2199    }
2200
2201    #[test]
2202    fn noise_becomes_wildcards() {
2203        assert_eq!(
2204            merge_noise(
2205                "start\nnow: 2026-11-16 10:00:01\nend\n",
2206                "start\nnow: 2026-11-16 10:00:02\nend\n"
2207            ),
2208            "start\nnow: 2026-11-16 10:00:[..]\nend\n"
2209        );
2210        assert_eq!(merge_noise("a\nb\nz\n", "a\nc\nd\nz\n"), "a\n...\nz\n");
2211        assert_eq!(merge_line("id=ab12 ok", "id=cd34 ok"), "id=[..] ok");
2212        let merged = merge_noise("x 1\n", "x 2\n");
2213        assert!(text_matches_exact(&merged, "x 3\n"));
2214    }
2215
2216    #[test]
2217    fn normalizers_by_name() {
2218        let mut config = Config {
2219            schema: SCHEMA.to_string(),
2220            name: "app".to_string(),
2221            run: Vec::new(),
2222            normalize: vec!["timestamps".into(), "uuids".into(), "key-order".into()],
2223            normalizers: BTreeMap::from([("req".to_string(), r"req-\d+".to_string())]),
2224            timeout_secs: 30,
2225            http: None,
2226            float_tolerance: None,
2227            unordered: BTreeMap::new(),
2228        };
2229        let norm = Normalizers::new(&config).unwrap();
2230        assert_eq!(
2231            norm.apply(
2232                "at 2026-11-16T10:00:00.123Z id 123e4567-e89b-12d3-a456-426614174000 req-77"
2233            ),
2234            "at [..] id [..] [..]"
2235        );
2236        assert_eq!(
2237            norm.canonical("{\"b\":1,\"a\":{\"d\":2,\"c\":3}}\nplain"),
2238            "{\"a\":{\"c\":3,\"d\":2},\"b\":1}\nplain"
2239        );
2240        config.normalize.push("nope".into());
2241        assert!(Normalizers::new(&config).is_err());
2242    }
2243
2244    #[test]
2245    fn examples_become_cases() {
2246        let repo = temp_dir("examples").unwrap();
2247        std::fs::write(repo.join("in.txt"), "hello\n").unwrap();
2248        std::fs::write(
2249            repo.join("README.md"),
2250            "# 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",
2251        )
2252        .unwrap();
2253        let names = vec!["tool".to_string()];
2254        let cases = find_examples(&repo, &names);
2255        let args: Vec<Vec<String>> = cases.iter().map(|c| c.args.clone()).collect();
2256        assert_eq!(
2257            args,
2258            [
2259                vec!["count", "in.txt"],
2260                vec!["words"],
2261                vec!["upper", "x y"],
2262                vec!["sort"],
2263            ]
2264        );
2265        assert_eq!(cases[0].files[Path::new("in.txt")], b"hello\n");
2266        assert_eq!(cases[1].stdin.as_deref(), Some(&b"a b\n"[..]));
2267        assert_eq!(cases[2].env["LANG"], "C");
2268        assert_eq!(cases[3].stdin.as_deref(), Some(&b"hello\n"[..]));
2269        std::fs::remove_dir_all(&repo).unwrap();
2270    }
2271
2272    #[test]
2273    fn traps_keep_the_shape_of_the_case() {
2274        let mut base = Case::new(vec!["div".into(), "7".into(), "2".into()]);
2275        base.stdin = Some(b"{\"a\":1}".to_vec());
2276        let traps = trap_cases(&[base]);
2277        assert!(traps.iter().all(|c| c.args[0] == "div"));
2278        assert!(traps.iter().any(|c| c.args == ["div", "-7", "2"]));
2279        assert!(traps.iter().any(|c| c.args == ["div", "7", "0"]));
2280        assert!(
2281            traps
2282                .iter()
2283                .any(|c| c.stdin.as_deref() == Some(JSON_TRAPS[0].as_bytes()))
2284        );
2285        let text = trap_cases(&[Case::new(vec!["upper".into(), "hi".into()])]);
2286        assert!(text.iter().any(|c| c.args[1] == "👍🏽 thumbs"));
2287    }
2288
2289    #[cfg(unix)]
2290    #[test]
2291    fn recording_keeps_all_cases_when_a_generated_name_is_already_used() {
2292        let repo = temp_dir("case-name-collisions").unwrap();
2293        let inputs = repo.join("cases.jsonl");
2294        std::fs::write(
2295            &inputs,
2296            concat!(
2297                "{\"name\":\"x\",\"args\":[\"one\"]}\n",
2298                "{\"name\":\"x-3\",\"args\":[\"two\"]}\n",
2299                "{\"name\":\"x\",\"args\":[\"three\"]}\n"
2300            ),
2301        )
2302        .unwrap();
2303        let recorded = record(&RecordOptions {
2304            repo: &repo,
2305            run: &["/bin/echo".into()],
2306            inputs: Some(&inputs),
2307            normalize: &[],
2308            name: None,
2309            traps: false,
2310            timeout_secs: None,
2311            http: false,
2312            port: None,
2313            float_tolerance: None,
2314        })
2315        .unwrap();
2316        let read = |name: &str| std::fs::read_to_string(recorded.dir.join(name)).unwrap();
2317        assert_eq!(recorded.cases, 3);
2318        assert_eq!(read("x.stdout"), "one\n");
2319        assert_eq!(read("x-3.stdout"), "two\n");
2320        assert_eq!(read("x-4.stdout"), "three\n");
2321        std::fs::remove_dir_all(repo).unwrap();
2322    }
2323
2324    #[test]
2325    fn names_come_from_the_run_command_and_manifests() {
2326        let repo = temp_dir("names").unwrap();
2327        std::fs::create_dir_all(repo.join("out")).unwrap();
2328        std::fs::write(
2329            repo.join("package.json"),
2330            r#"{"name":"x","bin":{"mytool":"b.js"}}"#,
2331        )
2332        .unwrap();
2333        let run: Vec<String> = ["java", "-cp", "out", "Tcli"].map(String::from).to_vec();
2334        assert_eq!(app_names(&repo, &run, None), ["tcli", "mytool"]);
2335        std::fs::remove_dir_all(&repo).unwrap();
2336    }
2337
2338    #[test]
2339    fn python_program_names_are_case_insensitive() {
2340        assert!(is_python_program("PYTHON"));
2341        assert!(is_python_program("/tools/Python3.exe"));
2342        assert!(is_python_program("Py.cmd"));
2343        assert!(!is_python_program("pythonw.exe"));
2344    }
2345
2346    #[test]
2347    fn shell_words() {
2348        assert_eq!(
2349            shell_split(r#"cargo run -q -- "a b" 'c d' e\ f"#).unwrap(),
2350            ["cargo", "run", "-q", "--", "a b", "c d", "e f"]
2351        );
2352        assert!(shell_split("a | b").is_err());
2353        assert!(shell_tokens("echo $(date)").is_none());
2354        assert!(shell_tokens("echo `date`").is_none());
2355        assert_eq!(
2356            shell_split(r"echo \$(date) \`date\`").unwrap(),
2357            ["echo", "$(date)", "`date`"]
2358        );
2359        #[cfg(windows)]
2360        assert_eq!(
2361            shell_split(r"C:\tools\rust-anything\app.exe --flag").unwrap(),
2362            [r"C:\tools\rust-anything\app.exe", "--flag"]
2363        );
2364        #[cfg(windows)]
2365        assert_eq!(
2366            shell_split(r"run C:\$cache\tool.exe").unwrap(),
2367            ["run", r"C:\$cache\tool.exe"]
2368        );
2369        #[cfg(windows)]
2370        assert_eq!(
2371            shell_split(r"\\server\share\tool.exe --flag").unwrap(),
2372            [r"\\server\share\tool.exe", "--flag"]
2373        );
2374        assert_eq!(shell_split(r"echo one\\two").unwrap(), ["echo", r"one\two"]);
2375    }
2376}