Skip to main content

rust_anything/
app.rs

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