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        for raw in text.lines() {
1252            let line = raw.trim();
1253            if markdown {
1254                if line.starts_with("```") || line.starts_with("~~~") {
1255                    fence = match fence {
1256                        Some(_) => None,
1257                        None => Some(
1258                            line.trim_start_matches(['`', '~'])
1259                                .split_whitespace()
1260                                .next()
1261                                .unwrap_or_default()
1262                                .to_lowercase(),
1263                        ),
1264                    };
1265                    continue;
1266                }
1267                let Some(lang) = &fence else { continue };
1268                let candidate = match line.strip_prefix("$ ") {
1269                    Some(rest) => rest,
1270                    None if matches!(lang.as_str(), "sh" | "bash" | "shell" | "zsh") => line,
1271                    None => continue,
1272                };
1273                if let Some(case) = parse(candidate, doc_dir) {
1274                    out.push(case);
1275                }
1276            } else {
1277                let candidate = line.strip_prefix("$ ").unwrap_or(line);
1278                if let Some(case) = parse(candidate, doc_dir) {
1279                    out.push(case);
1280                }
1281            }
1282        }
1283    }
1284    out
1285}
1286
1287fn read_inputs(path: &Path) -> Result<Vec<(Option<String>, Case)>> {
1288    let text =
1289        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
1290    let mut out = Vec::new();
1291    for (n, line) in text.lines().enumerate() {
1292        if line.trim().is_empty() {
1293            continue;
1294        }
1295        let input: Input = serde_json::from_str(line)
1296            .with_context(|| format!("{}:{}: expected {{\"args\": [...], \"stdin\": ..., \"env\": {{...}}, \"files\": {{path: text}}}}", path.display(), n + 1))?;
1297        let mut case = Case::new(input.args);
1298        case.stdin = input.stdin.map(String::into_bytes);
1299        case.env = input.env;
1300        for (file, content) in input.files {
1301            ensure!(
1302                safe_relative(&file),
1303                "{}:{}: file `{file}` must be a relative path inside the sandbox",
1304                path.display(),
1305                n + 1
1306            );
1307            case.files.insert(PathBuf::from(file), content.into_bytes());
1308        }
1309        for file in input.remove {
1310            ensure!(
1311                safe_relative(&file),
1312                "{}:{}: removed `{file}` must be a relative path inside the sandbox",
1313                path.display(),
1314                n + 1
1315            );
1316            case.remove.push(PathBuf::from(file));
1317        }
1318        out.push((input.name, case));
1319    }
1320    Ok(out)
1321}
1322
1323pub(crate) fn is_word(arg: &str) -> bool {
1324    let mut chars = arg.chars();
1325    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
1326        && chars.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
1327}
1328
1329fn trap_cases(bases: &[Case]) -> Vec<Case> {
1330    let mut out = Vec::new();
1331    for base in bases {
1332        for (i, arg) in base.args.iter().enumerate() {
1333            if i == 0 && is_word(arg) {
1334                continue;
1335            }
1336            let number = arg.parse::<f64>().is_ok();
1337            if arg.starts_with('-') && !number {
1338                continue;
1339            }
1340            let values: Vec<&str> = if arg.parse::<i128>().is_ok() {
1341                INT_TRAPS.to_vec()
1342            } else if number && arg.contains(['.', 'e', 'E']) {
1343                FLOAT_TRAPS.to_vec()
1344            } else if base.files.contains_key(Path::new(arg)) {
1345                vec!["missing-input.txt"]
1346            } else {
1347                STRING_TRAPS.to_vec()
1348            };
1349            for v in values.into_iter().filter(|v| v != arg) {
1350                let mut case = base.clone();
1351                case.args[i] = v.to_string();
1352                out.push(case);
1353            }
1354        }
1355        if let Some(stdin) = &base.stdin {
1356            let json = std::str::from_utf8(stdin)
1357                .ok()
1358                .and_then(|t| serde_json::from_str::<Value>(t).ok())
1359                .is_some_and(|v| v.is_object() || v.is_array());
1360            let values: &[&str] = if json { &JSON_TRAPS } else { &STDIN_TRAPS };
1361            for v in values {
1362                let mut case = base.clone();
1363                case.stdin = Some(v.as_bytes().to_vec());
1364                out.push(case);
1365            }
1366        }
1367    }
1368    out.truncate(MAX_TRAPS);
1369    out
1370}
1371
1372pub(crate) fn slug(text: &str) -> String {
1373    slug_max(text, 24)
1374}
1375
1376/// A case name the user gave in `--inputs`: longer than a generated one, so names that differ
1377/// only past the 24th character stay apart.
1378pub(crate) fn given_slug(text: &str) -> String {
1379    slug_max(text, 96)
1380}
1381
1382fn slug_max(text: &str, max: usize) -> String {
1383    let mut out = String::new();
1384    for c in text.chars() {
1385        if c.is_ascii_alphanumeric() {
1386            out.push(c.to_ascii_lowercase());
1387        } else if !out.ends_with('-') && !out.is_empty() {
1388            out.push('-');
1389        }
1390    }
1391    out.truncate(max);
1392    out.trim_end_matches('-').to_string()
1393}
1394
1395pub struct RecordOptions<'a> {
1396    pub repo: &'a Path,
1397    /// The command that runs the original; taken from the saved config when empty.
1398    pub run: &'a [String],
1399    pub inputs: Option<&'a Path>,
1400    /// Built-in normalizer names, or `name=regex` for your own.
1401    pub normalize: &'a [String],
1402    pub name: Option<&'a str>,
1403    pub traps: bool,
1404    pub timeout_secs: Option<u64>,
1405    /// The app is a server: record requests instead of command lines.
1406    pub http: bool,
1407    /// The port a server always listens on (implies `http`); unset, it gets a free one through
1408    /// `PORT` and `{port}`.
1409    pub port: Option<u16>,
1410    /// Servers: arguments every start gets after its command, the original's and every build's
1411    /// (implies `http`); kept from the last recording when empty.
1412    pub server_args: &'a [String],
1413    /// Servers: repository files or folders copied into a fresh working directory before every
1414    /// start (implies `http`); kept from the last recording when empty.
1415    pub fresh: &'a [String],
1416    /// Servers: milliseconds to wait after each response, for work the server does after
1417    /// answering (a file watcher, a write-behind); kept from the last recording when `None`.
1418    pub pace_ms: Option<u64>,
1419    /// Numbers in the output match within this tolerance; kept from the last recording when
1420    /// `None`, removed with 0.
1421    pub float_tolerance: Option<f64>,
1422    /// Written files of raw floats, `path=f32le` or `path=f64le`; kept from the last recording
1423    /// when empty.
1424    pub float_files: &'a [String],
1425    pub effects: Option<crate::effects::EffectsConfig>,
1426}
1427
1428#[derive(Debug, Serialize)]
1429pub struct RecordOutcome {
1430    pub dir: PathBuf,
1431    pub run: Vec<String>,
1432    pub cases: usize,
1433    pub examples: usize,
1434    pub inputs: usize,
1435    pub traps: usize,
1436    /// Cases where the two runs of the original differed.
1437    pub noisy: Vec<String>,
1438    /// What differed in each noisy case, and how: `values` became wildcards, `order` is compared
1439    /// in any order, `lines` became a `...` that matches anything.
1440    pub noise: Vec<Noise>,
1441    /// Cases whose exit code or written files differed between the two runs.
1442    pub unstable: Vec<String>,
1443    /// Cases not written: the original timed out or did not answer.
1444    pub timed_out: Vec<String>,
1445}
1446
1447struct Recorded {
1448    stdout: Vec<u8>,
1449    stderr: Vec<u8>,
1450    effects: Option<Vec<u8>>,
1451    status: Status,
1452    written: BTreeMap<PathBuf, Vec<u8>>,
1453    removed: Vec<PathBuf>,
1454    binary: bool,
1455    noise: Vec<(String, NoiseKind)>,
1456    unstable: bool,
1457}
1458
1459/// How two runs of the original disagreed.
1460#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1461#[serde(rename_all = "lowercase")]
1462pub enum NoiseKind {
1463    /// Values within lines changed (times, ids): those parts are wildcards now.
1464    Values,
1465    /// The same lines came out in another order (hash maps, concurrency): replay compares them
1466    /// in any order, and a port must produce exactly those lines.
1467    Order,
1468    /// A different number of lines came out: that stretch is a `...` wildcard, which matches
1469    /// anything. Look at these first.
1470    Lines,
1471}
1472
1473#[derive(Debug, Clone, Serialize)]
1474pub struct Noise {
1475    pub case: String,
1476    pub field: String,
1477    pub kind: NoiseKind,
1478}
1479
1480fn same_lines_any_order(a: &str, b: &str) -> bool {
1481    let (mut la, mut lb) = (lines(a), lines(b));
1482    la.sort_unstable();
1483    lb.sort_unstable();
1484    la == lb
1485}
1486
1487pub(crate) fn settle_text(
1488    norm: &Normalizers,
1489    a: &[u8],
1490    b: &[u8],
1491) -> (Vec<u8>, Option<NoiseKind>, bool) {
1492    match (std::str::from_utf8(a), std::str::from_utf8(b)) {
1493        (Ok(a), Ok(b)) => {
1494            let (a, b) = (norm.apply(a), norm.apply(b));
1495            if a == b || (norm.key_order && norm.canonical(&a) == norm.canonical(&b)) {
1496                (a.into_bytes(), None, false)
1497            } else if same_lines_any_order(&a, &b) {
1498                (a.into_bytes(), Some(NoiseKind::Order), false)
1499            } else {
1500                let merged = merge_noise(&a, &b);
1501                let kind = if merged.split('\n').any(|l| l == "...") {
1502                    NoiseKind::Lines
1503                } else {
1504                    NoiseKind::Values
1505                };
1506                (merged.into_bytes(), Some(kind), false)
1507            }
1508        }
1509        _ => (a.to_vec(), (a != b).then_some(NoiseKind::Values), true),
1510    }
1511}
1512
1513fn settle(norm: &Normalizers, case: &Case, one: &Run, two: &Run) -> Recorded {
1514    let binary = [&one.stdout, &one.stderr, &two.stdout, &two.stderr]
1515        .iter()
1516        .any(|bytes| std::str::from_utf8(bytes).is_err());
1517    let settle_stream = |a: &[u8], b: &[u8]| {
1518        if binary {
1519            (a.to_vec(), (a != b).then_some(NoiseKind::Values))
1520        } else {
1521            let (bytes, noise, _) = settle_text(norm, a, b);
1522            (bytes, noise)
1523        }
1524    };
1525    let (stdout, out_noise) = settle_stream(&one.stdout, &two.stdout);
1526    let (stderr, err_noise) = settle_stream(&one.stderr, &two.stderr);
1527    let (effects, fx_noise) = match (&one.effects, &two.effects) {
1528        (Some(a), Some(b)) => {
1529            let (bytes, noise, _) = settle_text(norm, a, b);
1530            (Some(bytes), noise)
1531        }
1532        _ => (None, None),
1533    };
1534    let (w1, w2) = (one.written(case), two.written(case));
1535    let mut unstable = one.status != two.status
1536        || one.removed != two.removed
1537        || !w1.keys().eq(w2.keys())
1538        || (binary && (out_noise.is_some() || err_noise.is_some()));
1539    let mut noise: Vec<(String, NoiseKind)> = [
1540        ("stdout", out_noise),
1541        ("stderr", err_noise),
1542        (crate::effects::EXT, fx_noise),
1543    ]
1544    .into_iter()
1545    .filter_map(|(f, k)| Some((f.to_string(), k?)))
1546    .collect();
1547    let mut written = BTreeMap::new();
1548    for (path, a) in &w1 {
1549        let b = w2.get(path).unwrap_or(a);
1550        let (bytes, file_noise, file_bin) = settle_text(norm, a, b);
1551        unstable |= file_bin && file_noise.is_some();
1552        if let Some(kind) = file_noise {
1553            noise.push((format!("file {}", path.display()), kind));
1554        }
1555        written.insert(path.clone(), bytes);
1556    }
1557    Recorded {
1558        stdout,
1559        stderr,
1560        effects,
1561        status: one.status.clone(),
1562        written,
1563        removed: one.removed.clone(),
1564        binary,
1565        noise,
1566        unstable,
1567    }
1568}
1569
1570fn dotted() -> Table {
1571    let mut t = Table::new();
1572    t.set_dotted(true);
1573    t
1574}
1575
1576fn write_case(dir: &Path, bin: &str, name: &str, case: &Case, rec: &Recorded) -> Result<()> {
1577    for ext in [
1578        "stdin",
1579        "stdout",
1580        "stderr",
1581        REMOVED_EXT,
1582        crate::effects::EXT,
1583    ] {
1584        let _ = std::fs::remove_file(dir.join(format!("{name}.{ext}")));
1585    }
1586    for ext in ["in", "out"] {
1587        let _ = std::fs::remove_dir_all(dir.join(format!("{name}.{ext}")));
1588    }
1589    let mut doc = DocumentMut::new();
1590    let mut bin_t = dotted();
1591    bin_t["name"] = value(bin);
1592    doc["bin"] = Item::Table(bin_t);
1593    let mut args = toml_edit::Array::new();
1594    for a in &case.args {
1595        args.push(a.as_str());
1596    }
1597    doc["args"] = value(args);
1598    if !case.env.is_empty() {
1599        let mut add = dotted();
1600        for (k, v) in &case.env {
1601            add[k.as_str()] = value(v.as_str());
1602        }
1603        let mut env = dotted();
1604        env.insert("add", Item::Table(add));
1605        doc["env"] = Item::Table(env);
1606    }
1607    match rec.status {
1608        Status::Code(code) => {
1609            let mut status = dotted();
1610            status["code"] = value(i64::from(code));
1611            doc["status"] = Item::Table(status);
1612        }
1613        _ => doc["status"] = value("interrupted"),
1614    }
1615    let mut fs = dotted();
1616    fs["sandbox"] = value(true);
1617    if !case.files.is_empty() {
1618        fs["base"] = value(format!("{name}.in"));
1619    }
1620    if !case.remove.is_empty() {
1621        let mut remove = toml_edit::Array::new();
1622        for path in &case.remove {
1623            remove.push(path.to_string_lossy().as_ref());
1624        }
1625        fs["remove"] = value(remove);
1626    }
1627    doc["fs"] = Item::Table(fs);
1628    if rec.binary {
1629        doc["binary"] = value(true);
1630    }
1631    std::fs::write(dir.join(format!("{name}.toml")), doc.to_string())?;
1632    if let Some(stdin) = &case.stdin {
1633        std::fs::write(dir.join(format!("{name}.stdin")), stdin)?;
1634    }
1635    std::fs::write(dir.join(format!("{name}.stdout")), &rec.stdout)?;
1636    std::fs::write(dir.join(format!("{name}.stderr")), &rec.stderr)?;
1637    if !rec.removed.is_empty() {
1638        let list: String = rec
1639            .removed
1640            .iter()
1641            .map(|p| format!("{}\n", p.display()))
1642            .collect();
1643        std::fs::write(dir.join(format!("{name}.{REMOVED_EXT}")), list)?;
1644    }
1645    if let Some(effects) = &rec.effects {
1646        std::fs::write(dir.join(format!("{name}.{}", crate::effects::EXT)), effects)?;
1647    }
1648    for (sub, files) in [("in", &case.files), ("out", &rec.written)] {
1649        for (path, bytes) in files {
1650            let target = dir.join(format!("{name}.{sub}")).join(path);
1651            if let Some(parent) = target.parent() {
1652                std::fs::create_dir_all(parent)?;
1653            }
1654            std::fs::write(&target, bytes)?;
1655        }
1656    }
1657    Ok(())
1658}
1659
1660pub(crate) fn reserve_case_name(
1661    taken: &mut BTreeSet<String>,
1662    base: String,
1663    mut suffix: usize,
1664) -> String {
1665    let mut name = base.clone();
1666    while !taken.insert(name.clone()) {
1667        name = format!("{base}-{suffix}");
1668        suffix += 1;
1669    }
1670    name
1671}
1672
1673pub fn record(opts: &RecordOptions) -> Result<RecordOutcome> {
1674    let repo = opts
1675        .repo
1676        .canonical()
1677        .with_context(|| format!("no folder {}", opts.repo.display()))?;
1678    let existing = Config::load(&repo)?;
1679    let run = if !opts.run.is_empty() {
1680        opts.run.to_vec()
1681    } else if let Some(c) = &existing {
1682        c.run.clone()
1683    } else {
1684        bail!(
1685            "give the command that runs the original after `--`, e.g. `rust-anything app record . -- python3 cli.py`"
1686        );
1687    };
1688    let mut normalize = existing
1689        .as_ref()
1690        .map(|c| c.normalize.clone())
1691        .unwrap_or_default();
1692    let mut normalizers = existing
1693        .as_ref()
1694        .map(|c| c.normalizers.clone())
1695        .unwrap_or_default();
1696    for n in opts.normalize {
1697        if let Some((name, pattern)) = n.split_once('=') {
1698            normalizers.insert(name.to_string(), pattern.to_string());
1699        } else if !normalize.contains(n) {
1700            normalize.push(n.clone());
1701        }
1702    }
1703    let explicit = opts
1704        .name
1705        .map(str::to_string)
1706        .or_else(|| existing.as_ref().map(|c| c.name.clone()));
1707    let names = app_names(&repo, &run, explicit.as_deref());
1708    let mut config = Config {
1709        schema: SCHEMA.to_string(),
1710        name: explicit
1711            .or_else(|| names.first().cloned())
1712            .unwrap_or_else(|| "app".to_string()),
1713        run,
1714        normalize,
1715        normalizers,
1716        timeout_secs: opts
1717            .timeout_secs
1718            .or(existing.as_ref().map(|c| c.timeout_secs))
1719            .unwrap_or_else(default_timeout),
1720        http: crate::http::merge_config(existing.as_ref().and_then(|c| c.http.clone()), opts),
1721        float_tolerance: match opts.float_tolerance {
1722            Some(t) => (crate::tolerance::check(t)? > 0.0).then_some(t),
1723            None => existing.as_ref().and_then(|c| c.float_tolerance),
1724        },
1725        float_files: if opts.float_files.is_empty() {
1726            existing
1727                .as_ref()
1728                .map(|c| c.float_files.clone())
1729                .unwrap_or_default()
1730        } else {
1731            opts.float_files
1732                .iter()
1733                .map(|spec| {
1734                    let (path, format) = spec.rsplit_once('=').with_context(|| {
1735                        format!("--float-file `{spec}`: use PATH=f32le or PATH=f64le")
1736                    })?;
1737                    float_width(format)?;
1738                    Ok((path.to_string(), format.to_string()))
1739                })
1740                .collect::<Result<_>>()?
1741        },
1742        unordered: BTreeMap::new(),
1743        effects: crate::effects::EffectsConfig::merge(
1744            existing.as_ref().and_then(|c| c.effects.clone()),
1745            opts.effects.clone(),
1746        ),
1747        fresh: Vec::new(),
1748    };
1749    if let Some(http) = config.http.as_mut() {
1750        if !opts.fresh.is_empty() {
1751            http.fresh = opts.fresh.to_vec();
1752        }
1753    } else if !opts.fresh.is_empty() {
1754        config.fresh = opts.fresh.to_vec();
1755    } else if let Some(c) = &existing {
1756        config.fresh = c.fresh.clone();
1757    }
1758    let norm = Normalizers::new(&config)?;
1759    if config.http.is_some() {
1760        let outcome = crate::http::record(&repo, &config, &norm, opts)?;
1761        config.unordered = unordered_of(&outcome.noise);
1762        std::fs::write(
1763            cases_dir(&repo).join(CONFIG_FILE),
1764            serde_json::to_string_pretty(&config)? + "\n",
1765        )?;
1766        return Ok(outcome);
1767    }
1768
1769    let examples = find_examples(&repo, &names);
1770    let inputs = match opts.inputs {
1771        Some(path) => read_inputs(path)?,
1772        None => Vec::new(),
1773    };
1774    let mut planned: Vec<(String, Case)> = Vec::new();
1775    let mut seen = BTreeSet::new();
1776    let mut taken = BTreeSet::new();
1777    let mut push = |prefix: &str, n: usize, given: Option<String>, case: Case| {
1778        if !seen.insert(case.key()) {
1779            return false;
1780        }
1781        let base_name = match given {
1782            Some(g) if !given_slug(&g).is_empty() => given_slug(&g),
1783            _ => match case.args.first().map(|a| slug(a)).filter(|s| !s.is_empty()) {
1784                Some(s) => format!("{prefix}-{n:03}-{s}"),
1785                None => format!("{prefix}-{n:03}"),
1786            },
1787        };
1788        let name = reserve_case_name(&mut taken, base_name, n);
1789        planned.push((name, case));
1790        true
1791    };
1792    let mut bases = Vec::new();
1793    let mut counts = [0usize; 3];
1794    for case in examples {
1795        if push("example", counts[0] + 1, None, case.clone()) {
1796            counts[0] += 1;
1797            bases.push(case);
1798        }
1799    }
1800    for (given, case) in inputs {
1801        if push("input", counts[1] + 1, given, case.clone()) {
1802            counts[1] += 1;
1803            bases.push(case);
1804        }
1805    }
1806    if bases.is_empty() {
1807        let case = Case::new(Vec::new());
1808        push("example", 1, Some("no-args".to_string()), case.clone());
1809        bases.push(case);
1810    }
1811    if opts.traps {
1812        for case in trap_cases(&bases) {
1813            if push("trap", counts[2] + 1, None, case) {
1814                counts[2] += 1;
1815            }
1816        }
1817    }
1818
1819    let timeout = Duration::from_secs(config.timeout_secs);
1820    let effects = config.effects.as_ref();
1821    let base = crate::http::snapshot_to(&repo, &config.fresh, &cases_dir(&repo).join(FRESH_DIR))?;
1822    let base = base.as_deref();
1823    let run_twice = |(_, case): &(String, Case)| -> Result<(Run, Run)> {
1824        let one = run_case(&config.run, &repo, case, timeout, effects, base)?;
1825        let two = run_case(&config.run, &repo, case, timeout, effects, base)?;
1826        Ok((one, two))
1827    };
1828    let runs = if effects.is_some_and(crate::effects::EffectsConfig::serial) {
1829        planned.iter().map(run_twice).collect()
1830    } else {
1831        par_map(&planned, run_twice)
1832    };
1833    let dir = cases_dir(&repo);
1834    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
1835    let mut outcome = RecordOutcome {
1836        dir: dir.clone(),
1837        run: config.run.clone(),
1838        cases: 0,
1839        examples: counts[0],
1840        inputs: counts[1],
1841        traps: counts[2],
1842        noisy: Vec::new(),
1843        noise: Vec::new(),
1844        unstable: Vec::new(),
1845        timed_out: Vec::new(),
1846    };
1847    for ((name, case), runs) in planned.iter().zip(runs) {
1848        let (one, two) = runs?;
1849        if one.status == Status::Timeout || two.status == Status::Timeout {
1850            outcome.timed_out.push(name.clone());
1851            continue;
1852        }
1853        let rec = settle(&norm, case, &one, &two);
1854        write_case(&dir, &config.name, name, case, &rec)?;
1855        outcome.cases += 1;
1856        if !rec.noise.is_empty() {
1857            outcome.noisy.push(name.clone());
1858        }
1859        outcome
1860            .noise
1861            .extend(rec.noise.iter().map(|(field, kind)| Noise {
1862                case: name.clone(),
1863                field: field.clone(),
1864                kind: *kind,
1865            }));
1866        if rec.unstable {
1867            outcome.unstable.push(name.clone());
1868        }
1869    }
1870    config.unordered = unordered_of(&outcome.noise);
1871    std::fs::write(
1872        dir.join(CONFIG_FILE),
1873        serde_json::to_string_pretty(&config)? + "\n",
1874    )?;
1875    Ok(outcome)
1876}
1877
1878fn unordered_of(noise: &[Noise]) -> BTreeMap<String, Vec<String>> {
1879    let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new();
1880    for n in noise.iter().filter(|n| n.kind == NoiseKind::Order) {
1881        out.entry(n.case.clone()).or_default().push(n.field.clone());
1882    }
1883    out
1884}
1885
1886enum Expect {
1887    Code(i32),
1888    Failed,
1889    Killed,
1890    Skip,
1891}
1892
1893struct Spec {
1894    name: String,
1895    case: Case,
1896    stdout: Option<Vec<u8>>,
1897    stderr: Option<Vec<u8>>,
1898    effects: Option<Vec<u8>>,
1899    status: Expect,
1900    out_dir: Option<PathBuf>,
1901    removed: Option<Vec<PathBuf>>,
1902    binary: bool,
1903}
1904
1905fn read_files(base: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
1906    walk_files(base)
1907        .into_iter()
1908        .map(|p| {
1909            let rel = p.strip_prefix(base).unwrap_or(&p).to_path_buf();
1910            let bytes = std::fs::read(&p).unwrap_or_default();
1911            (rel, bytes)
1912        })
1913        .collect()
1914}
1915
1916fn load_spec(dir: &Path, path: &Path) -> Result<Spec> {
1917    let name = path
1918        .file_stem()
1919        .map(|s| s.to_string_lossy().into_owned())
1920        .unwrap_or_default();
1921    let text =
1922        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
1923    let doc: DocumentMut = text
1924        .parse()
1925        .with_context(|| format!("parsing {}", path.display()))?;
1926    let args = match doc.get("args") {
1927        Some(item) if item.as_array().is_some() => item
1928            .as_array()
1929            .into_iter()
1930            .flatten()
1931            .map(|v| {
1932                v.as_str()
1933                    .map(str::to_string)
1934                    .unwrap_or_else(|| v.to_string())
1935            })
1936            .collect(),
1937        Some(item) => shell_split(item.as_str().unwrap_or_default())?,
1938        None => Vec::new(),
1939    };
1940    let mut case = Case::new(args);
1941    let side = |key: &str| -> Result<Option<Vec<u8>>> {
1942        if let Some(s) = doc.get(key).and_then(Item::as_str) {
1943            return Ok(Some(s.as_bytes().to_vec()));
1944        }
1945        let file = dir.join(format!("{name}.{key}"));
1946        Ok(if file.exists() {
1947            Some(std::fs::read(&file).with_context(|| format!("reading {}", file.display()))?)
1948        } else {
1949            None
1950        })
1951    };
1952    case.stdin = side("stdin")?;
1953    if let Some(env) = doc.get("env") {
1954        case.inherit_env = env.get("inherit").and_then(Item::as_bool).unwrap_or(true);
1955        if let Some(add) = env.get("add").and_then(Item::as_table_like) {
1956            for (k, v) in add.iter() {
1957                case.env
1958                    .insert(k.to_string(), v.as_str().unwrap_or_default().to_string());
1959            }
1960        }
1961        if let Some(remove) = env.get("remove").and_then(Item::as_array) {
1962            case.env_remove = remove
1963                .iter()
1964                .filter_map(|v| v.as_str().map(str::to_string))
1965                .collect();
1966        }
1967    }
1968    let base = doc
1969        .get("fs")
1970        .and_then(|f| f.get("base"))
1971        .and_then(Item::as_str)
1972        .map(|b| dir.join(b))
1973        .unwrap_or_else(|| dir.join(format!("{name}.in")));
1974    if base.is_dir() {
1975        case.files = read_files(&base);
1976    }
1977    if let Some(remove) = doc
1978        .get("fs")
1979        .and_then(|f| f.get("remove"))
1980        .and_then(Item::as_array)
1981    {
1982        case.remove = remove
1983            .iter()
1984            .filter_map(|v| v.as_str().map(PathBuf::from))
1985            .collect();
1986    }
1987    let status = match doc.get("status") {
1988        None => Expect::Code(0),
1989        Some(item) => match (item.as_str(), item.get("code").and_then(Item::as_integer)) {
1990            (Some("success"), _) => Expect::Code(0),
1991            (Some("failed"), _) => Expect::Failed,
1992            (Some("interrupted"), _) => Expect::Killed,
1993            (Some("skipped"), _) => Expect::Skip,
1994            (_, Some(code)) => Expect::Code(i32::try_from(code).unwrap_or(i32::MAX)),
1995            _ => bail!("{}: unknown `status`", path.display()),
1996        },
1997    };
1998    let out_dir = dir.join(format!("{name}.out"));
1999    Ok(Spec {
2000        stdout: side("stdout")?,
2001        stderr: side("stderr")?,
2002        effects: side(crate::effects::EXT)?,
2003        status,
2004        out_dir: out_dir.is_dir().then_some(out_dir),
2005        removed: side(REMOVED_EXT)?.map(|bytes| {
2006            String::from_utf8_lossy(&bytes)
2007                .lines()
2008                .filter(|l| !l.is_empty())
2009                .map(PathBuf::from)
2010                .collect()
2011        }),
2012        binary: doc.get("binary").and_then(Item::as_bool).unwrap_or(false),
2013        name,
2014        case,
2015    })
2016}
2017
2018fn float_width(format: &str) -> Result<usize> {
2019    match format {
2020        "f32le" => Ok(4),
2021        "f64le" => Ok(8),
2022        other => bail!("float file format `{other}`: use f32le or f64le"),
2023    }
2024}
2025
2026fn floats(bytes: &[u8], width: usize) -> Vec<f64> {
2027    bytes
2028        .chunks_exact(width)
2029        .map(|c| match c.try_into() {
2030            Ok(b) if width == 4 => f64::from(f32::from_le_bytes(b)),
2031            _ => c.try_into().map_or(f64::NAN, f64::from_le_bytes),
2032        })
2033        .collect()
2034}
2035
2036fn compare_floats(
2037    expected: &[u8],
2038    actual: &[u8],
2039    width: usize,
2040    tol: Option<f64>,
2041) -> Option<String> {
2042    if !expected.len().is_multiple_of(width) || expected.len() != actual.len() {
2043        return Some(format!(
2044            "{} values expected, {} bytes got ({} bytes per value)\n",
2045            expected.len() / width,
2046            actual.len(),
2047            width
2048        ));
2049    }
2050    let (e, a) = (floats(expected, width), floats(actual, width));
2051    let tol = tol.unwrap_or(0.0);
2052    let same =
2053        |x: f64, y: f64| x == y || (x.is_nan() && y.is_nan()) || crate::tolerance::near(x, y, tol);
2054    let off: Vec<usize> = (0..e.len()).filter(|&i| !same(e[i], a[i])).collect();
2055    let first = *off.first()?;
2056    let (mut abs, mut rel) = (0.0f64, 0.0f64);
2057    for &i in &off {
2058        let d = (e[i] - a[i]).abs();
2059        abs = abs.max(d);
2060        rel = rel.max(d / e[i].abs().max(a[i].abs()).max(f64::MIN_POSITIVE));
2061    }
2062    Some(format!(
2063        "{} of {} values differ beyond the tolerance ({tol}); first at index {first}: {} expected, {} got; max abs diff {abs:e}, max rel diff {rel:e}\n",
2064        off.len(),
2065        e.len(),
2066        e[first],
2067        a[first]
2068    ))
2069}
2070
2071pub(crate) fn compare(
2072    norm: &Normalizers,
2073    expected: &[u8],
2074    actual: &[u8],
2075    binary: bool,
2076    unordered: bool,
2077) -> Option<String> {
2078    if !binary && let (Ok(e), Ok(a)) = (std::str::from_utf8(expected), std::str::from_utf8(actual))
2079    {
2080        let e = norm.canonical(&norm.apply(e));
2081        let a = norm.canonical(&norm.apply(a));
2082        let tol = norm.float_tolerance;
2083        if unordered {
2084            let (mut el, mut al) = (lines(&e), lines(&a));
2085            let same = lines_match_in_any_order(&el, &al, tol);
2086            el.sort_unstable();
2087            al.sort_unstable();
2088            return (!same).then(|| {
2089                format!(
2090                    "(lines compared in any order: the original's own runs disagreed on it)\n{}",
2091                    render_diff(&el.join("\n"), &al.join("\n"), tol)
2092                )
2093            });
2094        }
2095        return (!text_matches(&e, &a, tol)).then(|| render_diff(&e, &a, tol));
2096    }
2097    (expected != actual).then(|| {
2098        format!(
2099            "binary content differs ({} bytes expected, {} bytes got)\n",
2100            expected.len(),
2101            actual.len()
2102        )
2103    })
2104}
2105
2106pub struct ReplayOptions<'a> {
2107    pub repo: &'a Path,
2108    /// Command line of the build to test; the original's command when `None`.
2109    pub build: Option<&'a str>,
2110    pub timeout_secs: Option<u64>,
2111    /// Servers: the port the build listens on, when it is fixed.
2112    pub port: Option<u16>,
2113    /// Replay only this case (a library: only this unit).
2114    pub case: Option<&'a str>,
2115}
2116
2117pub(crate) fn only_case<T>(
2118    items: Vec<T>,
2119    case: Option<&str>,
2120    name: impl Fn(&T) -> &str,
2121) -> Result<Vec<T>> {
2122    let Some(case) = case else {
2123        return Ok(items);
2124    };
2125    let names: Vec<String> = items.iter().map(|i| name(i).to_string()).collect();
2126    let kept: Vec<T> = items.into_iter().filter(|i| name(i) == case).collect();
2127    ensure!(
2128        !kept.is_empty(),
2129        "no case named {case}; the cases are: {}",
2130        names.join(", ")
2131    );
2132    Ok(kept)
2133}
2134
2135#[derive(Debug, Serialize)]
2136pub struct Problem {
2137    pub field: String,
2138    pub detail: String,
2139}
2140
2141#[derive(Debug, Serialize)]
2142pub struct Failure {
2143    pub case: String,
2144    pub args: Vec<String>,
2145    pub problems: Vec<Problem>,
2146}
2147
2148/// Cases the build handed to the original: the front door appends a line to the file named by
2149/// `RUST_ANYTHING_FALLBACK_LOG` for every fallback (and may create it empty to report none).
2150#[derive(Debug, Serialize)]
2151pub struct Fallback {
2152    pub cases: usize,
2153    pub total: usize,
2154    pub rate: f64,
2155    /// The cases that fell back.
2156    pub names: Vec<String>,
2157}
2158
2159#[derive(Debug, Serialize)]
2160pub struct ReplayOutcome {
2161    pub build: Vec<String>,
2162    pub passed: usize,
2163    pub total: usize,
2164    pub skipped: usize,
2165    pub failures: Vec<Failure>,
2166    pub fallback: Option<Fallback>,
2167    pub report: PathBuf,
2168}
2169
2170fn check(
2171    norm: &Normalizers,
2172    command: &[String],
2173    repo: &Path,
2174    spec: &Spec,
2175    timeout: Duration,
2176    effects: Option<&crate::effects::EffectsConfig>,
2177    base: Option<&Path>,
2178) -> Result<(Vec<Problem>, Option<bool>)> {
2179    let run = run_case(command, repo, &spec.case, timeout, effects, base)?;
2180    let mut problems = Vec::new();
2181    let status_ok = match (&spec.status, &run.status) {
2182        (Expect::Code(e), Status::Code(a)) => e == a,
2183        (Expect::Failed, Status::Code(a)) => *a != 0,
2184        (Expect::Killed, Status::Killed) | (Expect::Skip, _) => true,
2185        _ => false,
2186    };
2187    if !status_ok {
2188        let expected = match &spec.status {
2189            Expect::Code(c) => format!("exit code {c}"),
2190            Expect::Failed => "a non-zero exit code".to_string(),
2191            Expect::Killed => "killed by a signal".to_string(),
2192            Expect::Skip => String::new(),
2193        };
2194        problems.push(Problem {
2195            field: "status".to_string(),
2196            detail: format!("expected {expected}, got {}\n", run.status),
2197        });
2198    }
2199    let no_effects = Vec::new();
2200    for (field, expected, actual) in [
2201        ("stdout", &spec.stdout, &run.stdout),
2202        ("stderr", &spec.stderr, &run.stderr),
2203        (
2204            crate::effects::EXT,
2205            &spec.effects,
2206            run.effects.as_ref().unwrap_or(&no_effects),
2207        ),
2208    ] {
2209        if let Some(expected) = expected
2210            && let Some(detail) = compare(
2211                norm,
2212                expected,
2213                actual,
2214                spec.binary,
2215                norm.unordered(&spec.name, field),
2216            )
2217        {
2218            problems.push(Problem {
2219                field: field.to_string(),
2220                detail,
2221            });
2222        }
2223    }
2224    if let Some(expected) = &spec.removed
2225        && *expected != run.removed
2226    {
2227        let list = |paths: &[PathBuf]| -> String {
2228            paths
2229                .iter()
2230                .map(|p| format!("  {}\n", p.display()))
2231                .collect()
2232        };
2233        problems.push(Problem {
2234            field: "removed files".to_string(),
2235            detail: format!(
2236                "expected removed:\n{}got removed:\n{}",
2237                list(expected),
2238                list(&run.removed)
2239            ),
2240        });
2241    }
2242    if let Some(out_dir) = &spec.out_dir {
2243        for (path, expected) in read_files(out_dir) {
2244            let field = format!("file {}", path.display());
2245            match run.files.get(&path) {
2246                None => problems.push(Problem {
2247                    field,
2248                    detail: "not written\n".to_string(),
2249                }),
2250                Some(actual) => {
2251                    let unordered = norm.unordered(&spec.name, &field);
2252                    let detail = match norm.float_files.get(&path) {
2253                        Some(&width) => {
2254                            compare_floats(&expected, actual, width, norm.float_tolerance)
2255                        }
2256                        None => compare(norm, &expected, actual, false, unordered),
2257                    };
2258                    if let Some(detail) = detail {
2259                        problems.push(Problem { field, detail });
2260                    }
2261                }
2262            }
2263        }
2264    }
2265    Ok((problems, run.fallback))
2266}
2267
2268pub(crate) fn report_markdown(outcome: &ReplayOutcome) -> String {
2269    stable_paths(&report_body(outcome))
2270}
2271
2272/// The report with the per-run sandbox paths replaced, so two replays of the same build write the
2273/// same file and CI can commit it and fail on `git diff --exit-code`.
2274fn stable_paths(text: &str) -> String {
2275    static SANDBOX: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
2276    let tmp = std::env::temp_dir();
2277    let tmp = tmp.to_string_lossy();
2278    let tmp = tmp.trim_end_matches(['/', '\\']);
2279    let text = if tmp.len() > 1 {
2280        text.replace(tmp, "$TMPDIR")
2281    } else {
2282        text.to_string()
2283    };
2284    SANDBOX
2285        .get_or_init(|| regex::Regex::new(r"rust-anything-app-(\w+)-\d+-\d+").expect("valid regex"))
2286        .replace_all(&text, "rust-anything-app-$1")
2287        .into_owned()
2288}
2289
2290fn report_body(outcome: &ReplayOutcome) -> String {
2291    let mut out = String::from("# App replay\n\n");
2292    out += &format!(
2293        "Build: `{}`\n\n",
2294        outcome
2295            .build
2296            .iter()
2297            .map(|w| shell_quote(w))
2298            .collect::<Vec<_>>()
2299            .join(" ")
2300    );
2301    out += &format!("Passed: {}/{}\n\n", outcome.passed, outcome.total);
2302    if outcome.skipped > 0 {
2303        out += &format!("Skipped: {}\n\n", outcome.skipped);
2304    }
2305    out += &match &outcome.fallback {
2306        Some(f) => format!(
2307            "Fallback rate: {:.1}% ({}/{} cases answered by the original)\n\n",
2308            f.rate * 100.0,
2309            f.cases,
2310            f.total
2311        ),
2312        None => "Fallback rate: not reported by this build\n\n".to_string(),
2313    };
2314    if outcome.failures.is_empty() {
2315        out += "Every case matches.\n";
2316        return out;
2317    }
2318    out += "## Failing cases\n";
2319    for f in &outcome.failures {
2320        out += &format!(
2321            "\n### {}\n\nArguments: `{}`\n",
2322            f.case,
2323            f.args
2324                .iter()
2325                .map(|w| shell_quote(w))
2326                .collect::<Vec<_>>()
2327                .join(" ")
2328        );
2329        for p in &f.problems {
2330            out += &format!(
2331                "\n{}:\n\n```diff\n{}```\n",
2332                p.field,
2333                p.detail.replace("```", "`\u{200b}``")
2334            );
2335        }
2336    }
2337    out
2338}
2339
2340fn load_specs(dir: &Path) -> Result<Vec<Spec>> {
2341    let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
2342        .with_context(|| {
2343            format!(
2344                "no cases in {}: run `rust-anything app record` first",
2345                dir.display()
2346            )
2347        })?
2348        .flatten()
2349        .map(|e| e.path())
2350        .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "toml"))
2351        .collect();
2352    paths.sort();
2353    let specs = paths
2354        .iter()
2355        .map(|p| load_spec(dir, p))
2356        .collect::<Result<Vec<_>>>()?;
2357    ensure!(
2358        !specs.is_empty(),
2359        "no cases in {}: run `rust-anything app record` first",
2360        dir.display()
2361    );
2362    Ok(specs)
2363}
2364
2365/// The recorded cases' arguments, each with whether the original exited 0.
2366pub(crate) fn recorded_args(repo: &Path) -> Result<Vec<(Vec<String>, bool)>> {
2367    Ok(load_specs(&cases_dir(repo))?
2368        .into_iter()
2369        .map(|s| (s.case.args, matches!(s.status, Expect::Code(0))))
2370        .collect())
2371}
2372
2373pub fn replay(opts: &ReplayOptions) -> Result<ReplayOutcome> {
2374    let repo = opts
2375        .repo
2376        .canonical()
2377        .with_context(|| format!("no folder {}", opts.repo.display()))?;
2378    let dir = cases_dir(&repo);
2379    let config = Config::load(&repo)?;
2380    if config.is_none()
2381        && let Ok(state) = crate::front_door::State::load(&repo)
2382        && state.kind == crate::front_door::AppKind::Library
2383    {
2384        ensure!(
2385            opts.build.is_none(),
2386            "{} is a library: its cases replay through each unit's bindings, so --build does not apply",
2387            state.name
2388        );
2389        return crate::library::replay(&repo, &state, opts.case);
2390    }
2391    let command = match (opts.build, &config) {
2392        (Some(build), _) => shell_split(build)?,
2393        (None, Some(c)) => c.run.clone(),
2394        (None, None) => bail!(
2395            "no {} in {}: run `rust-anything app record` first, or pass --build",
2396            CONFIG_FILE,
2397            dir.display()
2398        ),
2399    };
2400    ensure!(!command.is_empty(), "the build command is empty");
2401    let config = config.unwrap_or_else(|| Config {
2402        schema: SCHEMA.to_string(),
2403        name: "app".to_string(),
2404        run: Vec::new(),
2405        normalize: Vec::new(),
2406        normalizers: BTreeMap::new(),
2407        timeout_secs: default_timeout(),
2408        http: None,
2409        float_tolerance: None,
2410        float_files: BTreeMap::new(),
2411        unordered: BTreeMap::new(),
2412        effects: None,
2413        fresh: Vec::new(),
2414    });
2415    let norm = Normalizers::new(&config)?;
2416    let timeout = Duration::from_secs(opts.timeout_secs.unwrap_or(config.timeout_secs));
2417    if config.http.is_some() {
2418        return crate::http::replay(
2419            &repo, &config, &norm, &command, opts.port, opts.case, timeout,
2420        );
2421    }
2422    let specs = only_case(load_specs(&dir)?, opts.case, |s| &s.name)?;
2423    let effects = config.effects.as_ref();
2424    let base = if config.fresh.is_empty() {
2425        None
2426    } else {
2427        let base = dir.join(FRESH_DIR);
2428        ensure!(
2429            base.is_dir(),
2430            "no {}: record again to snapshot the fresh files",
2431            base.display()
2432        );
2433        Some(base)
2434    };
2435    let check_one = |spec: &Spec| {
2436        if matches!(spec.status, Expect::Skip) {
2437            return Ok((Vec::new(), None));
2438        }
2439        check(
2440            &norm,
2441            &command,
2442            &repo,
2443            spec,
2444            timeout,
2445            effects,
2446            base.as_deref(),
2447        )
2448    };
2449    let results: Vec<Result<_>> = if effects.is_some_and(crate::effects::EffectsConfig::serial) {
2450        specs.iter().map(check_one).collect()
2451    } else {
2452        par_map(&specs, check_one)
2453    };
2454    let mut outcome = ReplayOutcome {
2455        build: command.clone(),
2456        passed: 0,
2457        total: 0,
2458        skipped: 0,
2459        failures: Vec::new(),
2460        fallback: None,
2461        report: dir.join(REPORT_FILE),
2462    };
2463    let (mut reported, mut fell_back) = (false, Vec::new());
2464    for (spec, result) in specs.iter().zip(results) {
2465        if matches!(spec.status, Expect::Skip) {
2466            outcome.skipped += 1;
2467            continue;
2468        }
2469        let (problems, fallback) = result?;
2470        outcome.total += 1;
2471        reported |= fallback.is_some();
2472        if fallback == Some(true) {
2473            fell_back.push(spec.name.clone());
2474        }
2475        if problems.is_empty() {
2476            outcome.passed += 1;
2477        } else {
2478            outcome.failures.push(Failure {
2479                case: spec.name.clone(),
2480                args: spec.case.args.clone(),
2481                problems,
2482            });
2483        }
2484    }
2485    if reported {
2486        outcome.fallback = Some(Fallback {
2487            cases: fell_back.len(),
2488            total: outcome.total,
2489            rate: fell_back.len() as f64 / outcome.total.max(1) as f64,
2490            names: fell_back,
2491        });
2492    }
2493    std::fs::write(&outcome.report, report_markdown(&outcome))
2494        .with_context(|| format!("writing {}", outcome.report.display()))?;
2495    Ok(outcome)
2496}
2497
2498#[cfg(test)]
2499mod tests {
2500    use super::*;
2501
2502    #[test]
2503    fn given_names_keep_their_tail() {
2504        let a = given_slug("tests/format/typescript/conformance/types/never/never.ts");
2505        let b = given_slug("tests/format/typescript/conformance/types/tuple/tuple.ts");
2506        assert_ne!(a, b);
2507        assert_eq!(
2508            a,
2509            "tests-format-typescript-conformance-types-never-never-ts"
2510        );
2511        assert_eq!(slug(&a).len(), 23);
2512    }
2513
2514    #[test]
2515    fn reports_do_not_carry_sandbox_paths() {
2516        let tmp = std::env::temp_dir();
2517        let line = format!(
2518            "-cwd {}\n",
2519            tmp.join("rust-anything-app-run-4242-7")
2520                .join("cwd")
2521                .display()
2522        );
2523        let stable = stable_paths(&line);
2524        assert!(!stable.contains("4242"), "{stable}");
2525        assert!(stable.contains("$TMPDIR"), "{stable}");
2526        assert_eq!(
2527            stable,
2528            stable_paths(&line.replace("4242-7", "99-0")),
2529            "{stable}"
2530        );
2531    }
2532
2533    fn text_matches_exact(e: &str, a: &str) -> bool {
2534        text_matches(e, a, None)
2535    }
2536
2537    fn norm_with_tolerance(tol: Option<f64>) -> Normalizers {
2538        Normalizers::new(&Config {
2539            schema: SCHEMA.to_string(),
2540            name: "app".to_string(),
2541            run: Vec::new(),
2542            normalize: Vec::new(),
2543            normalizers: BTreeMap::new(),
2544            timeout_secs: default_timeout(),
2545            http: None,
2546            float_tolerance: tol,
2547            float_files: BTreeMap::new(),
2548            unordered: BTreeMap::new(),
2549            effects: None,
2550            fresh: Vec::new(),
2551        })
2552        .unwrap()
2553    }
2554
2555    #[test]
2556    fn unordered_lines_pair_up_by_value_within_the_tolerance() {
2557        let norm = norm_with_tolerance(Some(1e-9));
2558        // `2.0` meets `2.0` and `10.0` meets `9.999999999999999`, but `10.0` sorts before `2.0`
2559        // as text, so pairing the sorted lines by position compared `10.0` against `2.0`.
2560        let expected = b"n 2.0\nn 10.0\n";
2561        let actual = b"n 2.0\nn 9.999999999999999\n";
2562        assert!(compare(&norm, expected, actual, false, false).is_none());
2563        assert!(compare(&norm, expected, actual, false, true).is_none());
2564        // A line that is genuinely different is still reported.
2565        let changed = b"n 2.0\nn 11.0\n";
2566        assert!(compare(&norm, expected, changed, false, true).is_some());
2567        // The order the lines arrive in does not matter.
2568        let swapped = b"n 9.999999999999999\nn 2.0\n";
2569        assert!(compare(&norm, expected, swapped, false, true).is_none());
2570    }
2571
2572    #[test]
2573    fn unordered_lines_pair_up_around_a_wildcard() {
2574        let norm = norm_with_tolerance(Some(1e-9));
2575        // `[..]` takes the line the numeric pairing does not want, so a tolerance and a wildcard
2576        // in the same output do not fight over the ordering.
2577        let expected = b"n 10.0\nn [..]\n";
2578        assert!(compare(&norm, expected, b"n 10.0\nn 2.0\n", false, true).is_none());
2579        assert!(compare(&norm, expected, b"n 2.0\nn 10.0\n", false, true).is_none());
2580        assert!(
2581            compare(
2582                &norm,
2583                expected,
2584                b"n 2.0\nn 9.999999999999999\n",
2585                false,
2586                true
2587            )
2588            .is_none()
2589        );
2590        // Nothing to take the 10.0: both actual lines are far from it.
2591        assert!(compare(&norm, expected, b"n 2.0\nn 3.0\n", false, true).is_some());
2592    }
2593
2594    #[test]
2595    fn unordered_lines_keep_a_plain_permutation_matching() {
2596        let norm = norm_with_tolerance(Some(1e-9));
2597        // The same lines in another order match whatever the numbers look like, and a value
2598        // written two ways stays a difference rather than becoming one by being re-sorted.
2599        assert!(compare(&norm, b"n 2\nn 2.0\n", b"n 2.0\nn 2\n", false, true).is_none());
2600        assert!(compare(&norm, b"n 2\nn 2\n", b"n 2.0\nn 2.0\n", false, true).is_some());
2601    }
2602
2603    #[test]
2604    fn unordered_lines_without_a_tolerance_still_compare_as_text() {
2605        let norm = norm_with_tolerance(None);
2606        let expected = b"b\na\n";
2607        assert!(compare(&norm, expected, b"a\nb\n", false, true).is_none());
2608        assert!(compare(&norm, expected, b"a\nc\n", false, true).is_some());
2609        assert!(compare(&norm, expected, b"a\n", false, true).is_some());
2610        // Without a tolerance a number is text like any other, so this stays a mismatch.
2611        let numeric = b"n 10.0\nn 2.0\n";
2612        assert!(compare(&norm, numeric, b"n 2.0\nn 9.999999999999999\n", false, true).is_some());
2613    }
2614
2615    #[cfg(unix)]
2616    #[test]
2617    fn replay_deadline_covers_descendants_that_keep_pipes_open() {
2618        for script in ["sleep 6 & wait", "sleep 6 & exit 0"] {
2619            let command = ["/bin/sh".into(), "-c".into(), script.into()];
2620            let start = Instant::now();
2621            let run = run_case(
2622                &command,
2623                Path::new("."),
2624                &Case::new(Vec::new()),
2625                Duration::from_millis(200),
2626                None,
2627                None,
2628            )
2629            .unwrap();
2630            assert!(start.elapsed() < Duration::from_secs(3), "{script}");
2631            assert!(run.status == Status::Timeout, "{script}: {}", run.status);
2632        }
2633    }
2634
2635    #[test]
2636    fn matching_follows_trycmd() {
2637        assert!(text_matches_exact("a\nb\n", "a\nb\n"));
2638        assert!(text_matches_exact("now: [..]\n", "now: 1234\n"));
2639        assert!(text_matches_exact("x [..] y [..] z\n", "x 1 y 2 y 3 z\n"));
2640        assert!(!text_matches_exact("x [..] z\n", "x 1 y\n"));
2641        assert!(text_matches_exact(
2642            "head\n...\ntail\n",
2643            "head\n1\n2\ntail\n"
2644        ));
2645        assert!(text_matches_exact("head\n...\ntail\n", "head\ntail\n"));
2646        assert!(!text_matches_exact("head\ntail\n", "head\nmid\ntail\n"));
2647        assert!(text_matches_exact("a\r\nb", "a\nb\n"));
2648    }
2649
2650    #[test]
2651    fn numbers_match_within_the_tolerance() {
2652        let e = "step 1\nenergy 0.3\nat [..]\n";
2653        let a = "step 1\nenergy 0.30000000000000004\nat 12:00\n";
2654        assert!(!text_matches(e, a, None));
2655        assert!(text_matches(e, a, Some(1e-9)));
2656        assert!(!text_matches(
2657            e,
2658            "step 2\nenergy 0.3\nat 12:00\n",
2659            Some(1e-9)
2660        ));
2661        assert!(!render_diff(e, a, Some(1e-9)).contains("energy"));
2662    }
2663
2664    #[cfg(unix)]
2665    #[test]
2666    fn binary_capture_replays_its_text_companion_byte_for_byte() {
2667        let repo = temp_dir("binary-stream-pair").unwrap();
2668        let run = [
2669            "/bin/sh".to_string(),
2670            "-c".to_string(),
2671            r"printf '\377'; printf 'at 2026-11-16T10:00:00Z\n' >&2".to_string(),
2672        ];
2673        let recorded = record(&RecordOptions {
2674            repo: &repo,
2675            run: &run,
2676            inputs: None,
2677            normalize: &["timestamps".into()],
2678            name: None,
2679            traps: false,
2680            timeout_secs: None,
2681            http: false,
2682            server_args: &[],
2683            fresh: &[],
2684            pace_ms: None,
2685            port: None,
2686            float_tolerance: None,
2687            float_files: &[],
2688            effects: None,
2689        })
2690        .unwrap();
2691        assert_eq!(recorded.cases, 1);
2692        let replayed = replay(&ReplayOptions {
2693            repo: &repo,
2694            build: None,
2695            timeout_secs: None,
2696            port: None,
2697            case: None,
2698        })
2699        .unwrap();
2700        assert_eq!(
2701            (replayed.passed, replayed.total),
2702            (1, 1),
2703            "{:?}",
2704            replayed.failures
2705        );
2706        std::fs::remove_dir_all(repo).unwrap();
2707    }
2708
2709    #[test]
2710    fn noise_is_classified() {
2711        let norm = Normalizers::new(&Config {
2712            schema: SCHEMA.to_string(),
2713            name: "app".to_string(),
2714            run: Vec::new(),
2715            normalize: Vec::new(),
2716            normalizers: BTreeMap::new(),
2717            timeout_secs: 30,
2718            http: None,
2719            float_tolerance: None,
2720            float_files: BTreeMap::new(),
2721            unordered: BTreeMap::new(),
2722            effects: None,
2723            fresh: Vec::new(),
2724        })
2725        .unwrap();
2726        let kind = |a: &str, b: &str| settle_text(&norm, a.as_bytes(), b.as_bytes()).1;
2727        assert_eq!(kind("a\nb\n", "a\nb\n"), None);
2728        assert_eq!(kind("x=1\ny=2\n", "y=2\nx=1\n"), Some(NoiseKind::Order));
2729        assert_eq!(kind("at 10:01\n", "at 10:02\n"), Some(NoiseKind::Values));
2730        assert_eq!(kind("a\nz\n", "a\nb\nc\nz\n"), Some(NoiseKind::Lines));
2731        let (kept, _, _) = settle_text(&norm, b"x=1\ny=2\n", b"y=2\nx=1\n");
2732        assert_eq!(kept, b"x=1\ny=2\n", "order noise keeps the lines exactly");
2733    }
2734
2735    #[test]
2736    fn unordered_output_matches_in_any_order_but_not_other_lines() {
2737        let norm = Normalizers::new(&Config {
2738            schema: SCHEMA.to_string(),
2739            name: "app".to_string(),
2740            run: Vec::new(),
2741            normalize: Vec::new(),
2742            normalizers: BTreeMap::new(),
2743            timeout_secs: 30,
2744            http: None,
2745            float_tolerance: None,
2746            float_files: BTreeMap::new(),
2747            unordered: BTreeMap::from([("c".to_string(), vec!["stdout".to_string()])]),
2748            effects: None,
2749            fresh: Vec::new(),
2750        })
2751        .unwrap();
2752        assert!(norm.unordered("c", "stdout"));
2753        assert!(!norm.unordered("c", "stderr"));
2754        let e = b"x=1\ny=2\n";
2755        assert!(compare(&norm, e, b"y=2\nx=1\n", false, true).is_none());
2756        assert!(compare(&norm, e, b"y=2\nx=2\n", false, true).is_some());
2757        assert!(compare(&norm, e, b"x=1\n", false, true).is_some());
2758        assert!(compare(&norm, e, b"y=2\nx=1\n", false, false).is_some());
2759    }
2760
2761    #[test]
2762    fn timestamps_cover_javascript_date_strings() {
2763        let re = Regex::new(TIMESTAMP).unwrap();
2764        let line = "Generated on Sat Nov 21 2026 01:30:12 GMT+0300 (Türkiye Standard Time) - ok";
2765        assert_eq!(re.replace_all(line, "[..]"), "Generated on [..] - ok");
2766        assert_eq!(
2767            re.replace_all("Mon Jan 05 2026 09:00:00 GMT-0800", "[..]"),
2768            "[..]"
2769        );
2770        assert_eq!(re.replace_all("at 2026-11-16T10:00:00Z", "[..]"), "at [..]");
2771        assert_eq!(re.replace_all("Saturday 12", "[..]"), "Saturday 12");
2772    }
2773
2774    #[test]
2775    fn noise_becomes_wildcards() {
2776        assert_eq!(
2777            merge_noise(
2778                "start\nnow: 2026-11-16 10:00:01\nend\n",
2779                "start\nnow: 2026-11-16 10:00:02\nend\n"
2780            ),
2781            "start\nnow: 2026-11-16 10:00:[..]\nend\n"
2782        );
2783        assert_eq!(merge_noise("a\nb\nz\n", "a\nc\nd\nz\n"), "a\n...\nz\n");
2784        assert_eq!(merge_line("id=ab12 ok", "id=cd34 ok"), "id=[..] ok");
2785        let merged = merge_noise("x 1\n", "x 2\n");
2786        assert!(text_matches_exact(&merged, "x 3\n"));
2787    }
2788
2789    #[test]
2790    fn normalizers_by_name() {
2791        let mut config = Config {
2792            schema: SCHEMA.to_string(),
2793            name: "app".to_string(),
2794            run: Vec::new(),
2795            normalize: vec!["timestamps".into(), "uuids".into(), "key-order".into()],
2796            normalizers: BTreeMap::from([("req".to_string(), r"req-\d+".to_string())]),
2797            timeout_secs: 30,
2798            http: None,
2799            float_tolerance: None,
2800            float_files: BTreeMap::new(),
2801            unordered: BTreeMap::new(),
2802            effects: None,
2803            fresh: Vec::new(),
2804        };
2805        let norm = Normalizers::new(&config).unwrap();
2806        assert_eq!(
2807            norm.apply(
2808                "at 2026-11-16T10:00:00.123Z id 123e4567-e89b-12d3-a456-426614174000 req-77"
2809            ),
2810            "at [..] id [..] [..]"
2811        );
2812        assert_eq!(
2813            norm.canonical("{\"b\":1,\"a\":{\"d\":2,\"c\":3}}\nplain"),
2814            "{\"a\":{\"c\":3,\"d\":2},\"b\":1}\nplain"
2815        );
2816        config.normalize.push("nope".into());
2817        assert!(Normalizers::new(&config).is_err());
2818    }
2819
2820    #[test]
2821    fn examples_become_cases() {
2822        let repo = temp_dir("examples").unwrap();
2823        std::fs::write(repo.join("in.txt"), "hello\n").unwrap();
2824        std::fs::write(
2825            repo.join("README.md"),
2826            "# 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",
2827        )
2828        .unwrap();
2829        let names = vec!["tool".to_string()];
2830        let cases = find_examples(&repo, &names);
2831        let args: Vec<Vec<String>> = cases.iter().map(|c| c.args.clone()).collect();
2832        assert_eq!(
2833            args,
2834            [
2835                vec!["count", "in.txt"],
2836                vec!["words"],
2837                vec!["upper", "x y"],
2838                vec!["sort"],
2839            ]
2840        );
2841        assert_eq!(cases[0].files[Path::new("in.txt")], b"hello\n");
2842        assert_eq!(cases[1].stdin.as_deref(), Some(&b"a b\n"[..]));
2843        assert_eq!(cases[2].env["LANG"], "C");
2844        assert_eq!(cases[3].stdin.as_deref(), Some(&b"hello\n"[..]));
2845        std::fs::remove_dir_all(&repo).unwrap();
2846    }
2847
2848    #[test]
2849    fn traps_keep_the_shape_of_the_case() {
2850        let mut base = Case::new(vec!["div".into(), "7".into(), "2".into()]);
2851        base.stdin = Some(b"{\"a\":1}".to_vec());
2852        let traps = trap_cases(&[base]);
2853        assert!(traps.iter().all(|c| c.args[0] == "div"));
2854        assert!(traps.iter().any(|c| c.args == ["div", "-7", "2"]));
2855        assert!(traps.iter().any(|c| c.args == ["div", "7", "0"]));
2856        assert!(
2857            traps
2858                .iter()
2859                .any(|c| c.stdin.as_deref() == Some(JSON_TRAPS[0].as_bytes()))
2860        );
2861        let text = trap_cases(&[Case::new(vec!["upper".into(), "hi".into()])]);
2862        assert!(text.iter().any(|c| c.args[1] == "👍🏽 thumbs"));
2863    }
2864
2865    #[cfg(unix)]
2866    #[test]
2867    fn recording_keeps_all_cases_when_a_generated_name_is_already_used() {
2868        let repo = temp_dir("case-name-collisions").unwrap();
2869        let inputs = repo.join("cases.jsonl");
2870        std::fs::write(
2871            &inputs,
2872            concat!(
2873                "{\"name\":\"x\",\"args\":[\"one\"]}\n",
2874                "{\"name\":\"x-3\",\"args\":[\"two\"]}\n",
2875                "{\"name\":\"x\",\"args\":[\"three\"]}\n"
2876            ),
2877        )
2878        .unwrap();
2879        let recorded = record(&RecordOptions {
2880            repo: &repo,
2881            run: &["/bin/echo".into()],
2882            inputs: Some(&inputs),
2883            normalize: &[],
2884            name: None,
2885            traps: false,
2886            timeout_secs: None,
2887            http: false,
2888            server_args: &[],
2889            fresh: &[],
2890            pace_ms: None,
2891            port: None,
2892            float_tolerance: None,
2893            float_files: &[],
2894            effects: None,
2895        })
2896        .unwrap();
2897        let read = |name: &str| std::fs::read_to_string(recorded.dir.join(name)).unwrap();
2898        assert_eq!(recorded.cases, 3);
2899        assert_eq!(read("x.stdout"), "one\n");
2900        assert_eq!(read("x-3.stdout"), "two\n");
2901        assert_eq!(read("x-4.stdout"), "three\n");
2902        std::fs::remove_dir_all(repo).unwrap();
2903    }
2904
2905    #[test]
2906    fn names_come_from_the_run_command_and_manifests() {
2907        let repo = temp_dir("names").unwrap();
2908        std::fs::create_dir_all(repo.join("out")).unwrap();
2909        std::fs::write(
2910            repo.join("package.json"),
2911            r#"{"name":"x","bin":{"mytool":"b.js"}}"#,
2912        )
2913        .unwrap();
2914        let run: Vec<String> = ["java", "-cp", "out", "Tcli"].map(String::from).to_vec();
2915        assert_eq!(app_names(&repo, &run, None), ["tcli", "mytool"]);
2916        std::fs::remove_dir_all(&repo).unwrap();
2917    }
2918
2919    #[test]
2920    fn python_program_names_are_case_insensitive() {
2921        assert!(is_python_program("PYTHON"));
2922        assert!(is_python_program("/tools/Python3.exe"));
2923        assert!(is_python_program("Py.cmd"));
2924        assert!(!is_python_program("pythonw.exe"));
2925    }
2926
2927    #[test]
2928    fn shell_words() {
2929        assert_eq!(
2930            shell_split(r#"cargo run -q -- "a b" 'c d' e\ f"#).unwrap(),
2931            ["cargo", "run", "-q", "--", "a b", "c d", "e f"]
2932        );
2933        assert!(shell_split("a | b").is_err());
2934        assert!(shell_tokens("echo $(date)").is_none());
2935        assert!(shell_tokens("echo `date`").is_none());
2936        assert_eq!(
2937            shell_split(r"echo \$(date) \`date\`").unwrap(),
2938            ["echo", "$(date)", "`date`"]
2939        );
2940        #[cfg(windows)]
2941        assert_eq!(
2942            shell_split(r"C:\tools\rust-anything\app.exe --flag").unwrap(),
2943            [r"C:\tools\rust-anything\app.exe", "--flag"]
2944        );
2945        #[cfg(windows)]
2946        assert_eq!(
2947            shell_split(r"run C:\$cache\tool.exe").unwrap(),
2948            ["run", r"C:\$cache\tool.exe"]
2949        );
2950        #[cfg(windows)]
2951        assert_eq!(
2952            shell_split(r"\\server\share\tool.exe --flag").unwrap(),
2953            [r"\\server\share\tool.exe", "--flag"]
2954        );
2955        assert_eq!(shell_split(r"echo one\\two").unwrap(), ["echo", r"one\two"]);
2956    }
2957}