Skip to main content

rust_anything/
enable.rs

1//! `enable` and `disable`: switch a ported unit in and out of the app with one command.
2//!
3//! `enable` puts one marked block in each original source file of the unit (TS/JS or Python).
4//! The block loads the built Rust module and rebinds the ported functions, so every caller gets
5//! Rust without an import changing. `disable` removes exactly the lines `enable` added. At run
6//! time `RUST_ANYTHING_MODE=old` or the unit's `RUST_ANYTHING_UNIT_<NAME>=original` keeps the
7//! original, and a module that fails to load falls back to it (`RUST_ANYTHING_MODE=new` makes
8//! that an error instead).
9
10use std::collections::BTreeMap;
11use std::path::{Path, PathBuf};
12use std::process::Command;
13
14use anyhow::{Context, Result, bail};
15use serde::Serialize;
16
17use crate::bridge::{Kind, Manifest};
18use crate::lang::Lang;
19use crate::walk::Canonical;
20
21const START: &str = ">>> rust-anything:";
22const END: &str = "<<< rust-anything:";
23const EOF_NOTE: &str = " (newline added)";
24
25#[derive(Debug, Serialize)]
26pub struct Switched {
27    pub crate_name: String,
28    pub on: bool,
29    /// Source files that changed.
30    pub files: Vec<PathBuf>,
31    /// Functions that run in Rust while the unit is on.
32    pub functions: Vec<String>,
33    /// Exports left to the original, with why.
34    pub skipped: Vec<String>,
35    /// The variable that sends this unit back to the original for one run.
36    pub switch: String,
37}
38
39/// Whether `enable` left its block in any of the unit's files.
40pub fn is_enabled(crate_dir: &Path) -> Result<bool> {
41    let manifest = Manifest::load(crate_dir)?;
42    Ok(files(&manifest).iter().any(|f| {
43        std::fs::read_to_string(manifest.root.join(f))
44            .is_ok_and(|text| find_block(&text, &manifest.crate_name).is_some())
45    }))
46}
47
48/// Sets the unit's kill switch on a command that runs the original, so a recording, diff or
49/// bench of an enabled unit measures the original, not the port.
50pub fn original_only(cmd: &mut Command, manifest: &Manifest) {
51    cmd.env(
52        crate::front_door::kill_switch(&manifest.crate_name),
53        "original",
54    );
55}
56
57pub fn enable(crate_dir: &Path) -> Result<Switched> {
58    enable_only(crate_dir, None, &[])
59}
60
61/// Switches on either all exports (`only = None`) or a specific subset (`only = Some(names)`).
62/// `extra_skipped` holds human-readable skip reasons already decided by the caller (e.g.
63/// per-function diff counts under `--partial`).
64pub fn enable_only(
65    crate_dir: &Path,
66    only: Option<&[String]>,
67    extra_skipped: &[String],
68) -> Result<Switched> {
69    let crate_dir = crate_dir.canonical().with_context(|| {
70        format!(
71            "resolving {} (run `rust-anything bridge` first)",
72            crate_dir.display()
73        )
74    })?;
75    let manifest = Manifest::load(&crate_dir)?;
76    supported(&manifest)?;
77    let selected: Option<Vec<&str>> = match only {
78        Some(names) => {
79            let mut unknown = Vec::new();
80            let mut chosen = Vec::new();
81            for name in names {
82                if manifest.exports.iter().any(|e| e.name == *name) {
83                    if !chosen.contains(&name.as_str()) {
84                        chosen.push(name.as_str());
85                    }
86                } else {
87                    unknown.push(name.as_str());
88                }
89            }
90            if !unknown.is_empty() {
91                let available: Vec<&str> =
92                    manifest.exports.iter().map(|f| f.name.as_str()).collect();
93                let noun = if unknown.len() == 1 {
94                    "export"
95                } else {
96                    "exports"
97                };
98                bail!(
99                    "unknown {noun} in {}: {} (exports: {})",
100                    manifest.crate_name,
101                    unknown.join(", "),
102                    available.join(", ")
103                );
104            }
105            if manifest.language == Lang::Powershell && chosen.len() < manifest.exports.len() {
106                bail!(
107                    "partial enable (--only / --partial) is not supported for PowerShell units: \
108                     dot-sourcing the wrapper rebinds every function in the file"
109                );
110            }
111            Some(chosen)
112        }
113        None => None,
114    };
115    let switch = crate::front_door::kill_switch(&manifest.crate_name);
116    let mut by_file: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
117    for f in &manifest.exports {
118        by_file.entry(&f.file).or_default().push(&f.name);
119    }
120    let mut skipped: Vec<String> = manifest
121        .js_only
122        .iter()
123        .map(|j| format!("{}: kept in the original", j.name))
124        .collect();
125    skipped.extend(extra_skipped.iter().cloned());
126    if let Some(chosen) = &selected {
127        for f in &manifest.exports {
128            if !chosen.contains(&f.name.as_str())
129                && !extra_skipped
130                    .iter()
131                    .any(|s| s.starts_with(&format!("{}:", f.name)))
132            {
133                skipped.push(format!(
134                    "{}: not selected (--only), kept in the original",
135                    f.name
136                ));
137            }
138        }
139    }
140    let mut out = Switched {
141        crate_name: manifest.crate_name.clone(),
142        on: true,
143        files: Vec::new(),
144        functions: Vec::new(),
145        skipped,
146        switch: switch.clone(),
147    };
148    let mut edits = Vec::new();
149    for (file, names) in by_file {
150        let path = manifest.root.join(file);
151        let text = std::fs::read_to_string(&path)
152            .with_context(|| format!("reading {}", path.display()))?;
153        let base = remove(&text, &manifest.crate_name).unwrap_or_else(|| text.clone());
154        let wanted: Vec<&str> = match &selected {
155            Some(chosen) => names.into_iter().filter(|n| chosen.contains(n)).collect(),
156            None => names,
157        };
158        let (swap, skip): (Vec<&str>, Vec<&str>) = wanted
159            .into_iter()
160            .partition(|n| declared(&base, n, manifest.language));
161        out.skipped.extend(skip.iter().map(|n| {
162            format!("{n}: not a plain function declaration in {file}, so callers keep the original")
163        }));
164        if swap.is_empty() {
165            if base != text {
166                edits.push((path.clone(), base));
167                out.files.push(path);
168            }
169            continue;
170        }
171        let dir = path
172            .parent()
173            .context("source file has no folder")?
174            .canonical()?;
175        let block = match manifest.language {
176            Lang::Python => python_block(&manifest, &crate_dir, &dir, &swap, &switch),
177            Lang::Powershell => powershell_block(&manifest, &crate_dir, &dir, &switch),
178            _ => js_block(
179                &manifest,
180                &crate_dir,
181                &dir,
182                &swap,
183                &switch,
184                esm(file, &base),
185            ),
186        };
187        let edited = insert(&base, &block, manifest.language);
188        if edited != text {
189            edits.push((path.clone(), edited));
190            out.files.push(path);
191        }
192        out.functions.extend(swap.iter().map(|n| n.to_string()));
193    }
194    if out.functions.is_empty() {
195        bail!(
196            "nothing to switch on in {}: {}",
197            manifest.crate_name,
198            out.skipped.join("; ")
199        );
200    }
201    for (path, text) in edits {
202        std::fs::write(&path, text).with_context(|| format!("writing {}", path.display()))?;
203    }
204    Ok(out)
205}
206
207/// Picks which exports to switch on from per-function diff counts.
208///
209/// - When `only` is non-empty (`--only`), validates each requested export exists and that all of
210///   its recorded cases match, returning `(selected, skipped_reasons)`.
211/// - When `only` is empty (`--partial`), selects every export whose recorded cases all match and
212///   lists the rest as `"<name>: <passed>/<total> match, kept in the original"`.
213pub fn select_matching(
214    manifest: &Manifest,
215    outcome: &crate::harness::DiffOutcome,
216    counts: &BTreeMap<String, (usize, usize)>,
217    only: &[String],
218) -> Result<(Vec<String>, Vec<String>)> {
219    let status = |name: &str| -> (bool, String) {
220        if outcome.missing.iter().any(|m| m == name) {
221            return (
222                false,
223                format!("{name}: missing from the Rust module, kept in the original"),
224            );
225        }
226        match counts.get(name).copied() {
227            Some((passed, total)) if total > 0 && passed == total => (true, String::new()),
228            Some((passed, total)) if total > 0 => (
229                false,
230                format!("{name}: {passed}/{total} match, kept in the original"),
231            ),
232            _ => (
233                false,
234                format!("{name}: no recorded cases, kept in the original"),
235            ),
236        }
237    };
238
239    if !only.is_empty() {
240        let mut unknown = Vec::new();
241        let mut selected = Vec::new();
242        let mut failures = Vec::new();
243        for name in only {
244            if !manifest.exports.iter().any(|e| e.name == *name) {
245                unknown.push(name.as_str());
246                continue;
247            }
248            if selected.contains(name) {
249                continue;
250            }
251            let (ok, reason) = status(name);
252            if ok {
253                selected.push(name.clone());
254            } else {
255                failures.push(reason);
256            }
257        }
258        if !unknown.is_empty() {
259            let available: Vec<&str> = manifest.exports.iter().map(|f| f.name.as_str()).collect();
260            let noun = if unknown.len() == 1 {
261                "export"
262            } else {
263                "exports"
264            };
265            bail!(
266                "unknown {noun} in {}: {} (exports: {})",
267                manifest.crate_name,
268                unknown.join(", "),
269                available.join(", ")
270            );
271        }
272        if !failures.is_empty() {
273            let (noun, verb) = if failures.len() == 1 {
274                ("function", "does")
275            } else {
276                ("functions", "do")
277            };
278            bail!(
279                "requested {noun} {verb} not match all recorded cases ({}); pass --force to switch them on anyway",
280                failures.join("; ")
281            );
282        }
283        let skipped = manifest
284            .exports
285            .iter()
286            .filter(|e| !selected.contains(&e.name))
287            .map(|e| format!("{}: not selected (--only), kept in the original", e.name))
288            .collect();
289        return Ok((selected, skipped));
290    }
291
292    let mut selected = Vec::new();
293    let mut skipped = Vec::new();
294    for e in &manifest.exports {
295        let (ok, reason) = status(&e.name);
296        if ok {
297            selected.push(e.name.clone());
298        } else {
299            skipped.push(reason);
300        }
301    }
302    if selected.is_empty() {
303        bail!(
304            "no functions in {} have all recorded cases matching ({})",
305            manifest.crate_name,
306            skipped.join("; ")
307        );
308    }
309    Ok((selected, skipped))
310}
311
312pub fn disable(crate_dir: &Path) -> Result<Switched> {
313    let crate_dir = crate_dir.canonical().with_context(|| {
314        format!(
315            "resolving {} (run `rust-anything bridge` first)",
316            crate_dir.display()
317        )
318    })?;
319    let manifest = Manifest::load(&crate_dir)?;
320    let mut out = Switched {
321        crate_name: manifest.crate_name.clone(),
322        on: false,
323        files: Vec::new(),
324        functions: Vec::new(),
325        skipped: Vec::new(),
326        switch: crate::front_door::kill_switch(&manifest.crate_name),
327    };
328    for file in files(&manifest) {
329        let path = manifest.root.join(file);
330        let Ok(text) = std::fs::read_to_string(&path) else {
331            continue;
332        };
333        if let Some(restored) = remove(&text, &manifest.crate_name) {
334            std::fs::write(&path, restored)
335                .with_context(|| format!("writing {}", path.display()))?;
336            out.files.push(path);
337        }
338    }
339    out.functions = manifest.exports.iter().map(|f| f.name.clone()).collect();
340    Ok(out)
341}
342
343pub fn is_supported(manifest: &Manifest) -> bool {
344    matches!(
345        (manifest.language, manifest.kind),
346        (Lang::Python, Kind::Pyo3)
347            | (Lang::Ts, Kind::Napi | Kind::Wasm)
348            | (Lang::Powershell, Kind::Ffi)
349    )
350}
351
352fn supported(manifest: &Manifest) -> Result<()> {
353    match manifest.language {
354        _ if is_supported(manifest) => Ok(()),
355        lang => bail!(
356            "`enable` switches TS/JS, Python and PowerShell ports in place; for {} use the shadow module \
357             (`rust-anything shadow`), imported where the app imported the original, and \
358             RUST_ANYTHING_MODE=old|shadow|new",
359            lang.name()
360        ),
361    }
362}
363
364fn files(manifest: &Manifest) -> Vec<&str> {
365    let mut files: Vec<&str> = manifest.exports.iter().map(|f| f.file.as_str()).collect();
366    files.sort_unstable();
367    files.dedup();
368    files
369}
370
371/// A function the block can rebind: a top-level `def` (Python) or a `function` declaration.
372fn declared(text: &str, name: &str, lang: Lang) -> bool {
373    let name = regex::escape(name);
374    let pattern = if lang == Lang::Python {
375        format!(r"(?m)^(async\s+)?def\s+{name}\s*\(")
376    } else if lang == Lang::Powershell {
377        format!(r"(?mi)^\s*function\s+{name}\s*[{{(\s]")
378    } else {
379        format!(r"(?m)^\s*(export\s+)?(default\s+)?(async\s+)?function\s*\*?\s*{name}\s*[<(]")
380    };
381    regex::Regex::new(&pattern).is_ok_and(|re| re.is_match(text))
382}
383
384fn esm(file: &str, text: &str) -> bool {
385    if file.ends_with(".cjs") || file.ends_with(".cts") {
386        return false;
387    }
388    file.ends_with(".mjs")
389        || file.ends_with(".mts")
390        || text
391            .lines()
392            .any(|l| l.starts_with("import ") || l.starts_with("export "))
393}
394
395fn marker(comment: &str, crate_name: &str, crate_dir: &Path, dir: &Path) -> (String, String) {
396    let at = crate::shadow::relative(dir, crate_dir);
397    (
398        format!(
399            "{comment} {START} {crate_name} is on. `rust-anything disable {at}` removes this block."
400        ),
401        format!("{comment} {END} {crate_name}"),
402    )
403}
404
405fn js_block(
406    manifest: &Manifest,
407    crate_dir: &Path,
408    dir: &Path,
409    names: &[&str],
410    switch: &str,
411    esm: bool,
412) -> String {
413    let (start, end) = marker("//", &manifest.crate_name, crate_dir, dir);
414    // `index.cjs` for every kind, including wasm: the raw `pkg/<crate>.js` wasm-bindgen module
415    // takes pre-serialized JSON strings, while the wrapper accepts the JS values a caller passes
416    // and maps the `$num`/`$undefined` markers.
417    let module = crate_dir.join("index.cjs");
418    let rel = crate::shadow::relative(dir, &module);
419    let here = if esm {
420        "import.meta.dirname"
421    } else {
422        "__dirname"
423    };
424    let var = format!(
425        "__rustAnything_{}",
426        crate::front_door::ident(&manifest.crate_name)
427    );
428    let assign: Vec<String> = names.iter().map(|n| format!("{n} = {var}.{n}")).collect();
429    format!(
430        "{start}\n\
431         // @ts-ignore\n\
432         const {var} = ((p) => p && p.env.RUST_ANYTHING_MODE !== 'old' && p.env.{switch} !== 'original' && (() => {{ try {{ const m = p.getBuiltinModule('node:module'); const at = p.getBuiltinModule('node:path').join({here}, {rel:?}); return m.createRequire(at)(at) }} catch (e) {{ if (p.env.RUST_ANYTHING_MODE === 'new') throw e }} }})())(globalThis.process)\n\
433         // @ts-ignore\n\
434         if ({var}) {{ {} }}\n\
435         {end}\n",
436        assign.join("; ")
437    )
438}
439
440fn python_block(
441    manifest: &Manifest,
442    crate_dir: &Path,
443    dir: &Path,
444    names: &[&str],
445    switch: &str,
446) -> String {
447    let (start, end) = marker("#", &manifest.crate_name, crate_dir, dir);
448    let (package_dir, lib) = crate::harness_py::package(crate_dir, manifest);
449    let rel = crate::shadow::relative(dir, &package_dir);
450    let fun = format!(
451        "_rust_anything_{}",
452        crate::front_door::ident(&manifest.crate_name)
453    );
454    let names: Vec<String> = names.iter().map(|n| format!("{n:?}")).collect();
455    format!(
456        "{start}\n\
457         def {fun}():\n\
458         \x20   import importlib, os, sys\n\
459         \x20   mode = os.environ.get(\"RUST_ANYTHING_MODE\")\n\
460         \x20   if mode == \"old\" or os.environ.get(\"{switch}\") == \"original\":\n\
461         \x20       return\n\
462         \x20   at = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), {rel:?}))\n\
463         \x20   sys.path.insert(0, at)\n\
464         \x20   try:\n\
465         \x20       native = importlib.import_module({lib:?})\n\
466         \x20   except ImportError:\n\
467         \x20       if mode == \"new\":\n\
468         \x20           raise\n\
469         \x20       return\n\
470         \x20   finally:\n\
471         \x20       sys.path.remove(at)\n\
472         \x20   globals().update({{name: getattr(native, name) for name in [{}]}})\n\
473         \n\
474         \n\
475         {fun}()\n\
476         del {fun}\n\
477         {end}\n",
478        names.join(", ")
479    )
480}
481
482fn powershell_block(manifest: &Manifest, crate_dir: &Path, dir: &Path, switch: &str) -> String {
483    let (start, end) = marker("#", &manifest.crate_name, crate_dir, dir);
484    let wrapper = crate_dir.join(crate::codegen_powershell::wrapper_path(manifest));
485    let rel = crate::shadow::relative(dir, &wrapper).replace('\'', "''");
486    format!(
487        "{start}\n\
488         if ($env:RUST_ANYTHING_MODE -ne 'old' -and $env:{switch} -ne 'original') {{\n\
489         \x20   try {{\n\
490         \x20       . (Join-Path $PSScriptRoot '{rel}')\n\
491         \x20   }} catch {{\n\
492         \x20       if ($env:RUST_ANYTHING_MODE -eq 'new') {{ throw }}\n\
493         \x20   }}\n\
494         }}\n\
495         {end}\n"
496    )
497}
498
499/// Puts the block on its own lines: Python before a top-level `if __name__ == "__main__":`
500/// (else at the end, after every `def`), JS after a shebang and `"use strict"`, where hoisted
501/// function declarations can already be rebound.
502fn insert(text: &str, block: &str, lang: Lang) -> String {
503    let at = if lang == Lang::Powershell {
504        crate::lang::powershell::after_functions(text).unwrap_or(text.len())
505    } else if lang == Lang::Python {
506        line_starts(text)
507            .find(|&i| {
508                let line = &text[i..];
509                line.starts_with("if __name__ == \"__main__\"")
510                    || line.starts_with("if __name__ == '__main__'")
511            })
512            .unwrap_or(text.len())
513    } else {
514        line_starts(text)
515            .find(|&i| {
516                let line = text[i..].lines().next().unwrap_or_default().trim();
517                !(line.starts_with("#!")
518                    || line == "'use strict'"
519                    || line == "\"use strict\""
520                    || line == "'use strict';"
521                    || line == "\"use strict\";")
522            })
523            .unwrap_or(text.len())
524    };
525    let mut out = String::with_capacity(text.len() + block.len() + 1);
526    out.push_str(&text[..at]);
527    if at == text.len() && !text.is_empty() && !text.ends_with('\n') {
528        out.push('\n');
529        let (first, rest) = block.split_once('\n').unwrap_or((block, ""));
530        out.push_str(first);
531        out.push_str(EOF_NOTE);
532        out.push('\n');
533        out.push_str(rest);
534    } else {
535        out.push_str(block);
536    }
537    out.push_str(&text[at..]);
538    out
539}
540
541fn line_starts(text: &str) -> impl Iterator<Item = usize> + '_ {
542    std::iter::once(0)
543        .chain(text.match_indices('\n').map(|(i, _)| i + 1))
544        .filter(move |&i| i < text.len())
545}
546
547/// The byte range of the unit's block, from its first line to the end of its last.
548fn find_block(text: &str, crate_name: &str) -> Option<(usize, usize, bool)> {
549    let start_tag = format!("{START} {crate_name} is on.");
550    let end_tag = format!("{END} {crate_name}");
551    let mut start = None;
552    for i in std::iter::once(0).chain(text.match_indices('\n').map(|(i, _)| i + 1)) {
553        let line = text[i..].split('\n').next().unwrap_or_default();
554        match start {
555            None if line.contains(&start_tag) => start = Some((i, line.ends_with(EOF_NOTE))),
556            Some((s, added)) if line.trim_end().ends_with(&end_tag) => {
557                let end = (i + line.len() + 1).min(text.len());
558                return Some((s, end, added));
559            }
560            _ => {}
561        }
562    }
563    None
564}
565
566fn remove(text: &str, crate_name: &str) -> Option<String> {
567    let (start, end, added) = find_block(text, crate_name)?;
568    let start = if added && end == text.len() && start > 0 {
569        start - 1
570    } else {
571        start
572    };
573    Some(format!("{}{}", &text[..start], &text[end..]))
574}
575
576#[cfg(test)]
577mod tests {
578    use super::*;
579
580    const BLOCK: &str = "# >>> rust-anything: fuzzy-rs is on. `rust-anything disable x` removes this block.\nx = 1\n# <<< rust-anything: fuzzy-rs\n";
581
582    #[test]
583    fn python_goes_before_the_main_guard_and_comes_out_byte_for_byte() {
584        let text = "def f(a):\n    return a\n\nif __name__ == \"__main__\":\n    print(f(1))\n";
585        let on = insert(text, BLOCK, Lang::Python);
586        assert!(
587            on.find("x = 1").unwrap() < on.find("if __name__").unwrap(),
588            "{on}"
589        );
590        assert_eq!(remove(&on, "fuzzy-rs").unwrap(), text);
591        assert!(remove(text, "fuzzy-rs").is_none());
592    }
593
594    #[test]
595    fn a_file_without_a_final_newline_gets_it_back_the_same() {
596        let text = "def f(a):\n    return a";
597        let on = insert(text, BLOCK, Lang::Python);
598        assert!(on.contains(EOF_NOTE), "{on}");
599        assert_eq!(remove(&on, "fuzzy-rs").unwrap(), text);
600    }
601
602    #[test]
603    fn js_goes_after_the_shebang_and_use_strict() {
604        let text = "#!/usr/bin/env node\n'use strict'\nfunction f(a) { return a }\nmodule.exports = { f }\n";
605        let block = BLOCK.replace('#', "//");
606        let on = insert(text, &block, Lang::Ts);
607        assert!(
608            on.starts_with("#!/usr/bin/env node\n'use strict'\n// >>>"),
609            "{on}"
610        );
611        assert_eq!(remove(&on, "fuzzy-rs").unwrap(), text);
612    }
613
614    #[test]
615    fn only_declarations_can_be_rebound() {
616        let js = "export function score(a: string): number { return 1 }\nexport const other = () => 2\nexport async function* gen<T>(x: T) {}\n";
617        assert!(declared(js, "score", Lang::Ts));
618        assert!(!declared(js, "other", Lang::Ts));
619        assert!(declared(js, "gen", Lang::Ts));
620        let py = "def dedupe(names):\n    pass\n\nclass A:\n    def inner(self):\n        pass\n";
621        assert!(declared(py, "dedupe", Lang::Python));
622        assert!(!declared(py, "inner", Lang::Python));
623    }
624
625    #[test]
626    fn module_kind_follows_the_syntax() {
627        assert!(esm("a.ts", "import x from 'y'\n"));
628        assert!(esm("a.mjs", ""));
629        assert!(!esm(
630            "a.js",
631            "const x = require('y')\nmodule.exports = {}\n"
632        ));
633        assert!(!esm("a.cjs", "export function f() {}\n"));
634    }
635
636    #[test]
637    fn select_matching_handles_partial_and_only_modes() {
638        use crate::harness::DiffOutcome;
639        use crate::ts::exports::ExportedFn;
640
641        let export = |name: &str| ExportedFn {
642            name: name.into(),
643            file: "util.py".into(),
644            line: 1,
645            ..Default::default()
646        };
647        let manifest = Manifest {
648            schema: "1".into(),
649            root: PathBuf::from("/tmp"),
650            root_written: None,
651            unit: "util.py".into(),
652            language: Lang::Python,
653            kind: Kind::Pyo3,
654            crate_name: "util-rs".into(),
655            exports: vec![export("slug"), export("words"), export("missing_fn")],
656            classes: Vec::new(),
657            js_only: Vec::new(),
658            batches: Vec::new(),
659            allocator: Default::default(),
660            float_tolerance: None,
661            ignore_key_order: false,
662            end_state: None,
663        };
664        let outcome = DiffOutcome {
665            total: 446,
666            passed: 223,
667            failed: 223,
668            missing: vec!["missing_fn".into()],
669            ..Default::default()
670        };
671        let counts = BTreeMap::from([
672            ("slug".into(), (223, 223)),
673            ("words".into(), (0, 223)),
674            ("missing_fn".into(), (0, 10)),
675        ]);
676
677        // --partial picks only `slug` and reports per-function skip reasons for the rest.
678        let (selected, skipped) = select_matching(&manifest, &outcome, &counts, &[]).unwrap();
679        assert_eq!(selected, ["slug"]);
680        assert_eq!(
681            skipped,
682            [
683                "words: 0/223 match, kept in the original",
684                "missing_fn: missing from the Rust module, kept in the original",
685            ]
686        );
687
688        // --only accepts a matching function even while others fail.
689        let (selected, skipped) =
690            select_matching(&manifest, &outcome, &counts, &["slug".into()]).unwrap();
691        assert_eq!(selected, ["slug"]);
692        assert_eq!(skipped.len(), 2);
693
694        // --only rejects a failing requested function (singular for 1, plural for 2+).
695        let err = select_matching(&manifest, &outcome, &counts, &["words".into()]).unwrap_err();
696        assert!(
697            format!("{err:#}").contains("requested function does not match all recorded cases"),
698            "{err:#}"
699        );
700        assert!(format!("{err:#}").contains("words: 0/223 match"), "{err:#}");
701
702        let err_multi = select_matching(
703            &manifest,
704            &outcome,
705            &counts,
706            &["words".into(), "missing_fn".into()],
707        )
708        .unwrap_err();
709        assert!(
710            format!("{err_multi:#}")
711                .contains("requested functions do not match all recorded cases"),
712            "{err_multi:#}"
713        );
714
715        // --only rejects an unknown export name (singular for 1, plural for 2+).
716        let err = select_matching(&manifest, &outcome, &counts, &["nope".into()]).unwrap_err();
717        assert!(
718            format!("{err:#}").contains("unknown export in util-rs: nope"),
719            "{err:#}"
720        );
721        assert!(
722            format!("{err:#}").contains("(exports: slug, words, missing_fn)"),
723            "{err:#}"
724        );
725
726        let err_two = select_matching(
727            &manifest,
728            &outcome,
729            &counts,
730            &["nope".into(), "nada".into()],
731        )
732        .unwrap_err();
733        assert!(
734            format!("{err_two:#}").contains("unknown exports in util-rs: nope, nada"),
735            "{err_two:#}"
736        );
737
738        // --partial fails clearly when nothing matches.
739        let none_counts = BTreeMap::from([("slug".into(), (1, 2)), ("words".into(), (0, 223))]);
740        let err = select_matching(&manifest, &outcome, &none_counts, &[]).unwrap_err();
741        assert!(
742            format!("{err:#}").contains("no functions in util-rs have all recorded cases matching"),
743            "{err:#}"
744        );
745    }
746}