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 crate::app::write_report(crate::app::grouped(replay_unwritten(repo, state, unit)?))
203}
204
205pub(crate) fn replay_unwritten(
207 repo: &Path,
208 state: &State,
209 unit: Option<&str>,
210) -> Result<ReplayOutcome> {
211 let app_dir = repo.join(APP_DIR);
212 let mut outcome = ReplayOutcome {
213 build: vec!["the units' bindings".to_string()],
214 passed: 0,
215 total: 0,
216 skipped: 0,
217 failures: Vec::new(),
218 fallback: None,
219 report: app_dir.join(crate::app::REPORT_FILE),
220 groups: Vec::new(),
221 };
222 let units = crate::app::only_case(state.units.iter().collect(), unit, |u| &u.name)?;
223 for unit in units {
224 let crate_dir = app_dir.join(&unit.path);
225 match crate::harness::diff(&crate::harness::DiffOptions {
226 crate_dir: &crate_dir,
227 module: None,
228 ignore_key_order: false,
229 float_tolerance: None,
230 node_args: &[],
231 }) {
232 Ok(d) => {
233 outcome.total += d.total;
234 outcome.passed += d.passed;
235 for m in &d.mismatches {
236 let args = m["args"]
237 .as_array()
238 .map(|a| a.iter().map(ToString::to_string).collect())
239 .unwrap_or_default();
240 outcome.failures.push(Failure {
241 case: format!("{}: {}", unit.name, m["fn"].as_str().unwrap_or("?")),
242 args,
243 problems: vec![{
244 let p = Problem::new(
245 "result",
246 format!("- {}\n+ {}\n", m["expected"], m["actual"]),
247 );
248 match serde_json::from_value(m["at"].clone()) {
249 Ok(at) => p.at(at),
250 Err(_) => p,
251 }
252 }],
253 });
254 }
255 if !d.missing.is_empty() {
256 outcome.total += 1;
257 outcome.failures.push(Failure {
258 case: format!("{}: api", unit.name),
259 args: Vec::new(),
260 problems: vec![
261 Problem::new("exports", format!("missing: {}\n", d.missing.join(", ")))
262 .at(crate::mismatch::At::new("missing key")),
263 ],
264 });
265 }
266 }
267 Err(e) => {
268 outcome.total += 1;
269 outcome.failures.push(Failure {
270 case: unit.name.clone(),
271 args: Vec::new(),
272 problems: vec![
273 Problem::new(
274 "replay",
275 format!(
276 "{e:#}\n(build it first: rust-anything build {})\n",
277 crate_dir.display()
278 ),
279 )
280 .at(crate::mismatch::At::new("no response")),
281 ],
282 });
283 }
284 }
285 }
286 let names = pending(state);
287 let exports: usize = state.api.iter().map(|a| a.exports.len()).sum();
288 outcome.fallback = Some(Fallback {
289 cases: names.len(),
290 total: exports,
291 rate: names.len() as f64 / exports.max(1) as f64,
292 names,
293 });
294 Ok(outcome)
295}
296
297pub(crate) fn original_references(repo: &Path, state: &State) -> Vec<String> {
299 let needles: Vec<String> = state
300 .units
301 .iter()
302 .flat_map(|u| [u.crate_name.clone(), u.crate_name.replace('-', "_")])
303 .collect();
304 let mut out = Vec::new();
305 let walker = crate::walk::filtered(repo, |e| {
306 !matches!(
307 e.file_name().to_string_lossy().as_ref(),
308 "rust" | "target" | "node_modules" | ".git"
309 )
310 })
311 .build();
312 for entry in walker.flatten() {
313 let path = entry.path();
314 if !path.is_file() || std::fs::metadata(path).is_ok_and(|m| m.len() > 1 << 20) {
315 continue;
316 }
317 let Ok(text) = std::fs::read_to_string(path) else {
318 continue;
319 };
320 if needles.iter().any(|n| text.contains(n.as_str())) {
321 out.push(
322 path.strip_prefix(repo)
323 .unwrap_or(path)
324 .to_string_lossy()
325 .into_owned(),
326 );
327 }
328 }
329 out.sort();
330 out
331}
332
333pub(crate) fn api_unit<'s>(state: &'s State, unit: &str) -> Result<&'s ApiUnit> {
335 let wanted = unit.trim_end_matches('/');
336 match state
337 .api
338 .iter()
339 .find(|a| a.unit.trim_end_matches('/') == wanted)
340 {
341 Some(a) => Ok(a),
342 None => bail!(
343 "`{unit}` is not part of the public API (units: {})",
344 state
345 .api
346 .iter()
347 .map(|a| a.unit.as_str())
348 .collect::<Vec<_>>()
349 .join(", ")
350 ),
351 }
352}
353
354pub(crate) fn shadow_for(crate_dir: &Path, previous: Option<&str>) -> Result<Option<PathBuf>> {
356 if let Some(p) = previous {
357 return Ok(Some(PathBuf::from(p)));
358 }
359 match crate::shadow::shadow(crate_dir, None) {
360 Ok(o) => Ok(Some(o.path)),
361 Err(e) if format!("{e:#}").contains("exists") => Ok(None),
362 Err(e) => Err(e),
363 }
364}
365
366#[cfg(test)]
367mod tests {
368 use super::{api_unit, pending};
369 use crate::front_door::{State, WiredUnit};
370
371 fn state(api: &[(&str, &[&str])], wired: &[(&str, Option<&str>, &[&str])]) -> State {
373 State {
374 schema: String::new(),
375 name: "lib".into(),
376 commands: Vec::new(),
377 units: wired
378 .iter()
379 .map(|(name, unit, kept)| WiredUnit {
380 name: (*name).into(),
381 crate_name: format!("{name}-rs"),
382 path: format!("../{name}-rs"),
383 commands: Vec::new(),
384 routes: Vec::new(),
385 switch: format!("RUST_ANYTHING_UNIT_{}", name.to_uppercase()),
386 unit: unit.map(ToString::to_string),
387 shadow: None,
388 kept: kept.iter().map(|k| (*k).to_string()).collect(),
389 })
390 .collect(),
391 lifted: false,
392 kind: crate::front_door::AppKind::Library,
393 routes: Vec::new(),
394 api: api
395 .iter()
396 .map(|(unit, exports)| crate::library::ApiUnit {
397 unit: (*unit).to_string(),
398 module: (*unit).replace('/', "_"),
399 exports: exports.iter().map(|e| (*e).to_string()).collect(),
400 })
401 .collect(),
402 }
403 }
404
405 #[test]
406 fn every_export_is_pending_until_its_unit_is_wired() {
407 let s = state(
410 &[("src/textkit", &["split", "join"]), ("src/net", &["get"])],
411 &[],
412 );
413 assert_eq!(
414 pending(&s),
415 vec!["src/textkit: split", "src/textkit: join", "src/net: get"]
416 );
417 }
418
419 #[test]
420 fn a_wired_unit_is_pending_only_for_the_exports_it_kept() {
421 let s = state(
422 &[("src/textkit", &["split", "join"])],
423 &[("textkit", Some("src/textkit"), &["join"])],
424 );
425 assert_eq!(pending(&s), vec!["src/textkit: join"]);
426 }
427
428 #[test]
429 fn nothing_is_pending_once_every_unit_is_wired_and_keeps_nothing() {
430 let s = state(
431 &[("src/textkit", &["split"]), ("src/net", &["get"])],
432 &[
433 ("textkit", Some("src/textkit"), &[]),
434 ("net", Some("src/net"), &[]),
435 ],
436 );
437 assert!(pending(&s).is_empty(), "{:?}", pending(&s));
438 }
439
440 #[test]
441 fn a_unit_is_found_with_or_without_a_trailing_slash() {
442 let s = state(&[("src/textkit", &["split"])], &[]);
443 assert_eq!(api_unit(&s, "src/textkit").unwrap().unit, "src/textkit");
444 assert_eq!(
445 api_unit(&s, "src/textkit/").unwrap().unit,
446 "src/textkit",
447 "a trailing slash on the argument still finds the unit"
448 );
449 let slashed = state(&[("src/textkit/", &["split"])], &[]);
451 assert_eq!(
452 api_unit(&slashed, "src/textkit").unwrap().unit,
453 "src/textkit/"
454 );
455 }
456
457 #[test]
458 fn an_unknown_unit_names_itself_and_the_units_that_exist() {
459 let s = state(&[("src/textkit", &["split"]), ("src/net", &["get"])], &[]);
460 let err = api_unit(&s, "src/missing").unwrap_err().to_string();
461 assert!(
462 err.contains("`src/missing` is not part of the public API"),
463 "{err}"
464 );
465 assert!(
466 err.contains("src/textkit, src/net"),
467 "the units are listed: {err}"
468 );
469 }
470}