1use std::collections::{BTreeMap, HashSet};
12use std::path::{Path, PathBuf};
13use std::process::Command;
14
15use anyhow::{Context, Result, bail};
16use serde_json::Value;
17
18use crate::bridge::Manifest;
19use crate::lang::Lang;
20use crate::walk::Canonical;
21
22const PER_FUNCTION: usize = 1000;
24pub const TEST_INPUTS: &str = "test-inputs.jsonl";
25const BACKUP: &str = ".rust-anything-backup";
26
27#[derive(Debug)]
28pub struct Capture {
29 pub inputs: PathBuf,
31 pub per_function: BTreeMap<String, usize>,
32 pub skipped: Vec<String>,
34 pub tests_passed: bool,
35}
36
37pub fn capture(crate_dir: &Path, command: &[String]) -> Result<Capture> {
38 let m = Manifest::load(crate_dir)?;
39 let Some((program, args)) = command.split_first() else {
40 bail!("--from-tests needs the test command after `--`, e.g. `-- npx jest`");
41 };
42 let raw = std::path::absolute(crate_dir.join("test-calls.raw.jsonl"))?;
43 let _ = std::fs::remove_file(&raw);
44 let mut cmd = Command::new(program);
45 cmd.args(args)
46 .current_dir(&m.root)
47 .stdout(std::io::stderr())
48 .env("RUST_ANYTHING_CAPTURE", &raw)
49 .env("CI", "1");
50 let mut skipped = Vec::new();
51 let status = match m.language {
52 Lang::Ts => {
53 let guard = instrument_js(&m, &mut skipped)?;
54 let status = crate::process::status(&mut cmd, crate::process::TESTS);
55 drop(guard);
56 status
57 }
58 Lang::Python => {
59 let hook = crate_dir.join("target").join("from-tests");
60 std::fs::create_dir_all(&hook)?;
61 std::fs::write(hook.join("sitecustomize.py"), python_hook())?;
62 let mut want: BTreeMap<String, Vec<String>> = BTreeMap::new();
63 for f in &m.exports {
64 let path = m.root.join(&f.file).canonical()?;
65 want.entry(path.to_string_lossy().into_owned())
66 .or_default()
67 .push(f.name.clone());
68 }
69 let path = std::env::join_paths(
70 std::iter::once(std::path::absolute(&hook)?).chain(
71 std::env::var_os("PYTHONPATH")
72 .map(|p| std::env::split_paths(&p).collect::<Vec<_>>())
73 .unwrap_or_default(),
74 ),
75 )?;
76 cmd.env("PYTHONPATH", path)
77 .env("RUST_ANYTHING_CAPTURE_FUNCS", serde_json::to_string(&want)?)
78 .env("PYTHONDONTWRITEBYTECODE", "1");
79 crate::process::status(&mut cmd, crate::process::TESTS)
80 }
81 other => bail!(
82 "--from-tests captures TS/JS and Python test suites; this unit is {}",
83 other.name()
84 ),
85 }
86 .with_context(|| format!("running `{}`", command.join(" ")))?;
87
88 let text = std::fs::read_to_string(&raw).unwrap_or_default();
89 let _ = std::fs::remove_file(&raw);
90 let exported: HashSet<&str> = m.exports.iter().map(|f| f.name.as_str()).collect();
91 let mut seen = HashSet::new();
92 let mut per_function: BTreeMap<String, usize> = BTreeMap::new();
93 let mut out = String::new();
94 for line in text.lines() {
95 let Ok(call) = serde_json::from_str::<Value>(line) else {
96 continue;
97 };
98 let Some(name) = call["fn"].as_str() else {
99 continue;
100 };
101 if !exported.contains(name) || !call["args"].is_array() || !seen.insert(line.to_string()) {
102 continue;
103 }
104 let n = per_function.entry(name.to_string()).or_default();
105 if *n >= PER_FUNCTION {
106 continue;
107 }
108 *n += 1;
109 out.push_str(line);
110 out.push('\n');
111 }
112 let inputs = crate_dir.join(TEST_INPUTS);
113 std::fs::write(&inputs, out).with_context(|| format!("writing {}", inputs.display()))?;
114 Ok(Capture {
115 inputs,
116 per_function,
117 skipped,
118 tests_passed: status.success(),
119 })
120}
121
122pub fn with_own_inputs(crate_dir: &Path, own: Option<&Path>, captured: &Path) -> Result<PathBuf> {
124 let Some(own) = own else {
125 return Ok(captured.to_path_buf());
126 };
127 let mut text =
128 std::fs::read_to_string(own).with_context(|| format!("reading {}", own.display()))?;
129 if !text.is_empty() && !text.ends_with('\n') {
130 text.push('\n');
131 }
132 text += &std::fs::read_to_string(captured)?;
133 let combined = crate_dir.join("target").join("record-inputs.jsonl");
134 std::fs::create_dir_all(crate_dir.join("target"))?;
135 std::fs::write(&combined, text)?;
136 Ok(combined)
137}
138
139struct Restore(Vec<PathBuf>);
141
142impl Drop for Restore {
143 fn drop(&mut self) {
144 for file in &self.0 {
145 restore(file);
146 }
147 }
148}
149
150fn backup_of(file: &Path) -> PathBuf {
151 let mut name = file.as_os_str().to_owned();
152 name.push(BACKUP);
153 PathBuf::from(name)
154}
155
156fn restore(file: &Path) {
157 let backup = backup_of(file);
158 if std::fs::copy(&backup, file).is_ok() {
159 let _ = std::fs::remove_file(backup);
160 }
161}
162
163fn instrument_js(m: &Manifest, skipped: &mut Vec<String>) -> Result<Restore> {
164 let mut by_file: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
165 for f in &m.exports {
166 by_file.entry(&f.file).or_default().push(&f.name);
167 }
168 let mut guard = Restore(Vec::new());
169 for (file, names) in by_file {
170 let path = m.root.join(file);
171 restore(&path);
172 let text = std::fs::read_to_string(&path)
173 .with_context(|| format!("reading {}", path.display()))?;
174 let wrappable: Vec<&str> = names
175 .into_iter()
176 .filter(|name| {
177 let declared = regex::Regex::new(&format!(
178 r"\bfunction\s*\*?\s*{}\s*[<(]",
179 regex::escape(name)
180 ))
181 .is_ok_and(|re| re.is_match(&text));
182 if !declared {
183 skipped.push(format!(
184 "{name} ({file}): not a function declaration, so its binding cannot be wrapped"
185 ));
186 }
187 declared
188 })
189 .collect();
190 if wrappable.is_empty() {
191 continue;
192 }
193 std::fs::copy(&path, backup_of(&path))
194 .with_context(|| format!("backing up {}", path.display()))?;
195 guard.0.push(path.clone());
196 let ts = file.ends_with(".ts") || file.ends_with(".tsx") || file.ends_with(".mts");
197 let wraps: String = wrappable
198 .iter()
199 .map(|n| format!(" {n} = __raWrap('{n}', {n})\n"))
200 .collect();
201 let instrumented = format!(
202 "{}{text}\n{}",
203 if ts { "// @ts-nocheck\n" } else { "" },
204 JS_CAPTURE.replace("__WRAPS__", &wraps)
205 );
206 std::fs::write(&path, instrumented)
207 .with_context(|| format!("instrumenting {}", path.display()))?;
208 }
209 Ok(guard)
210}
211
212const JS_CAPTURE: &str = r#"// rust-anything record --from-tests: removed when the tests finish.
213/* c8 ignore start */
214/* istanbul ignore next */
215{
216 const __raFs = globalThis.process?.getBuiltinModule?.('node:fs')
217 const __raOut = globalThis.process?.env?.RUST_ANYTHING_CAPTURE
218 const __raCount = new Map()
219 const __raReplacer = function (k, v) {
220 const raw = this[k]
221 if (typeof raw === 'function' || typeof raw === 'symbol') throw new Error('not data')
222 if (raw instanceof Date) return { $date: Number.isNaN(raw.getTime()) ? 'Invalid' : raw.toISOString() }
223 if (raw instanceof Uint8Array) return { $bytes: Array.from(raw) }
224 if (raw instanceof Map) return { $map: [...raw] }
225 if (raw instanceof Set) return { $set: [...raw] }
226 return v === undefined ? { $undefined: true }
227 : typeof v === 'bigint' ? { $bigint: String(v) }
228 : typeof v === 'number' ? (Number.isFinite(v) && !Object.is(v, -0) ? v : { $num: Object.is(v, -0) ? '-0' : String(v) })
229 : typeof v === 'string' && !v.isWellFormed() ? { $utf16: Array.from({ length: v.length }, (_, i) => v.charCodeAt(i)) }
230 : v
231 }
232 const __raWrap = (name, orig) => {
233 if (!__raFs || !__raOut || typeof orig !== 'function') return orig
234 const wrapped = function (...args) {
235 const n = __raCount.get(name) ?? 0
236 if (n < 5000) {
237 __raCount.set(name, n + 1)
238 try { __raFs.appendFileSync(__raOut, JSON.stringify({ fn: name, args }, __raReplacer) + '\n') } catch {}
239 }
240 return new.target ? Reflect.construct(orig, args, new.target) : orig.apply(this, args)
241 }
242 if (typeof exports === 'object' && exports !== null) {
243 for (const key of [name, 'default']) if (exports[key] === orig) exports[key] = wrapped
244 }
245 return wrapped
246 }
247__WRAPS__}
248/* c8 ignore stop */
249"#;
250
251fn python_hook() -> String {
252 let driver = crate::harness_py::DRIVER_PY;
253 let enc = driver
254 .find("def enc(")
255 .and_then(|start| {
256 driver[start..]
257 .find("\ndef dec(")
258 .map(|end| &driver[start..start + end])
259 })
260 .unwrap_or("def enc(v, stack=()):\n return v\n");
261 format!("{PY_HOOK_HEAD}\n{enc}\n{PY_HOOK_TAIL}")
262}
263
264const PY_HOOK_HEAD: &str = r#"# rust-anything record --from-tests: wraps the unit's functions when their module loads.
265import functools
266import importlib.abc
267import importlib.machinery
268import inspect
269import json
270import math
271import os
272import sys
273
274BIG = 2 ** 53
275"#;
276
277const PY_HOOK_TAIL: &str = r#"
278_OUT = os.environ.get("RUST_ANYTHING_CAPTURE")
279_WANT = json.loads(os.environ.get("RUST_ANYTHING_CAPTURE_FUNCS") or "{}")
280_COUNT = {}
281
282
283def _wrap(name, orig):
284 try:
285 sig = inspect.signature(orig)
286 except (TypeError, ValueError):
287 sig = None
288
289 @functools.wraps(orig)
290 def wrapped(*args, **kwargs):
291 n = _COUNT.get(name, 0)
292 if n < 5000 and sig is not None:
293 try:
294 bound = sig.bind(*args, **kwargs)
295 if not bound.kwargs:
296 line = json.dumps({"fn": name, "args": enc(list(bound.args))}, ensure_ascii=False, allow_nan=False)
297 with open(_OUT, "a", encoding="utf-8") as f:
298 f.write(line + "\n")
299 _COUNT[name] = n + 1
300 except Exception:
301 pass
302 return orig(*args, **kwargs)
303
304 return wrapped
305
306
307class _Loader(importlib.abc.Loader):
308 def __init__(self, inner, names):
309 self.inner = inner
310 self.names = names
311
312 def create_module(self, spec):
313 return self.inner.create_module(spec)
314
315 def exec_module(self, module):
316 self.inner.exec_module(module)
317 for name in self.names:
318 orig = getattr(module, name, None)
319 if callable(orig):
320 setattr(module, name, _wrap(name, orig))
321
322
323class _Finder(importlib.abc.MetaPathFinder):
324 def find_spec(self, fullname, path, target=None):
325 spec = importlib.machinery.PathFinder.find_spec(fullname, path)
326 if spec is None or spec.origin is None or spec.loader is None:
327 return None
328 names = _WANT.get(os.path.realpath(spec.origin))
329 if not names:
330 return None
331 spec.loader = _Loader(spec.loader, names)
332 return spec
333
334
335if _OUT and _WANT:
336 sys.meta_path.insert(0, _Finder())
337"#;