Skip to main content

rust_anything/
app.rs

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