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