1use std::collections::BTreeMap;
7use std::path::{Path, PathBuf};
8use std::process::Command;
9
10use anyhow::{Context, Result, bail, ensure};
11use serde::{Deserialize, Serialize};
12
13use crate::app::{Failure, Fallback, Problem, ReplayOutcome};
14use crate::front_door::{APP_DIR, State, ident};
15use crate::lang::Lang;
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct ApiUnit {
20 pub unit: String,
21 pub module: String,
23 pub exports: Vec<String>,
24}
25
26fn exports_of(root: &Path, lang: Lang, files: &[String]) -> Vec<String> {
28 let mut out = Vec::new();
29 for file in files {
30 let Ok(text) = std::fs::read_to_string(root.join(file)) else {
31 continue;
32 };
33 if lang == Lang::Ts {
34 out.extend(
35 crate::ts::exports::exported_functions(file, &text)
36 .into_iter()
37 .map(|f| f.name),
38 );
39 out.extend(
40 crate::ts::exports::exported_classes(file, &text)
41 .into_iter()
42 .map(|c| c.name),
43 );
44 } else {
45 let (functions, classes) = crate::lang::exports(lang, file, &text);
46 out.extend(functions.into_iter().map(|f| f.name));
47 out.extend(classes.into_iter().map(|c| c.name));
48 }
49 }
50 out
51}
52
53pub(crate) fn public_api(root: &Path, report: &crate::analyze::Report) -> Vec<ApiUnit> {
55 let mut taken = BTreeMap::new();
56 let mut out = Vec::new();
57 for unit in report
58 .units
59 .iter()
60 .filter(|u| u.status != crate::analyze::Status::Keep)
61 {
62 let exports = exports_of(root, report.language, &unit.files);
63 if exports.is_empty() {
64 continue;
65 }
66 let stem = unit
67 .id
68 .trim_end_matches('/')
69 .rsplit('/')
70 .next()
71 .unwrap_or(&unit.id);
72 let stem = stem.split('.').next().unwrap_or(stem);
73 let mut module = ident(stem);
74 let n = taken.entry(module.clone()).or_insert(0);
75 *n += 1;
76 if *n > 1 {
77 module = format!("{module}_{n}");
78 }
79 out.push(ApiUnit {
80 unit: unit.id.clone(),
81 module,
82 exports,
83 });
84 }
85 out
86}
87
88pub(crate) fn cargo_toml(package: &str, name: &str) -> String {
89 format!(
90 "[package]\nname = \"{package}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\
91 description = \"`{name}`'s public API in Rust, generated by rust-anything: each unit's port, re-exported\"\n\n\
92 [lib]\npath = \"src/lib.rs\"\n\n\
93 [dependencies]\n\n\
94 [workspace]\n"
95 )
96}
97
98pub(crate) fn lib_rs(state: &State, lifted: bool) -> String {
100 let mut out = if lifted {
101 format!(
102 "//! `{}`'s public API in Rust. Written by `rust-anything app lift`: every unit is a plain\n\
103 //! Rust library here.\n",
104 state.name
105 )
106 } else {
107 format!(
108 "//! `{}`'s public API in Rust. Generated by `rust-anything app wire` from rust-anything.json;\n\
109 //! it is rewritten on every wire until the lift.\n",
110 state.name
111 )
112 };
113 let wired = |api: &ApiUnit| {
114 state
115 .units
116 .iter()
117 .find(|u| u.unit.as_deref() == Some(&api.unit))
118 };
119 let pending: Vec<String> = state
120 .api
121 .iter()
122 .filter(|a| wired(a).is_none())
123 .map(|a| format!("`{}`", a.unit))
124 .collect();
125 if !pending.is_empty() {
126 out += &format!(
127 "//!\n//! Still only in the original: {}.\n",
128 pending.join(", ")
129 );
130 }
131 out.push('\n');
132 for api in &state.api {
133 if let Some(unit) = wired(api) {
134 out += &format!(
135 "pub use {}::port as {};\n",
136 unit.crate_name.replace('-', "_"),
137 api.module
138 );
139 }
140 }
141 out
142}
143
144pub(crate) const CARGO_CONFIG: &str = ".cargo/config.toml";
145
146pub(crate) fn allow_python_symbols(app_dir: &Path) -> Result<()> {
149 let path = app_dir.join(CARGO_CONFIG);
150 if path.exists() {
151 return Ok(());
152 }
153 std::fs::create_dir_all(app_dir.join(".cargo"))?;
154 std::fs::write(
155 &path,
156 "[target.'cfg(target_os = \"macos\")']
157 rustflags = [\"-C\", \"link-arg=-undefined\", \"-C\", \"link-arg=dynamic_lookup\"]
158",
159 )?;
160 Ok(())
161}
162
163pub(crate) fn cargo_build_lib(app_dir: &Path, target_dir: Option<&Path>) -> Result<()> {
164 let mut cmd = Command::new("cargo");
165 cmd.args(["build", "--quiet", "--manifest-path"])
166 .arg(app_dir.join("Cargo.toml"))
167 .current_dir(app_dir);
168 if let Some(dir) = target_dir {
169 cmd.env("CARGO_TARGET_DIR", dir);
170 }
171 let out = crate::process::output(&mut cmd, crate::process::BUILD).context("running cargo")?;
172 ensure!(
173 out.status.success(),
174 "cargo build in {} failed:\n{}",
175 app_dir.display(),
176 String::from_utf8_lossy(&out.stderr)
177 );
178 Ok(())
179}
180
181pub(crate) fn pending(state: &State) -> Vec<String> {
184 let mut out = Vec::new();
185 for api in &state.api {
186 let wired = state
187 .units
188 .iter()
189 .find(|u| u.unit.as_deref() == Some(&api.unit));
190 for name in &api.exports {
191 if wired.is_none_or(|u| u.kept.contains(name)) {
192 out.push(format!("{}: {name}", api.unit));
193 }
194 }
195 }
196 out
197}
198
199pub(crate) fn replay(repo: &Path, state: &State, unit: Option<&str>) -> Result<ReplayOutcome> {
202 let app_dir = repo.join(APP_DIR);
203 let mut outcome = ReplayOutcome {
204 build: vec!["the units' bindings".to_string()],
205 passed: 0,
206 total: 0,
207 skipped: 0,
208 failures: Vec::new(),
209 fallback: None,
210 report: app_dir.join(crate::app::REPORT_FILE),
211 };
212 let units = crate::app::only_case(state.units.iter().collect(), unit, |u| &u.name)?;
213 for unit in units {
214 let crate_dir = app_dir.join(&unit.path);
215 match crate::harness::diff(&crate::harness::DiffOptions {
216 crate_dir: &crate_dir,
217 module: None,
218 ignore_key_order: false,
219 float_tolerance: None,
220 node_args: &[],
221 }) {
222 Ok(d) => {
223 outcome.total += d.total;
224 outcome.passed += d.passed;
225 for m in &d.mismatches {
226 let args = m["args"]
227 .as_array()
228 .map(|a| a.iter().map(ToString::to_string).collect())
229 .unwrap_or_default();
230 outcome.failures.push(Failure {
231 case: format!("{}: {}", unit.name, m["fn"].as_str().unwrap_or("?")),
232 args,
233 problems: vec![Problem {
234 field: "result".to_string(),
235 detail: format!("- {}\n+ {}\n", m["expected"], m["actual"]),
236 }],
237 });
238 }
239 if !d.missing.is_empty() {
240 outcome.total += 1;
241 outcome.failures.push(Failure {
242 case: format!("{}: api", unit.name),
243 args: Vec::new(),
244 problems: vec![Problem {
245 field: "exports".to_string(),
246 detail: format!("missing: {}\n", d.missing.join(", ")),
247 }],
248 });
249 }
250 }
251 Err(e) => {
252 outcome.total += 1;
253 outcome.failures.push(Failure {
254 case: unit.name.clone(),
255 args: Vec::new(),
256 problems: vec![Problem {
257 field: "replay".to_string(),
258 detail: format!(
259 "{e:#}\n(build it first: rust-anything build {})\n",
260 crate_dir.display()
261 ),
262 }],
263 });
264 }
265 }
266 }
267 let names = pending(state);
268 let exports: usize = state.api.iter().map(|a| a.exports.len()).sum();
269 outcome.fallback = Some(Fallback {
270 cases: names.len(),
271 total: exports,
272 rate: names.len() as f64 / exports.max(1) as f64,
273 names,
274 });
275 std::fs::write(&outcome.report, crate::app::report_markdown(&outcome))
276 .with_context(|| format!("writing {}", outcome.report.display()))?;
277 Ok(outcome)
278}
279
280pub(crate) fn original_references(repo: &Path, state: &State) -> Vec<String> {
282 let needles: Vec<String> = state
283 .units
284 .iter()
285 .flat_map(|u| [u.crate_name.clone(), u.crate_name.replace('-', "_")])
286 .collect();
287 let mut out = Vec::new();
288 let walker = crate::walk::filtered(repo, |e| {
289 !matches!(
290 e.file_name().to_string_lossy().as_ref(),
291 "rust" | "target" | "node_modules" | ".git"
292 )
293 })
294 .build();
295 for entry in walker.flatten() {
296 let path = entry.path();
297 if !path.is_file() || std::fs::metadata(path).is_ok_and(|m| m.len() > 1 << 20) {
298 continue;
299 }
300 let Ok(text) = std::fs::read_to_string(path) else {
301 continue;
302 };
303 if needles.iter().any(|n| text.contains(n.as_str())) {
304 out.push(
305 path.strip_prefix(repo)
306 .unwrap_or(path)
307 .to_string_lossy()
308 .into_owned(),
309 );
310 }
311 }
312 out.sort();
313 out
314}
315
316pub(crate) fn api_unit<'s>(state: &'s State, unit: &str) -> Result<&'s ApiUnit> {
318 let wanted = unit.trim_end_matches('/');
319 match state
320 .api
321 .iter()
322 .find(|a| a.unit.trim_end_matches('/') == wanted)
323 {
324 Some(a) => Ok(a),
325 None => bail!(
326 "`{unit}` is not part of the public API (units: {})",
327 state
328 .api
329 .iter()
330 .map(|a| a.unit.as_str())
331 .collect::<Vec<_>>()
332 .join(", ")
333 ),
334 }
335}
336
337pub(crate) fn shadow_for(crate_dir: &Path, previous: Option<&str>) -> Result<Option<PathBuf>> {
339 if let Some(p) = previous {
340 return Ok(Some(PathBuf::from(p)));
341 }
342 match crate::shadow::shadow(crate_dir, None) {
343 Ok(o) => Ok(Some(o.path)),
344 Err(e) if format!("{e:#}").contains("exists") => Ok(None),
345 Err(e) => Err(e),
346 }
347}