1use crate::walk::Canonical;
8use std::collections::BTreeSet;
9use std::path::{Path, PathBuf};
10use std::process::Command;
11
12use anyhow::{Context, Result, bail, ensure};
13use regex::Regex;
14use serde::Serialize;
15use toml_edit::{DocumentMut, Item as TomlItem, value};
16
17use crate::app::{self, ReplayOptions, ReplayOutcome};
18use crate::front_door::{self, APP_DIR, AppKind, MAIN_RS, STATE_FILE, State};
19use crate::front_door_http as http_door;
20use crate::gate::{self, Check};
21
22const BINDING_DEPS: [&str; 9] = [
23 "napi",
24 "napi-derive",
25 "napi-build",
26 "wasm-bindgen",
27 "pyo3",
28 "pyo3-build-config",
29 "magnus",
30 "rb-sys",
31 "jni",
32];
33const GENERATED_FILES: [&str; 3] = ["build.rs", "index.cjs", "index.d.ts"];
34const GENERATED_DIRS: [&str; 7] = ["python", "go", "ruby", "java", "include", "shadow", "pkg"];
35const GENERATED_MODULES: [&str; 6] = ["js", "wire", "pyconv", "rbconv", "utf16", "pynum"];
36const ASSET_DIRS: [&str; 9] = [
37 "assets",
38 "templates",
39 "static",
40 "data",
41 "locales",
42 "i18n",
43 "public",
44 "resources",
45 "share",
46];
47const TARGET_TRIPLE: &str = r"\b(?:x86_64|aarch64|i686|i586|armv7|arm|thumbv7em|wasm32|wasm64|riscv64gc|powerpc64le|s390x|loongarch64)-[a-z0-9_]+(?:-[a-z0-9_]+){1,2}\b";
48
49const LIFTED_MAIN: &str = "mod cli;
50mod units;
51
52use std::process::ExitCode;
53
54fn main() -> ExitCode {
55 let matches = cli::command().get_matches();
56 let (command, sub) = matches.subcommand().unwrap_or((cli::ROOT, &matches));
57 units::dispatch(command, sub).unwrap_or_else(|| {
58 eprintln!(\"{}: no handler for `{command}`\", cli::ROOT);
59 ExitCode::from(2)
60 })
61}
62";
63
64#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
65#[serde(rename_all = "lowercase")]
66pub enum Mark {
67 Pass,
68 Warn,
69 Fail,
70 Skip,
71}
72
73#[derive(Debug, Serialize)]
75pub struct Item {
76 pub name: String,
77 pub mark: Mark,
78 pub detail: String,
79}
80
81impl Item {
82 fn new(name: impl Into<String>, mark: Mark, detail: impl Into<String>) -> Self {
83 Item {
84 name: name.into(),
85 mark,
86 detail: detail.into(),
87 }
88 }
89
90 fn from_check(prefix: &str, check: Check) -> Self {
91 Item::new(
92 format!("{prefix}: {}", check.name),
93 if check.passed { Mark::Pass } else { Mark::Fail },
94 check.detail,
95 )
96 }
97}
98
99pub struct LiftOptions<'a> {
100 pub repo: &'a Path,
101}
102
103#[derive(Debug, Serialize)]
104pub struct LiftOutcome {
105 pub lifted: bool,
106 pub blockers: Vec<String>,
108 pub checklist: Vec<Item>,
109 pub units: Vec<String>,
110 pub removed: Vec<String>,
112 pub binary: Option<PathBuf>,
113 pub replay: Option<ReplayOutcome>,
115 pub stage: Option<PathBuf>,
117}
118
119impl LiftOutcome {
120 fn refused(blockers: Vec<String>, checklist: Vec<Item>, stage: Option<PathBuf>) -> Self {
121 LiftOutcome {
122 lifted: false,
123 blockers,
124 checklist,
125 units: Vec::new(),
126 removed: Vec::new(),
127 binary: None,
128 replay: None,
129 stage,
130 }
131 }
132}
133
134fn copy_tree(from: &Path, to: &Path) -> Result<()> {
135 std::fs::create_dir_all(to)?;
136 for entry in std::fs::read_dir(from)?.flatten() {
137 let name = entry.file_name();
138 if name == "target" || name == ".git" {
139 continue;
140 }
141 let kind = entry.file_type()?;
142 if kind.is_dir() {
143 copy_tree(&entry.path(), &to.join(&name))?;
144 } else if kind.is_file() {
145 std::fs::copy(entry.path(), to.join(&name))?;
146 }
147 }
148 Ok(())
149}
150
151fn files_under(root: &Path) -> Vec<PathBuf> {
152 let mut out = Vec::new();
153 let mut stack = vec![root.to_path_buf()];
154 while let Some(dir) = stack.pop() {
155 let Ok(entries) = std::fs::read_dir(&dir) else {
156 continue;
157 };
158 for entry in entries.flatten() {
159 let path = entry.path();
160 if dir == root && (entry.file_name() == "target" || entry.file_name() == ".git") {
161 continue;
162 }
163 match entry.file_type() {
164 Ok(t) if t.is_dir() => stack.push(path),
165 Ok(t) if t.is_file() => out.push(path),
166 _ => {}
167 }
168 }
169 }
170 out.sort();
171 out
172}
173
174fn remove_empty_dirs(root: &Path) {
175 let Ok(entries) = std::fs::read_dir(root) else {
176 return;
177 };
178 for entry in entries.flatten() {
179 if entry.file_type().is_ok_and(|t| t.is_dir()) && entry.file_name() != "target" {
180 remove_empty_dirs(&entry.path());
181 let _ = std::fs::remove_dir(entry.path());
182 }
183 }
184}
185
186fn sync(from: &Path, to: &Path) -> Result<Vec<PathBuf>> {
188 let mut removed = Vec::new();
189 for path in files_under(to) {
190 let rel = path.strip_prefix(to).unwrap_or(&path);
191 if !from.join(rel).exists() {
192 std::fs::remove_file(&path)?;
193 removed.push(path);
194 }
195 }
196 copy_tree(from, to)?;
197 remove_empty_dirs(to);
198 Ok(removed)
199}
200
201fn port_modules(src: &Path) -> BTreeSet<String> {
203 let single = Regex::new(r"(?:crate|super)::([A-Za-z_][A-Za-z0-9_]*)").expect("valid regex");
204 let group = Regex::new(r"(?:crate|super)::\{([^}]*)\}").expect("valid regex");
205 let module_file = |name: &str| -> Option<PathBuf> {
206 [
207 src.join(format!("{name}.rs")),
208 src.join(name).join("mod.rs"),
209 ]
210 .into_iter()
211 .find(|p| p.is_file())
212 };
213 let mut keep = BTreeSet::new();
214 let mut queue = vec![src.join("port.rs")];
215 while let Some(file) = queue.pop() {
216 let text = std::fs::read_to_string(&file).unwrap_or_default();
217 let mut names: Vec<String> = single
218 .captures_iter(&text)
219 .map(|c| c[1].to_string())
220 .collect();
221 for c in group.captures_iter(&text) {
222 names.extend(
223 c[1].split(',')
224 .filter_map(|n| n.split("::").next())
225 .map(|n| n.trim().to_string()),
226 );
227 }
228 for name in names {
229 if name == "port" || keep.contains(&name) {
230 continue;
231 }
232 if let Some(path) = module_file(&name) {
233 keep.insert(name);
234 queue.push(path);
235 }
236 }
237 }
238 keep
239}
240
241fn path_dependencies(roots: &[PathBuf], rust_dir: &Path) -> Vec<PathBuf> {
246 let mut seen: BTreeSet<PathBuf> = roots.iter().cloned().collect();
247 let mut found = Vec::new();
248 let mut queue: Vec<PathBuf> = roots.to_vec();
249 while let Some(dir) = queue.pop() {
250 let Ok(text) = std::fs::read_to_string(dir.join("Cargo.toml")) else {
251 continue;
252 };
253 let Ok(doc) = text.parse::<DocumentMut>() else {
254 continue;
255 };
256 for table in ["dependencies", "dev-dependencies", "build-dependencies"] {
257 let Some(deps) = doc.get(table).and_then(TomlItem::as_table_like) else {
258 continue;
259 };
260 for (_, dep) in deps.iter() {
261 let Some(path) = dep.get("path").and_then(TomlItem::as_str) else {
262 continue;
263 };
264 let Ok(target) = dir.join(path).canonical() else {
265 continue;
266 };
267 if target.starts_with(rust_dir) && seen.insert(target.clone()) {
268 found.push(target.clone());
269 queue.push(target);
270 }
271 }
272 }
273 }
274 found.sort();
275 found
276}
277
278fn stripped_lib_rs(keep: &[String]) -> String {
281 let mut modules: Vec<&str> = keep.iter().map(String::as_str).collect();
282 modules.push("port");
283 modules.sort_unstable();
284 modules.dedup();
285 modules.iter().map(|m| format!("pub mod {m};\n")).collect()
286}
287
288pub fn strip_unit(dir: &Path) -> Result<Vec<PathBuf>> {
289 let cargo = dir.join("Cargo.toml");
290 let mut doc: DocumentMut = std::fs::read_to_string(&cargo)
291 .with_context(|| format!("reading {}", cargo.display()))?
292 .parse()
293 .with_context(|| format!("parsing {}", cargo.display()))?;
294 if let Some(lib) = doc.get_mut("lib").and_then(TomlItem::as_table_mut) {
295 lib.remove("crate-type");
296 if lib.is_empty() {
297 doc.remove("lib");
298 }
299 }
300 for table in ["dependencies", "build-dependencies"] {
301 if let Some(deps) = doc.get_mut(table).and_then(TomlItem::as_table_like_mut) {
302 for dep in BINDING_DEPS {
303 deps.remove(dep);
304 }
305 }
306 }
307 if doc
308 .get("build-dependencies")
309 .and_then(TomlItem::as_table_like)
310 .is_some_and(|t| t.is_empty())
311 {
312 doc.remove("build-dependencies");
313 }
314 if let Some(package) = doc.get_mut("package").and_then(TomlItem::as_table_mut) {
315 package.remove("build");
316 }
317 std::fs::write(&cargo, doc.to_string())?;
318
319 let mut removed = Vec::new();
320 if !dir.join(crate::bridge::MANIFEST).exists() {
321 return Ok(removed);
322 }
323 let src = dir.join("src");
324 let keep = port_modules(&src);
325 let kept: Vec<String> = keep.iter().cloned().collect();
326 std::fs::write(src.join("lib.rs"), stripped_lib_rs(&kept))?;
327 for file in GENERATED_FILES {
328 let path = dir.join(file);
329 if path.is_file() {
330 std::fs::remove_file(&path)?;
331 removed.push(path);
332 }
333 }
334 for sub in GENERATED_DIRS {
335 let path = dir.join(sub);
336 if path.is_dir() {
337 removed.extend(files_under(&path));
338 std::fs::remove_dir_all(&path)?;
339 }
340 }
341 for module in GENERATED_MODULES {
342 let path = src.join(format!("{module}.rs"));
343 if !keep.contains(module) && path.is_file() {
344 std::fs::remove_file(&path)?;
345 removed.push(path);
346 }
347 }
348 for entry in std::fs::read_dir(dir)?.flatten() {
349 let path = entry.path();
350 if path.extension().is_some_and(|e| e == "node") && path.is_file() {
351 std::fs::remove_file(&path)?;
352 removed.push(path);
353 }
354 }
355 Ok(removed)
356}
357
358fn lifted_units_rs(state: &State) -> String {
359 let mut out = String::from(
360 "//! Written by `rust-anything app lift`: every command is answered in Rust.\n\n\
361 use std::process::ExitCode;\n\n\
362 use clap::ArgMatches;\n\n",
363 );
364 for unit in &state.units {
365 out += &format!("mod {};\n", front_door::ident(&unit.name));
366 }
367 out += "\npub fn dispatch(command: &str, matches: &ArgMatches) -> Option<ExitCode> {\n match command {\n";
368 for unit in &state.units {
369 let pattern: Vec<String> = unit.commands.iter().map(|c| format!("{c:?}")).collect();
370 out += &format!(
371 " {} => Some({}::run(command, matches)),\n",
372 pattern.join(" | "),
373 front_door::ident(&unit.name)
374 );
375 }
376 out += " _ => None,\n }\n}\n";
377 out
378}
379
380fn cases_test_rs(case_bin: &str, binary: &str, unordered: &[&String]) -> String {
381 let skips: String = unordered
382 .iter()
383 .map(|case| format!("\n .skip(\"../app-cases/{case}.toml\")"))
384 .collect();
385 format!(
386 "#[test]\n\
387 fn recorded_cases() {{\n \
388 trycmd::TestCases::new()\n \
389 .register_bin(\n \
390 {case_bin:?},\n \
391 std::path::Path::new(env!(\"CARGO_BIN_EXE_{binary}\")),\n \
392 )\n \
393 .case(\"../app-cases/*.toml\"){skips};\n\
394 }}\n"
395 )
396}
397
398fn same_code(a: &str, b: &str) -> bool {
399 let squash = |s: &str| s.split_whitespace().collect::<String>();
400 squash(a) == squash(b)
401}
402
403fn generated_mains(state: &State) -> Vec<String> {
404 match state.kind {
405 AppKind::Cli => vec![MAIN_RS.to_string()],
406 AppKind::Http => http_door::main_rs_versions(),
407 AppKind::Library => Vec::new(),
408 }
409}
410
411fn is_generated_main(code: &str, state: &State) -> bool {
412 generated_mains(state).iter().any(|m| same_code(code, m))
413}
414
415fn ship_settings(doc: &mut DocumentMut) {
416 if doc["package"].get("rust-version").is_none() {
417 doc["package"]["rust-version"] = value(crate::MIN_RUST);
418 }
419 let release = doc["profile"]["release"].or_insert(toml_edit::table());
420 if let Some(release) = release.as_table_like_mut() {
421 if release.get("lto").is_none() {
422 release.insert("lto", value(true));
423 }
424 if release.get("codegen-units").is_none() {
425 release.insert("codegen-units", value(1));
426 }
427 }
428 if let Some(profile) = doc["profile"].as_table_mut() {
429 profile.set_implicit(true);
430 }
431}
432
433fn lift_library(stage_app: &Path, state: &mut State) -> Result<()> {
434 state.lifted = true;
435 let _ = std::fs::remove_file(stage_app.join(crate::library::CARGO_CONFIG));
436 let lib = stage_app.join("src/lib.rs");
437 std::fs::write(&lib, crate::library::lib_rs(state, true))?;
438 front_door::rustfmt(&lib);
439 std::fs::write(
440 stage_app.join(STATE_FILE),
441 serde_json::to_string_pretty(state)? + "\n",
442 )?;
443 let cargo = stage_app.join("Cargo.toml");
444 let mut doc: DocumentMut = std::fs::read_to_string(&cargo)?.parse()?;
445 doc["package"]["description"] = value(format!(
446 "`{}` in Rust, lifted by rust-anything from its units' ports",
447 state.name
448 ));
449 ship_settings(&mut doc);
450 std::fs::write(&cargo, doc.to_string())?;
451 Ok(())
452}
453
454fn lift_app(
455 stage_app: &Path,
456 state: &mut State,
457 case_bin: &str,
458 unordered: &[&String],
459) -> Result<()> {
460 if state.kind == AppKind::Library {
461 return lift_library(stage_app, state);
462 }
463 let http = state.kind == AppKind::Http;
464 let main = stage_app.join("src/main.rs");
465 if is_generated_main(&std::fs::read_to_string(&main)?, state) {
466 let lifted = if http {
467 http_door::lifted_main_rs()
468 } else {
469 LIFTED_MAIN.to_string()
470 };
471 std::fs::write(&main, lifted)?;
472 }
473 let _ = std::fs::remove_file(stage_app.join("src/original.rs"));
474 let cli = stage_app.join("src/cli.rs");
475 if let Ok(text) = std::fs::read_to_string(&cli) {
476 std::fs::write(
477 &cli,
478 text.replace(
479 "/// Routes argv to a command. Anything this parser rejects runs the original, so it never\n/// has to match every way the original accepts its arguments.\n",
480 "/// Parses argv into a command and its arguments.\n",
481 ),
482 )?;
483 }
484 state.lifted = true;
485 let units = stage_app.join("src/units/mod.rs");
486 let routing = if http {
487 http_door::units_rs(state, true)
488 } else {
489 lifted_units_rs(state)
490 };
491 std::fs::write(&units, routing)?;
492 front_door::rustfmt(&units);
493 std::fs::write(
494 stage_app.join(STATE_FILE),
495 serde_json::to_string_pretty(state)? + "\n",
496 )?;
497
498 let cargo = stage_app.join("Cargo.toml");
499 let mut doc: DocumentMut = std::fs::read_to_string(&cargo)?.parse()?;
500 let binary = doc["package"]["name"]
501 .as_str()
502 .context("rust/app/Cargo.toml has no package name")?
503 .to_string();
504 if let Some(description) = doc["package"].get("description").and_then(|d| d.as_str())
505 && description.starts_with("Front door for")
506 {
507 doc["package"]["description"] = value(format!(
508 "`{}` in Rust, lifted by rust-anything from its front door",
509 state.name
510 ));
511 }
512 ship_settings(&mut doc);
513 if http {
514 if let Some(deps) = doc
515 .get_mut("dependencies")
516 .and_then(TomlItem::as_table_like_mut)
517 {
518 deps.remove("reqwest");
519 }
520 std::fs::write(&cargo, doc.to_string())?;
521 front_door::rustfmt(&main);
522 return Ok(());
523 }
524 doc["dev-dependencies"]["trycmd"] = value("1");
525 std::fs::write(&cargo, doc.to_string())?;
526 std::fs::create_dir_all(stage_app.join("tests"))?;
527 let test = stage_app.join("tests/app_cases.rs");
528 std::fs::write(&test, cases_test_rs(case_bin, &binary, unordered))?;
529 front_door::rustfmt(&test);
530 front_door::rustfmt(&main);
531 Ok(())
532}
533
534fn command_output(program: &str, args: &[&str]) -> Option<String> {
535 let out = Command::new(program).args(args).output().ok()?;
536 out.status
537 .success()
538 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
539}
540
541fn target_items(repo: &Path, stage_app: &Path, target_dir: &Path) -> Vec<Item> {
542 let decisions = repo.join("rust/DECISIONS.md");
543 let Ok(text) = std::fs::read_to_string(&decisions) else {
544 return vec![Item::new(
545 "targets",
546 Mark::Skip,
547 "no rust/DECISIONS.md: only the host target was built",
548 )];
549 };
550 let triple = Regex::new(TARGET_TRIPLE).expect("valid regex");
551 let targets: BTreeSet<&str> = triple.find_iter(&text).map(|m| m.as_str()).collect();
552 if targets.is_empty() {
553 return vec![Item::new(
554 "targets",
555 Mark::Skip,
556 "rust/DECISIONS.md names no target triple: only the host target was built",
557 )];
558 }
559 let host = command_output("rustc", &["-vV"]).and_then(|v| {
560 v.lines()
561 .find_map(|l| l.strip_prefix("host: ").map(str::to_string))
562 });
563 let installed: Vec<String> = command_output("rustup", &["target", "list", "--installed"])
564 .map(|t| t.lines().map(str::to_string).collect())
565 .unwrap_or_default();
566 targets
567 .into_iter()
568 .map(|target| {
569 let name = format!("target {target}");
570 if host.as_deref() == Some(target) {
571 return Item::new(name, Mark::Pass, "the host: built and tested above");
572 }
573 if !installed.iter().any(|t| t == target) {
574 return Item::new(
575 name,
576 Mark::Skip,
577 format!("not installed here: `rustup target add {target}` to check it"),
578 );
579 }
580 let out = Command::new("cargo")
581 .args(["check", "--quiet", "--target", target, "--manifest-path"])
582 .arg(stage_app.join("Cargo.toml"))
583 .env("CARGO_TARGET_DIR", target_dir)
584 .output();
585 match out {
586 Ok(o) if o.status.success() => {
587 Item::new(name, Mark::Pass, "`cargo check` passes (not linked)")
588 }
589 Ok(o) => Item::new(
590 name,
591 Mark::Fail,
592 String::from_utf8_lossy(&o.stderr)
593 .lines()
594 .rev()
595 .take(10)
596 .collect::<Vec<_>>()
597 .into_iter()
598 .rev()
599 .collect::<Vec<_>>()
600 .join("\n"),
601 ),
602 Err(e) => Item::new(name, Mark::Fail, e.to_string()),
603 }
604 })
605 .collect()
606}
607
608fn asset_items(repo: &Path, sources: &[PathBuf]) -> Vec<Item> {
609 let reads =
610 Regex::new(r#"(?:read_to_string|read|read_dir|read_to_end|File::open|open)\(\s*"([^"]+)""#)
611 .expect("valid regex");
612 let mut items = Vec::new();
613 let mut included = String::new();
614 for root in sources {
615 for file in files_under(root) {
616 if file.extension().is_none_or(|e| e != "rs") {
617 continue;
618 }
619 let text = std::fs::read_to_string(&file).unwrap_or_default();
620 for line in text.lines().filter(|l| l.contains("include_")) {
621 included += line;
622 }
623 for c in reads.captures_iter(&text) {
624 items.push(Item::new(
625 "assets",
626 Mark::Warn,
627 format!(
628 "{} reads `{}` at run time from the working directory: embed it with include_str!/include_bytes! or ship it with the binary",
629 file.file_name().unwrap_or_default().to_string_lossy(),
630 &c[1]
631 ),
632 ));
633 }
634 }
635 }
636 for dir in ASSET_DIRS {
637 if repo.join(dir).is_dir() && !included.contains(dir) {
638 items.push(Item::new(
639 "assets",
640 Mark::Warn,
641 format!(
642 "the original has `{dir}/` and no include_str!/include_bytes! names it: embed what the app reads, or ship it with the binary"
643 ),
644 ));
645 }
646 }
647 if items.is_empty() {
648 items.push(Item::new(
649 "assets",
650 Mark::Pass,
651 "no file read at run time from a fixed path, and no asset folder in the original",
652 ));
653 }
654 items
655}
656
657pub fn lift(opts: &LiftOptions) -> Result<LiftOutcome> {
658 let repo = opts
659 .repo
660 .canonical()
661 .with_context(|| format!("no folder {}", opts.repo.display()))?;
662 let mut state = State::load(&repo)?;
663 if state.lifted {
664 bail!("{} is already lifted", repo.join(APP_DIR).display());
665 }
666 let library = state.kind == AppKind::Library;
667 let config = app::Config::load(&repo)?;
668 ensure!(
669 library || config.is_some(),
670 "no recorded cases: run `app record` first"
671 );
672 let case_bin = config
673 .as_ref()
674 .map_or_else(|| state.name.clone(), |c| c.name.clone());
675 let key_order = config
676 .as_ref()
677 .is_some_and(|c| c.normalize.iter().any(|n| n == "key-order"));
678 let unordered: Vec<&String> = config
679 .as_ref()
680 .map(|c| c.unordered.keys().collect())
681 .unwrap_or_default();
682 let app_dir = repo.join(APP_DIR);
683 let rust_dir = repo.join("rust");
684 let mut blockers = Vec::new();
685 if state.units.is_empty() {
686 blockers.push("no unit is wired yet: run `rust-anything app wire` first".to_string());
687 }
688 let mut units = Vec::new();
689 for unit in &state.units {
690 let dir = app_dir
691 .join(&unit.path)
692 .canonical()
693 .with_context(|| format!("unit crate {} not found", unit.path))?;
694 if !dir.starts_with(&rust_dir) {
695 blockers.push(format!(
696 "{}: lift works on unit crates under rust/, and this one is at {}",
697 unit.crate_name,
698 dir.display()
699 ));
700 }
701 let glue = app_dir
702 .join("src/units")
703 .join(format!("{}.rs", front_door::ident(&unit.name)));
704 let glue_text = std::fs::read_to_string(&glue).unwrap_or_default();
705 if !library && front_door::is_stub(&glue_text) {
706 blockers.push(format!(
707 "{}: the glue in {} is still the generated stub",
708 unit.name,
709 glue.display()
710 ));
711 } else if !library && glue_text.contains("original::") {
712 blockers.push(format!(
713 "{}: the glue in {} still hands cases to the original (`original::`): answer them in Rust, then lift again",
714 unit.name,
715 glue.display()
716 ));
717 }
718 units.push((unit.clone(), dir));
719 }
720 let main = std::fs::read_to_string(app_dir.join("src/main.rs")).unwrap_or_default();
721 if !library && !is_generated_main(&main, &state) && main.contains("original::") {
722 blockers.push(
723 "src/main.rs was changed and still calls the original: remove `mod original`, `original::report_fallbacks()` and `original::run` by hand, then lift again"
724 .to_string(),
725 );
726 }
727
728 let target_dir = app_dir.join("target");
729 let before = if library {
730 crate::library::cargo_build_lib(&app_dir, Some(&target_dir))
731 .and_then(|()| crate::library::replay(&repo, &state, None))
732 } else {
733 front_door::cargo_build(&app_dir, Some(&target_dir)).and_then(|exe| {
734 app::replay(&ReplayOptions {
735 case: None,
736 repo: &repo,
737 build: Some(&app::shell_quote(&exe.to_string_lossy())),
738 timeout_secs: None,
739 port: None,
740 })
741 })
742 };
743 let replay_before = match &before {
744 Ok(r) => Some((r.passed, r.total)),
745 Err(_) => None,
746 };
747 match before {
748 Err(e) => blockers.push(format!("the front door does not build: {e:#}")),
749 Ok(replay) => {
750 if replay.passed != replay.total {
751 blockers.push(format!(
752 "{} of {} cases fail against the front door (see {})",
753 replay.total - replay.passed,
754 replay.total,
755 replay.report.display()
756 ));
757 }
758 match &replay.fallback {
759 None => blockers.push(
760 "the front door does not report its fallbacks (src/original.rs changed?)"
761 .to_string(),
762 ),
763 Some(f) if f.cases > 0 => {
764 let mut names = f.names.iter().take(10).cloned().collect::<Vec<_>>();
765 if f.names.len() > 10 {
766 names.push(format!("and {} more", f.names.len() - 10));
767 }
768 blockers.push(if library {
769 format!(
770 "{} of {} exports are still only in the original ({}): wire their units",
771 f.cases,
772 f.total,
773 names.join(", ")
774 )
775 } else {
776 format!(
777 "{} of {} cases still fall back to the original ({}): wire units for them",
778 f.cases,
779 f.total,
780 names.join(", ")
781 )
782 });
783 }
784 Some(_) => {}
785 }
786 }
787 }
788 for (unit, dir) in &units {
789 let checks = if dir.join(crate::bridge::MANIFEST).exists() {
790 gate::gate(dir, &[])?.checks
791 } else {
792 let mut checks = gate::rust_checks(dir, &dir.join("target"));
793 checks.push(gate::ported_check(dir));
794 checks
795 };
796 let failed: Vec<&str> = checks
797 .iter()
798 .filter(|c| !c.passed)
799 .map(|c| c.name)
800 .collect();
801 if !failed.is_empty() {
802 blockers.push(format!(
803 "{}: gate fails ({}): run `rust-anything gate {}`",
804 unit.crate_name,
805 failed.join(", "),
806 dir.display()
807 ));
808 }
809 }
810 if !blockers.is_empty() {
811 return Ok(LiftOutcome::refused(blockers, Vec::new(), None));
812 }
813
814 let stage = std::env::temp_dir().join(format!(
815 "rust-anything-lift-{}-{}",
816 std::process::id(),
817 std::time::SystemTime::now()
818 .duration_since(std::time::UNIX_EPOCH)
819 .map_or(0, |d| d.as_nanos())
820 ));
821 let stage_rust = stage.join("rust");
822 copy_tree(&app_dir, &stage_rust.join("app"))?;
823 if app::cases_dir(&repo).is_dir() {
824 copy_tree(&app::cases_dir(&repo), &stage_rust.join("app-cases"))?;
825 }
826 let mut staged_units = Vec::new();
827 for (unit, dir) in &units {
828 let rel = dir.strip_prefix(&rust_dir).unwrap_or(dir);
829 let staged = stage_rust.join(rel);
830 copy_tree(dir, &staged)?;
831 strip_unit(&staged)?;
832 staged_units.push((unit.clone(), dir.clone(), staged));
833 }
834 let unit_dirs: Vec<PathBuf> = units.iter().map(|(_, dir)| dir.clone()).collect();
835 let mut staged_deps = Vec::new();
836 for dir in path_dependencies(&unit_dirs, &rust_dir) {
837 if dir == app_dir.canonical().unwrap_or_else(|_| app_dir.clone()) {
838 continue;
839 }
840 let rel = dir.strip_prefix(&rust_dir).unwrap_or(&dir);
841 let staged = stage_rust.join(rel);
842 copy_tree(&dir, &staged)?;
843 strip_unit(&staged)?;
844 staged_deps.push((dir, staged));
845 }
846 let stage_app = stage_rust.join("app");
847 lift_app(&stage_app, &mut state, &case_bin, &unordered)?;
848
849 let mut checklist = Vec::new();
850 for (unit, dir, staged) in &staged_units {
851 for check in gate::rust_checks(staged, &dir.join("target")) {
852 checklist.push(Item::from_check(&unit.crate_name, check));
853 }
854 }
855 for (dir, staged) in &staged_deps {
856 let name = dir
857 .file_name()
858 .map_or_else(String::new, |n| n.to_string_lossy().into_owned());
859 for check in gate::rust_checks(staged, &dir.join("target")) {
860 checklist.push(Item::from_check(&name, check));
861 }
862 }
863 for check in gate::rust_checks(&stage_app, &target_dir) {
864 checklist.push(Item::from_check("rust/app", check));
865 }
866 checklist.push(Item::new(
867 "replay in CI",
868 if state.kind != AppKind::Cli || key_order || !unordered.is_empty() {
869 Mark::Warn
870 } else {
871 Mark::Pass
872 },
873 if library {
874 "the recorded cases ran through the units' bindings, which the lift removes: `cargo test` on the crates is what CI keeps; turn the cases that matter into Rust tests"
875 } else if state.kind == AppKind::Http {
876 "trycmd runs command lines only: run `rust-anything app replay <repo> --build <the binary>` in CI for the HTTP cases"
877 } else if !unordered.is_empty() {
878 "rust/app/tests/app_cases.rs runs the cases with trycmd on `cargo test`, which compares line order exactly, so it skips the cases whose order the original's own runs disagreed on: also run `rust-anything app replay` in CI for them"
879 } else if key_order {
880 "rust/app/tests/app_cases.rs runs the cases with trycmd on `cargo test`, which compares JSON as text: also run `rust-anything app replay` in CI for the key-order normalizer"
881 } else {
882 "rust/app/tests/app_cases.rs runs the recorded cases with trycmd on `cargo test`"
883 },
884 ));
885 checklist.extend(target_items(&repo, &stage_app, &target_dir));
886 let mut sources = vec![stage_app.join("src")];
887 sources.extend(staged_units.iter().map(|(_, _, s)| s.join("src")));
888 checklist.extend(asset_items(&repo, &sources));
889
890 if library {
891 let references = crate::library::original_references(&repo, &state);
892 checklist.push(if references.is_empty() {
893 Item::new(
894 "original package",
895 Mark::Pass,
896 "nothing in the original names the units' bindings or shadows",
897 )
898 } else {
899 Item::new(
900 "original package",
901 Mark::Warn,
902 format!(
903 "these files use the units' bindings or shadows, which the lift removes; the original stays as reference, so point them back at its own modules: {}",
904 references.join(", ")
905 ),
906 )
907 });
908 let unchanged = staged_units.iter().all(|(_, dir, staged)| {
909 std::fs::read(dir.join("src/port.rs")).ok()
910 == std::fs::read(staged.join("src/port.rs")).ok()
911 });
912 let built = crate::library::cargo_build_lib(&stage_app, Some(&target_dir));
913 let (passed, total) = replay_before.unwrap_or((0, 0));
914 checklist.push(Item::new(
915 "replay",
916 if built.is_ok() && unchanged && passed == total {
917 Mark::Pass
918 } else {
919 Mark::Fail
920 },
921 match built {
922 Err(e) => format!("{e:#}"),
923 Ok(()) => format!(
924 "{passed}/{total} recorded cases matched through the bindings before the lift; the lift leaves every port.rs as it was, and the whole API builds as one Rust library"
925 ),
926 },
927 ));
928 }
929 let built = if library {
930 Ok(PathBuf::new())
931 } else {
932 front_door::cargo_build(&stage_app, Some(&target_dir))
933 };
934 let replay = match built {
935 Ok(_) if library => None,
936 Err(e) => {
937 checklist.push(Item::new("build", Mark::Fail, format!("{e:#}")));
938 None
939 }
940 Ok(exe) => {
941 let replay = app::replay(&ReplayOptions {
942 case: None,
943 repo: &repo,
944 build: Some(&app::shell_quote(&exe.to_string_lossy())),
945 timeout_secs: None,
946 port: None,
947 })?;
948 checklist.push(Item::new(
949 "replay",
950 if replay.passed == replay.total {
951 Mark::Pass
952 } else {
953 Mark::Fail
954 },
955 format!(
956 "{}/{} cases pass against the lifted binary, fallback rate 0 (no fallback path left)",
957 replay.passed, replay.total
958 ),
959 ));
960 Some(replay)
961 }
962 };
963 let failed: Vec<String> = checklist
964 .iter()
965 .filter(|i| i.mark == Mark::Fail)
966 .map(|i| format!("{}: {}", i.name, i.detail))
967 .collect();
968 if !failed.is_empty() {
969 let mut outcome = LiftOutcome::refused(failed, checklist, Some(stage));
970 outcome.replay = replay;
971 return Ok(outcome);
972 }
973
974 let mut removed = Vec::new();
975 removed.extend(sync(&stage_app, &app_dir)?);
976 for (_, dir, staged) in &staged_units {
977 removed.extend(sync(staged, dir)?);
978 }
979 for (dir, staged) in &staged_deps {
980 removed.extend(sync(staged, dir)?);
981 }
982 let _ = std::fs::remove_dir_all(&stage);
983 let binary = if library {
984 crate::library::cargo_build_lib(&app_dir, Some(&target_dir))?;
985 None
986 } else {
987 Some(front_door::cargo_build(&app_dir, Some(&target_dir))?)
988 };
989 Ok(LiftOutcome {
990 lifted: true,
991 blockers: Vec::new(),
992 checklist,
993 units: state.units.iter().map(|u| u.crate_name.clone()).collect(),
994 removed: removed
995 .iter()
996 .map(|p| {
997 p.strip_prefix(&repo)
998 .unwrap_or(p)
999 .to_string_lossy()
1000 .into_owned()
1001 })
1002 .collect(),
1003 binary,
1004 replay,
1005 stage: None,
1006 })
1007}
1008
1009#[cfg(test)]
1010mod tests {
1011 #[test]
1012 fn stripped_lib_rs_lists_modules_as_rustfmt_orders_them() {
1013 assert_eq!(
1014 super::stripped_lib_rs(&["utf16".into(), "js".into()]),
1015 "pub mod js;\npub mod port;\npub mod utf16;\n"
1016 );
1017 }
1018
1019 #[test]
1020 fn path_dependencies_are_found_transitively_under_rust() {
1021 let root = crate::app::temp_dir("lift-deps").unwrap();
1022 let rust = root.join("rust");
1023 let write = |name: &str, deps: &str| {
1024 let dir = rust.join(name);
1025 std::fs::create_dir_all(&dir).unwrap();
1026 std::fs::write(
1027 dir.join("Cargo.toml"),
1028 format!("[package]\nname = \"{name}\"\n\n[dependencies]\n{deps}"),
1029 )
1030 .unwrap();
1031 };
1032 std::fs::create_dir_all(root.join("outside")).unwrap();
1033 write(
1034 "unit-rs",
1035 "shared = { path = \"../shared\" }\nother = { path = \"../../outside\" }\nserde = \"1\"\n",
1036 );
1037 write("shared", "leaf = { path = \"../leaf\" }\n");
1038 write("leaf", "");
1039 let rust = rust.canonical().unwrap();
1040 let found = super::path_dependencies(&[rust.join("unit-rs")], &rust);
1041 std::fs::remove_dir_all(&root).unwrap();
1042 assert_eq!(found, [rust.join("leaf"), rust.join("shared")]);
1043 }
1044
1045 use super::*;
1046
1047 #[test]
1048 fn port_modules_follow_crate_paths() {
1049 let dir =
1050 std::env::temp_dir().join(format!("rust-anything-lift-mods-{}", std::process::id()));
1051 let src = dir.join("src");
1052 std::fs::create_dir_all(&src).unwrap();
1053 std::fs::write(
1054 src.join("port.rs"),
1055 "use crate::utf16::len;\nuse crate::{helpers, Thing};\n",
1056 )
1057 .unwrap();
1058 std::fs::write(src.join("utf16.rs"), "").unwrap();
1059 std::fs::write(src.join("helpers.rs"), "use super::deep;\n").unwrap();
1060 std::fs::write(src.join("deep.rs"), "").unwrap();
1061 std::fs::write(src.join("wire.rs"), "").unwrap();
1062 let keep: Vec<String> = port_modules(&src).into_iter().collect();
1063 assert_eq!(keep, ["deep", "helpers", "utf16"]);
1064 std::fs::remove_dir_all(&dir).unwrap();
1065 }
1066
1067 #[test]
1068 fn lifted_routing_has_no_kill_switch() {
1069 let state = State {
1070 schema: String::new(),
1071 name: "tcli".into(),
1072 commands: vec!["words".into()],
1073 units: vec![front_door::WiredUnit {
1074 name: "wordcount".into(),
1075 crate_name: "wordcount-rs".into(),
1076 path: "../wordcount-rs".into(),
1077 commands: vec!["words".into(), "tcli".into()],
1078 switch: "RUST_ANYTHING_UNIT_WORDCOUNT".into(),
1079 routes: Vec::new(),
1080 unit: None,
1081 shadow: None,
1082 kept: Vec::new(),
1083 }],
1084 lifted: true,
1085 kind: AppKind::Cli,
1086 routes: Vec::new(),
1087 api: Vec::new(),
1088 };
1089 let code = lifted_units_rs(&state);
1090 assert!(code.contains("\"words\" | \"tcli\" => Some(wordcount::run(command, matches)),"));
1091 assert!(!code.contains("RUST_ANYTHING_UNIT"));
1092 assert!(!LIFTED_MAIN.contains("original"));
1093 }
1094}