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