Skip to main content

rust_anything/
app.rs

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