1use 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 pub files: Vec<PathBuf>,
31 pub functions: Vec<String>,
33 pub skipped: Vec<String>,
35 pub switch: String,
37}
38
39pub 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
48pub 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
61pub 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 bail!(
94 "unknown export(s) in {}: {} (exports: {})",
95 manifest.crate_name,
96 unknown.join(", "),
97 available.join(", ")
98 );
99 }
100 if manifest.language == Lang::Powershell && chosen.len() < manifest.exports.len() {
101 bail!(
102 "partial enable (--only / --partial) is not supported for PowerShell units: \
103 dot-sourcing the wrapper rebinds every function in the file"
104 );
105 }
106 Some(chosen)
107 }
108 None => None,
109 };
110 let switch = crate::front_door::kill_switch(&manifest.crate_name);
111 let mut by_file: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
112 for f in &manifest.exports {
113 by_file.entry(&f.file).or_default().push(&f.name);
114 }
115 let mut skipped: Vec<String> = manifest
116 .js_only
117 .iter()
118 .map(|j| format!("{}: kept in the original", j.name))
119 .collect();
120 skipped.extend(extra_skipped.iter().cloned());
121 if let Some(chosen) = &selected {
122 for f in &manifest.exports {
123 if !chosen.contains(&f.name.as_str())
124 && !extra_skipped
125 .iter()
126 .any(|s| s.starts_with(&format!("{}:", f.name)))
127 {
128 skipped.push(format!(
129 "{}: not selected (--only), kept in the original",
130 f.name
131 ));
132 }
133 }
134 }
135 let mut out = Switched {
136 crate_name: manifest.crate_name.clone(),
137 on: true,
138 files: Vec::new(),
139 functions: Vec::new(),
140 skipped,
141 switch: switch.clone(),
142 };
143 let mut edits = Vec::new();
144 for (file, names) in by_file {
145 let path = manifest.root.join(file);
146 let text = std::fs::read_to_string(&path)
147 .with_context(|| format!("reading {}", path.display()))?;
148 let base = remove(&text, &manifest.crate_name).unwrap_or_else(|| text.clone());
149 let wanted: Vec<&str> = match &selected {
150 Some(chosen) => names.into_iter().filter(|n| chosen.contains(n)).collect(),
151 None => names,
152 };
153 let (swap, skip): (Vec<&str>, Vec<&str>) = wanted
154 .into_iter()
155 .partition(|n| declared(&base, n, manifest.language));
156 out.skipped.extend(skip.iter().map(|n| {
157 format!("{n}: not a plain function declaration in {file}, so callers keep the original")
158 }));
159 if swap.is_empty() {
160 if base != text {
161 edits.push((path.clone(), base));
162 out.files.push(path);
163 }
164 continue;
165 }
166 let dir = path
167 .parent()
168 .context("source file has no folder")?
169 .canonical()?;
170 let block = match manifest.language {
171 Lang::Python => python_block(&manifest, &crate_dir, &dir, &swap, &switch),
172 Lang::Powershell => powershell_block(&manifest, &crate_dir, &dir, &switch),
173 _ => js_block(
174 &manifest,
175 &crate_dir,
176 &dir,
177 &swap,
178 &switch,
179 esm(file, &base),
180 ),
181 };
182 let edited = insert(&base, &block, manifest.language);
183 if edited != text {
184 edits.push((path.clone(), edited));
185 out.files.push(path);
186 }
187 out.functions.extend(swap.iter().map(|n| n.to_string()));
188 }
189 if out.functions.is_empty() {
190 bail!(
191 "nothing to switch on in {}: {}",
192 manifest.crate_name,
193 out.skipped.join("; ")
194 );
195 }
196 for (path, text) in edits {
197 std::fs::write(&path, text).with_context(|| format!("writing {}", path.display()))?;
198 }
199 Ok(out)
200}
201
202pub fn select_matching(
209 manifest: &Manifest,
210 outcome: &crate::harness::DiffOutcome,
211 counts: &BTreeMap<String, (usize, usize)>,
212 only: &[String],
213) -> Result<(Vec<String>, Vec<String>)> {
214 let status = |name: &str| -> (bool, String) {
215 if outcome.missing.iter().any(|m| m == name) {
216 return (
217 false,
218 format!("{name}: missing from the Rust module, kept in the original"),
219 );
220 }
221 match counts.get(name).copied() {
222 Some((passed, total)) if total > 0 && passed == total => (true, String::new()),
223 Some((passed, total)) if total > 0 => (
224 false,
225 format!("{name}: {passed}/{total} match, kept in the original"),
226 ),
227 _ => (
228 false,
229 format!("{name}: no recorded cases, kept in the original"),
230 ),
231 }
232 };
233
234 if !only.is_empty() {
235 let mut unknown = Vec::new();
236 let mut selected = Vec::new();
237 let mut failures = Vec::new();
238 for name in only {
239 if !manifest.exports.iter().any(|e| e.name == *name) {
240 unknown.push(name.as_str());
241 continue;
242 }
243 if selected.contains(name) {
244 continue;
245 }
246 let (ok, reason) = status(name);
247 if ok {
248 selected.push(name.clone());
249 } else {
250 failures.push(reason);
251 }
252 }
253 if !unknown.is_empty() {
254 let available: Vec<&str> = manifest.exports.iter().map(|f| f.name.as_str()).collect();
255 bail!(
256 "unknown export(s) in {}: {} (exports: {})",
257 manifest.crate_name,
258 unknown.join(", "),
259 available.join(", ")
260 );
261 }
262 if !failures.is_empty() {
263 bail!(
264 "requested function(s) do not match all recorded cases ({}); pass --force to switch them on anyway",
265 failures.join("; ")
266 );
267 }
268 let skipped = manifest
269 .exports
270 .iter()
271 .filter(|e| !selected.contains(&e.name))
272 .map(|e| format!("{}: not selected (--only), kept in the original", e.name))
273 .collect();
274 return Ok((selected, skipped));
275 }
276
277 let mut selected = Vec::new();
278 let mut skipped = Vec::new();
279 for e in &manifest.exports {
280 let (ok, reason) = status(&e.name);
281 if ok {
282 selected.push(e.name.clone());
283 } else {
284 skipped.push(reason);
285 }
286 }
287 if selected.is_empty() {
288 bail!(
289 "no functions in {} have all recorded cases matching ({})",
290 manifest.crate_name,
291 skipped.join("; ")
292 );
293 }
294 Ok((selected, skipped))
295}
296
297pub fn disable(crate_dir: &Path) -> Result<Switched> {
298 let crate_dir = crate_dir.canonical().with_context(|| {
299 format!(
300 "resolving {} (run `rust-anything bridge` first)",
301 crate_dir.display()
302 )
303 })?;
304 let manifest = Manifest::load(&crate_dir)?;
305 let mut out = Switched {
306 crate_name: manifest.crate_name.clone(),
307 on: false,
308 files: Vec::new(),
309 functions: Vec::new(),
310 skipped: Vec::new(),
311 switch: crate::front_door::kill_switch(&manifest.crate_name),
312 };
313 for file in files(&manifest) {
314 let path = manifest.root.join(file);
315 let Ok(text) = std::fs::read_to_string(&path) else {
316 continue;
317 };
318 if let Some(restored) = remove(&text, &manifest.crate_name) {
319 std::fs::write(&path, restored)
320 .with_context(|| format!("writing {}", path.display()))?;
321 out.files.push(path);
322 }
323 }
324 out.functions = manifest.exports.iter().map(|f| f.name.clone()).collect();
325 Ok(out)
326}
327
328pub fn is_supported(manifest: &Manifest) -> bool {
329 matches!(
330 (manifest.language, manifest.kind),
331 (Lang::Python, Kind::Pyo3)
332 | (Lang::Ts, Kind::Napi | Kind::Wasm)
333 | (Lang::Powershell, Kind::Ffi)
334 )
335}
336
337fn supported(manifest: &Manifest) -> Result<()> {
338 match manifest.language {
339 _ if is_supported(manifest) => Ok(()),
340 lang => bail!(
341 "`enable` switches TS/JS, Python and PowerShell ports in place; for {} use the shadow module \
342 (`rust-anything shadow`), imported where the app imported the original, and \
343 RUST_ANYTHING_MODE=old|shadow|new",
344 lang.name()
345 ),
346 }
347}
348
349fn files(manifest: &Manifest) -> Vec<&str> {
350 let mut files: Vec<&str> = manifest.exports.iter().map(|f| f.file.as_str()).collect();
351 files.sort_unstable();
352 files.dedup();
353 files
354}
355
356fn declared(text: &str, name: &str, lang: Lang) -> bool {
358 let name = regex::escape(name);
359 let pattern = if lang == Lang::Python {
360 format!(r"(?m)^(async\s+)?def\s+{name}\s*\(")
361 } else if lang == Lang::Powershell {
362 format!(r"(?mi)^\s*function\s+{name}\s*[{{(\s]")
363 } else {
364 format!(r"(?m)^\s*(export\s+)?(default\s+)?(async\s+)?function\s*\*?\s*{name}\s*[<(]")
365 };
366 regex::Regex::new(&pattern).is_ok_and(|re| re.is_match(text))
367}
368
369fn esm(file: &str, text: &str) -> bool {
370 if file.ends_with(".cjs") || file.ends_with(".cts") {
371 return false;
372 }
373 file.ends_with(".mjs")
374 || file.ends_with(".mts")
375 || text
376 .lines()
377 .any(|l| l.starts_with("import ") || l.starts_with("export "))
378}
379
380fn marker(comment: &str, crate_name: &str, crate_dir: &Path, dir: &Path) -> (String, String) {
381 let at = crate::shadow::relative(dir, crate_dir);
382 (
383 format!(
384 "{comment} {START} {crate_name} is on. `rust-anything disable {at}` removes this block."
385 ),
386 format!("{comment} {END} {crate_name}"),
387 )
388}
389
390fn js_block(
391 manifest: &Manifest,
392 crate_dir: &Path,
393 dir: &Path,
394 names: &[&str],
395 switch: &str,
396 esm: bool,
397) -> String {
398 let (start, end) = marker("//", &manifest.crate_name, crate_dir, dir);
399 let module = crate_dir.join("index.cjs");
403 let rel = crate::shadow::relative(dir, &module);
404 let here = if esm {
405 "import.meta.dirname"
406 } else {
407 "__dirname"
408 };
409 let var = format!(
410 "__rustAnything_{}",
411 crate::front_door::ident(&manifest.crate_name)
412 );
413 let assign: Vec<String> = names.iter().map(|n| format!("{n} = {var}.{n}")).collect();
414 format!(
415 "{start}\n\
416 // @ts-ignore\n\
417 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\
418 // @ts-ignore\n\
419 if ({var}) {{ {} }}\n\
420 {end}\n",
421 assign.join("; ")
422 )
423}
424
425fn python_block(
426 manifest: &Manifest,
427 crate_dir: &Path,
428 dir: &Path,
429 names: &[&str],
430 switch: &str,
431) -> String {
432 let (start, end) = marker("#", &manifest.crate_name, crate_dir, dir);
433 let (package_dir, lib) = crate::harness_py::package(crate_dir, manifest);
434 let rel = crate::shadow::relative(dir, &package_dir);
435 let fun = format!(
436 "_rust_anything_{}",
437 crate::front_door::ident(&manifest.crate_name)
438 );
439 let names: Vec<String> = names.iter().map(|n| format!("{n:?}")).collect();
440 format!(
441 "{start}\n\
442 def {fun}():\n\
443 \x20 import importlib, os, sys\n\
444 \x20 mode = os.environ.get(\"RUST_ANYTHING_MODE\")\n\
445 \x20 if mode == \"old\" or os.environ.get(\"{switch}\") == \"original\":\n\
446 \x20 return\n\
447 \x20 at = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), {rel:?}))\n\
448 \x20 sys.path.insert(0, at)\n\
449 \x20 try:\n\
450 \x20 native = importlib.import_module({lib:?})\n\
451 \x20 except ImportError:\n\
452 \x20 if mode == \"new\":\n\
453 \x20 raise\n\
454 \x20 return\n\
455 \x20 finally:\n\
456 \x20 sys.path.remove(at)\n\
457 \x20 globals().update({{name: getattr(native, name) for name in [{}]}})\n\
458 \n\
459 \n\
460 {fun}()\n\
461 del {fun}\n\
462 {end}\n",
463 names.join(", ")
464 )
465}
466
467fn powershell_block(manifest: &Manifest, crate_dir: &Path, dir: &Path, switch: &str) -> String {
468 let (start, end) = marker("#", &manifest.crate_name, crate_dir, dir);
469 let wrapper = crate_dir.join(crate::codegen_powershell::wrapper_path(manifest));
470 let rel = crate::shadow::relative(dir, &wrapper).replace('\'', "''");
471 format!(
472 "{start}\n\
473 if ($env:RUST_ANYTHING_MODE -ne 'old' -and $env:{switch} -ne 'original') {{\n\
474 \x20 try {{\n\
475 \x20 . (Join-Path $PSScriptRoot '{rel}')\n\
476 \x20 }} catch {{\n\
477 \x20 if ($env:RUST_ANYTHING_MODE -eq 'new') {{ throw }}\n\
478 \x20 }}\n\
479 }}\n\
480 {end}\n"
481 )
482}
483
484fn insert(text: &str, block: &str, lang: Lang) -> String {
488 let at = if lang == Lang::Powershell {
489 crate::lang::powershell::after_functions(text).unwrap_or(text.len())
490 } else if lang == Lang::Python {
491 line_starts(text)
492 .find(|&i| {
493 let line = &text[i..];
494 line.starts_with("if __name__ == \"__main__\"")
495 || line.starts_with("if __name__ == '__main__'")
496 })
497 .unwrap_or(text.len())
498 } else {
499 line_starts(text)
500 .find(|&i| {
501 let line = text[i..].lines().next().unwrap_or_default().trim();
502 !(line.starts_with("#!")
503 || line == "'use strict'"
504 || line == "\"use strict\""
505 || line == "'use strict';"
506 || line == "\"use strict\";")
507 })
508 .unwrap_or(text.len())
509 };
510 let mut out = String::with_capacity(text.len() + block.len() + 1);
511 out.push_str(&text[..at]);
512 if at == text.len() && !text.is_empty() && !text.ends_with('\n') {
513 out.push('\n');
514 let (first, rest) = block.split_once('\n').unwrap_or((block, ""));
515 out.push_str(first);
516 out.push_str(EOF_NOTE);
517 out.push('\n');
518 out.push_str(rest);
519 } else {
520 out.push_str(block);
521 }
522 out.push_str(&text[at..]);
523 out
524}
525
526fn line_starts(text: &str) -> impl Iterator<Item = usize> + '_ {
527 std::iter::once(0)
528 .chain(text.match_indices('\n').map(|(i, _)| i + 1))
529 .filter(move |&i| i < text.len())
530}
531
532fn find_block(text: &str, crate_name: &str) -> Option<(usize, usize, bool)> {
534 let start_tag = format!("{START} {crate_name} is on.");
535 let end_tag = format!("{END} {crate_name}");
536 let mut start = None;
537 for i in std::iter::once(0).chain(text.match_indices('\n').map(|(i, _)| i + 1)) {
538 let line = text[i..].split('\n').next().unwrap_or_default();
539 match start {
540 None if line.contains(&start_tag) => start = Some((i, line.ends_with(EOF_NOTE))),
541 Some((s, added)) if line.trim_end().ends_with(&end_tag) => {
542 let end = (i + line.len() + 1).min(text.len());
543 return Some((s, end, added));
544 }
545 _ => {}
546 }
547 }
548 None
549}
550
551fn remove(text: &str, crate_name: &str) -> Option<String> {
552 let (start, end, added) = find_block(text, crate_name)?;
553 let start = if added && end == text.len() && start > 0 {
554 start - 1
555 } else {
556 start
557 };
558 Some(format!("{}{}", &text[..start], &text[end..]))
559}
560
561#[cfg(test)]
562mod tests {
563 use super::*;
564
565 const BLOCK: &str = "# >>> rust-anything: fuzzy-rs is on. `rust-anything disable x` removes this block.\nx = 1\n# <<< rust-anything: fuzzy-rs\n";
566
567 #[test]
568 fn python_goes_before_the_main_guard_and_comes_out_byte_for_byte() {
569 let text = "def f(a):\n return a\n\nif __name__ == \"__main__\":\n print(f(1))\n";
570 let on = insert(text, BLOCK, Lang::Python);
571 assert!(
572 on.find("x = 1").unwrap() < on.find("if __name__").unwrap(),
573 "{on}"
574 );
575 assert_eq!(remove(&on, "fuzzy-rs").unwrap(), text);
576 assert!(remove(text, "fuzzy-rs").is_none());
577 }
578
579 #[test]
580 fn a_file_without_a_final_newline_gets_it_back_the_same() {
581 let text = "def f(a):\n return a";
582 let on = insert(text, BLOCK, Lang::Python);
583 assert!(on.contains(EOF_NOTE), "{on}");
584 assert_eq!(remove(&on, "fuzzy-rs").unwrap(), text);
585 }
586
587 #[test]
588 fn js_goes_after_the_shebang_and_use_strict() {
589 let text = "#!/usr/bin/env node\n'use strict'\nfunction f(a) { return a }\nmodule.exports = { f }\n";
590 let block = BLOCK.replace('#', "//");
591 let on = insert(text, &block, Lang::Ts);
592 assert!(
593 on.starts_with("#!/usr/bin/env node\n'use strict'\n// >>>"),
594 "{on}"
595 );
596 assert_eq!(remove(&on, "fuzzy-rs").unwrap(), text);
597 }
598
599 #[test]
600 fn only_declarations_can_be_rebound() {
601 let js = "export function score(a: string): number { return 1 }\nexport const other = () => 2\nexport async function* gen<T>(x: T) {}\n";
602 assert!(declared(js, "score", Lang::Ts));
603 assert!(!declared(js, "other", Lang::Ts));
604 assert!(declared(js, "gen", Lang::Ts));
605 let py = "def dedupe(names):\n pass\n\nclass A:\n def inner(self):\n pass\n";
606 assert!(declared(py, "dedupe", Lang::Python));
607 assert!(!declared(py, "inner", Lang::Python));
608 }
609
610 #[test]
611 fn module_kind_follows_the_syntax() {
612 assert!(esm("a.ts", "import x from 'y'\n"));
613 assert!(esm("a.mjs", ""));
614 assert!(!esm(
615 "a.js",
616 "const x = require('y')\nmodule.exports = {}\n"
617 ));
618 assert!(!esm("a.cjs", "export function f() {}\n"));
619 }
620
621 #[test]
622 fn select_matching_handles_partial_and_only_modes() {
623 use crate::harness::DiffOutcome;
624 use crate::ts::exports::ExportedFn;
625
626 let export = |name: &str| ExportedFn {
627 name: name.into(),
628 file: "util.py".into(),
629 line: 1,
630 ..Default::default()
631 };
632 let manifest = Manifest {
633 schema: "1".into(),
634 root: PathBuf::from("/tmp"),
635 root_written: None,
636 unit: "util.py".into(),
637 language: Lang::Python,
638 kind: Kind::Pyo3,
639 crate_name: "util-rs".into(),
640 exports: vec![export("slug"), export("words"), export("missing_fn")],
641 classes: Vec::new(),
642 js_only: Vec::new(),
643 batches: Vec::new(),
644 allocator: Default::default(),
645 float_tolerance: None,
646 ignore_key_order: false,
647 };
648 let outcome = DiffOutcome {
649 total: 446,
650 passed: 223,
651 failed: 223,
652 missing: vec!["missing_fn".into()],
653 ..Default::default()
654 };
655 let counts = BTreeMap::from([
656 ("slug".into(), (223, 223)),
657 ("words".into(), (0, 223)),
658 ("missing_fn".into(), (0, 10)),
659 ]);
660
661 let (selected, skipped) = select_matching(&manifest, &outcome, &counts, &[]).unwrap();
663 assert_eq!(selected, ["slug"]);
664 assert_eq!(
665 skipped,
666 [
667 "words: 0/223 match, kept in the original",
668 "missing_fn: missing from the Rust module, kept in the original",
669 ]
670 );
671
672 let (selected, skipped) =
674 select_matching(&manifest, &outcome, &counts, &["slug".into()]).unwrap();
675 assert_eq!(selected, ["slug"]);
676 assert_eq!(skipped.len(), 2);
677
678 let err = select_matching(&manifest, &outcome, &counts, &["words".into()]).unwrap_err();
680 assert!(format!("{err:#}").contains("words: 0/223 match"), "{err:#}");
681
682 let err = select_matching(&manifest, &outcome, &counts, &["nope".into()]).unwrap_err();
684 assert!(format!("{err:#}").contains("unknown export(s)"), "{err:#}");
685 assert!(
686 format!("{err:#}").contains("(exports: slug, words, missing_fn)"),
687 "{err:#}"
688 );
689
690 let none_counts = BTreeMap::from([("slug".into(), (1, 2)), ("words".into(), (0, 223))]);
692 let err = select_matching(&manifest, &outcome, &none_counts, &[]).unwrap_err();
693 assert!(
694 format!("{err:#}").contains("no functions in util-rs have all recorded cases matching"),
695 "{err:#}"
696 );
697 }
698}