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