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 let crate_dir = crate_dir
59 .canonical()
60 .with_context(|| format!("resolving {}", crate_dir.display()))?;
61 let manifest = Manifest::load(&crate_dir)?;
62 supported(&manifest)?;
63 let switch = crate::front_door::kill_switch(&manifest.crate_name);
64 let mut by_file: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
65 for f in &manifest.exports {
66 by_file.entry(&f.file).or_default().push(&f.name);
67 }
68 let mut out = Switched {
69 crate_name: manifest.crate_name.clone(),
70 on: true,
71 files: Vec::new(),
72 functions: Vec::new(),
73 skipped: manifest
74 .js_only
75 .iter()
76 .map(|j| format!("{}: kept in the original", j.name))
77 .collect(),
78 switch: switch.clone(),
79 };
80 let mut edits = Vec::new();
81 for (file, names) in by_file {
82 let path = manifest.root.join(file);
83 let text = std::fs::read_to_string(&path)
84 .with_context(|| format!("reading {}", path.display()))?;
85 if find_block(&text, &manifest.crate_name).is_some() {
86 out.functions.extend(names.iter().map(|n| n.to_string()));
87 continue;
88 }
89 let (swap, skip): (Vec<&str>, Vec<&str>) = names
90 .into_iter()
91 .partition(|n| declared(&text, n, manifest.language));
92 out.skipped.extend(skip.iter().map(|n| {
93 format!("{n}: not a plain function declaration in {file}, so callers keep the original")
94 }));
95 if swap.is_empty() {
96 continue;
97 }
98 let dir = path
99 .parent()
100 .context("source file has no folder")?
101 .canonical()?;
102 let block = match manifest.language {
103 Lang::Python => python_block(&manifest, &crate_dir, &dir, &swap, &switch),
104 Lang::Powershell => powershell_block(&manifest, &crate_dir, &dir, &switch),
105 _ => js_block(
106 &manifest,
107 &crate_dir,
108 &dir,
109 &swap,
110 &switch,
111 esm(file, &text),
112 ),
113 };
114 let edited = insert(&text, &block, manifest.language);
115 edits.push((path.clone(), edited));
116 out.files.push(path);
117 out.functions.extend(swap.iter().map(|n| n.to_string()));
118 }
119 if out.functions.is_empty() {
120 bail!(
121 "nothing to switch on in {}: {}",
122 manifest.crate_name,
123 out.skipped.join("; ")
124 );
125 }
126 for (path, text) in edits {
127 std::fs::write(&path, text).with_context(|| format!("writing {}", path.display()))?;
128 }
129 Ok(out)
130}
131
132pub fn disable(crate_dir: &Path) -> Result<Switched> {
133 let crate_dir = crate_dir
134 .canonical()
135 .with_context(|| format!("resolving {}", crate_dir.display()))?;
136 let manifest = Manifest::load(&crate_dir)?;
137 let mut out = Switched {
138 crate_name: manifest.crate_name.clone(),
139 on: false,
140 files: Vec::new(),
141 functions: Vec::new(),
142 skipped: Vec::new(),
143 switch: crate::front_door::kill_switch(&manifest.crate_name),
144 };
145 for file in files(&manifest) {
146 let path = manifest.root.join(file);
147 let Ok(text) = std::fs::read_to_string(&path) else {
148 continue;
149 };
150 if let Some(restored) = remove(&text, &manifest.crate_name) {
151 std::fs::write(&path, restored)
152 .with_context(|| format!("writing {}", path.display()))?;
153 out.files.push(path);
154 }
155 }
156 out.functions = manifest.exports.iter().map(|f| f.name.clone()).collect();
157 Ok(out)
158}
159
160pub fn is_supported(manifest: &Manifest) -> bool {
161 matches!(
162 (manifest.language, manifest.kind),
163 (Lang::Python, Kind::Pyo3)
164 | (Lang::Ts, Kind::Napi | Kind::Wasm)
165 | (Lang::Powershell, Kind::Ffi)
166 )
167}
168
169fn supported(manifest: &Manifest) -> Result<()> {
170 match manifest.language {
171 _ if is_supported(manifest) => Ok(()),
172 lang => bail!(
173 "`enable` switches TS/JS, Python and PowerShell ports in place; for {} use the shadow module \
174 (`rust-anything shadow`), imported where the app imported the original, and \
175 RUST_ANYTHING_MODE=old|shadow|new",
176 lang.name()
177 ),
178 }
179}
180
181fn files(manifest: &Manifest) -> Vec<&str> {
182 let mut files: Vec<&str> = manifest.exports.iter().map(|f| f.file.as_str()).collect();
183 files.sort_unstable();
184 files.dedup();
185 files
186}
187
188fn declared(text: &str, name: &str, lang: Lang) -> bool {
190 let name = regex::escape(name);
191 let pattern = if lang == Lang::Python {
192 format!(r"(?m)^(async\s+)?def\s+{name}\s*\(")
193 } else if lang == Lang::Powershell {
194 format!(r"(?mi)^\s*function\s+{name}\s*[{{(\s]")
195 } else {
196 format!(r"(?m)^\s*(export\s+)?(default\s+)?(async\s+)?function\s*\*?\s*{name}\s*[<(]")
197 };
198 regex::Regex::new(&pattern).is_ok_and(|re| re.is_match(text))
199}
200
201fn esm(file: &str, text: &str) -> bool {
202 if file.ends_with(".cjs") || file.ends_with(".cts") {
203 return false;
204 }
205 file.ends_with(".mjs")
206 || file.ends_with(".mts")
207 || text
208 .lines()
209 .any(|l| l.starts_with("import ") || l.starts_with("export "))
210}
211
212fn marker(comment: &str, crate_name: &str, crate_dir: &Path, dir: &Path) -> (String, String) {
213 let at = crate::shadow::relative(dir, crate_dir);
214 (
215 format!(
216 "{comment} {START} {crate_name} is on. `rust-anything disable {at}` removes this block."
217 ),
218 format!("{comment} {END} {crate_name}"),
219 )
220}
221
222fn js_block(
223 manifest: &Manifest,
224 crate_dir: &Path,
225 dir: &Path,
226 names: &[&str],
227 switch: &str,
228 esm: bool,
229) -> String {
230 let (start, end) = marker("//", &manifest.crate_name, crate_dir, dir);
231 let module = crate_dir.join("index.cjs");
235 let rel = crate::shadow::relative(dir, &module);
236 let here = if esm {
237 "import.meta.dirname"
238 } else {
239 "__dirname"
240 };
241 let var = format!(
242 "__rustAnything_{}",
243 crate::front_door::ident(&manifest.crate_name)
244 );
245 let assign: Vec<String> = names.iter().map(|n| format!("{n} = {var}.{n}")).collect();
246 format!(
247 "{start}\n\
248 // @ts-ignore\n\
249 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\
250 // @ts-ignore\n\
251 if ({var}) {{ {} }}\n\
252 {end}\n",
253 assign.join("; ")
254 )
255}
256
257fn python_block(
258 manifest: &Manifest,
259 crate_dir: &Path,
260 dir: &Path,
261 names: &[&str],
262 switch: &str,
263) -> String {
264 let (start, end) = marker("#", &manifest.crate_name, crate_dir, dir);
265 let (package_dir, lib) = crate::harness_py::package(crate_dir, manifest);
266 let rel = crate::shadow::relative(dir, &package_dir);
267 let fun = format!(
268 "_rust_anything_{}",
269 crate::front_door::ident(&manifest.crate_name)
270 );
271 let names: Vec<String> = names.iter().map(|n| format!("{n:?}")).collect();
272 format!(
273 "{start}\n\
274 def {fun}():\n\
275 \x20 import importlib, os, sys\n\
276 \x20 mode = os.environ.get(\"RUST_ANYTHING_MODE\")\n\
277 \x20 if mode == \"old\" or os.environ.get(\"{switch}\") == \"original\":\n\
278 \x20 return\n\
279 \x20 at = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), {rel:?}))\n\
280 \x20 sys.path.insert(0, at)\n\
281 \x20 try:\n\
282 \x20 native = importlib.import_module({lib:?})\n\
283 \x20 except ImportError:\n\
284 \x20 if mode == \"new\":\n\
285 \x20 raise\n\
286 \x20 return\n\
287 \x20 finally:\n\
288 \x20 sys.path.remove(at)\n\
289 \x20 globals().update({{name: getattr(native, name) for name in [{}]}})\n\
290 \n\
291 \n\
292 {fun}()\n\
293 del {fun}\n\
294 {end}\n",
295 names.join(", ")
296 )
297}
298
299fn powershell_block(manifest: &Manifest, crate_dir: &Path, dir: &Path, switch: &str) -> String {
300 let (start, end) = marker("#", &manifest.crate_name, crate_dir, dir);
301 let wrapper = crate_dir.join(crate::codegen_powershell::wrapper_path(manifest));
302 let rel = crate::shadow::relative(dir, &wrapper).replace('\'', "''");
303 format!(
304 "{start}\n\
305 if ($env:RUST_ANYTHING_MODE -ne 'old' -and $env:{switch} -ne 'original') {{\n\
306 \x20 try {{\n\
307 \x20 . (Join-Path $PSScriptRoot '{rel}')\n\
308 \x20 }} catch {{\n\
309 \x20 if ($env:RUST_ANYTHING_MODE -eq 'new') {{ throw }}\n\
310 \x20 }}\n\
311 }}\n\
312 {end}\n"
313 )
314}
315
316fn insert(text: &str, block: &str, lang: Lang) -> String {
320 let at = if lang == Lang::Powershell {
321 crate::lang::powershell::after_functions(text).unwrap_or(text.len())
322 } else if lang == Lang::Python {
323 line_starts(text)
324 .find(|&i| {
325 let line = &text[i..];
326 line.starts_with("if __name__ == \"__main__\"")
327 || line.starts_with("if __name__ == '__main__'")
328 })
329 .unwrap_or(text.len())
330 } else {
331 line_starts(text)
332 .find(|&i| {
333 let line = text[i..].lines().next().unwrap_or_default().trim();
334 !(line.starts_with("#!")
335 || line == "'use strict'"
336 || line == "\"use strict\""
337 || line == "'use strict';"
338 || line == "\"use strict\";")
339 })
340 .unwrap_or(text.len())
341 };
342 let mut out = String::with_capacity(text.len() + block.len() + 1);
343 out.push_str(&text[..at]);
344 if at == text.len() && !text.is_empty() && !text.ends_with('\n') {
345 out.push('\n');
346 let (first, rest) = block.split_once('\n').unwrap_or((block, ""));
347 out.push_str(first);
348 out.push_str(EOF_NOTE);
349 out.push('\n');
350 out.push_str(rest);
351 } else {
352 out.push_str(block);
353 }
354 out.push_str(&text[at..]);
355 out
356}
357
358fn line_starts(text: &str) -> impl Iterator<Item = usize> + '_ {
359 std::iter::once(0)
360 .chain(text.match_indices('\n').map(|(i, _)| i + 1))
361 .filter(move |&i| i < text.len())
362}
363
364fn find_block(text: &str, crate_name: &str) -> Option<(usize, usize, bool)> {
366 let start_tag = format!("{START} {crate_name} is on.");
367 let end_tag = format!("{END} {crate_name}");
368 let mut start = None;
369 for i in std::iter::once(0).chain(text.match_indices('\n').map(|(i, _)| i + 1)) {
370 let line = text[i..].split('\n').next().unwrap_or_default();
371 match start {
372 None if line.contains(&start_tag) => start = Some((i, line.ends_with(EOF_NOTE))),
373 Some((s, added)) if line.trim_end().ends_with(&end_tag) => {
374 let end = (i + line.len() + 1).min(text.len());
375 return Some((s, end, added));
376 }
377 _ => {}
378 }
379 }
380 None
381}
382
383fn remove(text: &str, crate_name: &str) -> Option<String> {
384 let (start, end, added) = find_block(text, crate_name)?;
385 let start = if added && end == text.len() && start > 0 {
386 start - 1
387 } else {
388 start
389 };
390 Some(format!("{}{}", &text[..start], &text[end..]))
391}
392
393#[cfg(test)]
394mod tests {
395 use super::*;
396
397 const BLOCK: &str = "# >>> rust-anything: fuzzy-rs is on. `rust-anything disable x` removes this block.\nx = 1\n# <<< rust-anything: fuzzy-rs\n";
398
399 #[test]
400 fn python_goes_before_the_main_guard_and_comes_out_byte_for_byte() {
401 let text = "def f(a):\n return a\n\nif __name__ == \"__main__\":\n print(f(1))\n";
402 let on = insert(text, BLOCK, Lang::Python);
403 assert!(
404 on.find("x = 1").unwrap() < on.find("if __name__").unwrap(),
405 "{on}"
406 );
407 assert_eq!(remove(&on, "fuzzy-rs").unwrap(), text);
408 assert!(remove(text, "fuzzy-rs").is_none());
409 }
410
411 #[test]
412 fn a_file_without_a_final_newline_gets_it_back_the_same() {
413 let text = "def f(a):\n return a";
414 let on = insert(text, BLOCK, Lang::Python);
415 assert!(on.contains(EOF_NOTE), "{on}");
416 assert_eq!(remove(&on, "fuzzy-rs").unwrap(), text);
417 }
418
419 #[test]
420 fn js_goes_after_the_shebang_and_use_strict() {
421 let text = "#!/usr/bin/env node\n'use strict'\nfunction f(a) { return a }\nmodule.exports = { f }\n";
422 let block = BLOCK.replace('#', "//");
423 let on = insert(text, &block, Lang::Ts);
424 assert!(
425 on.starts_with("#!/usr/bin/env node\n'use strict'\n// >>>"),
426 "{on}"
427 );
428 assert_eq!(remove(&on, "fuzzy-rs").unwrap(), text);
429 }
430
431 #[test]
432 fn only_declarations_can_be_rebound() {
433 let js = "export function score(a: string): number { return 1 }\nexport const other = () => 2\nexport async function* gen<T>(x: T) {}\n";
434 assert!(declared(js, "score", Lang::Ts));
435 assert!(!declared(js, "other", Lang::Ts));
436 assert!(declared(js, "gen", Lang::Ts));
437 let py = "def dedupe(names):\n pass\n\nclass A:\n def inner(self):\n pass\n";
438 assert!(declared(py, "dedupe", Lang::Python));
439 assert!(!declared(py, "inner", Lang::Python));
440 }
441
442 #[test]
443 fn module_kind_follows_the_syntax() {
444 assert!(esm("a.ts", "import x from 'y'\n"));
445 assert!(esm("a.mjs", ""));
446 assert!(!esm(
447 "a.js",
448 "const x = require('y')\nmodule.exports = {}\n"
449 ));
450 assert!(!esm("a.cjs", "export function f() {}\n"));
451 }
452}