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