1use crate::walk::Canonical;
6use std::collections::{BTreeMap, BTreeSet};
7use std::path::{Path, PathBuf};
8use std::process::Command;
9
10use anyhow::{Context, Result, bail, ensure};
11use serde::{Deserialize, Serialize};
12use toml_edit::{DocumentMut, InlineTable, value};
13
14use crate::app::{self, ReplayOptions, ReplayOutcome};
15use crate::front_door_http as http_door;
16
17pub const APP_DIR: &str = "rust/app";
18pub const STATE_FILE: &str = "rust-anything.json";
19pub const KILL_SWITCH_PREFIX: &str = "RUST_ANYTHING_UNIT_";
20const SCHEMA: &str = "rust-anything/front-door@1";
21const GLUE_MARKER: &str = "unimplemented!(\"glue for";
22
23pub(crate) fn is_stub(glue: &str) -> bool {
25 let squash = |s: &str| s.split_whitespace().collect::<String>();
26 squash(glue).contains(&squash(GLUE_MARKER))
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct State {
32 pub schema: String,
33 pub name: String,
34 pub commands: Vec<String>,
35 #[serde(default)]
36 pub units: Vec<WiredUnit>,
37 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
38 pub lifted: bool,
39 #[serde(default, skip_serializing_if = "AppKind::is_cli")]
40 pub kind: AppKind,
41 #[serde(default, skip_serializing_if = "Vec::is_empty")]
43 pub routes: Vec<String>,
44 #[serde(default, skip_serializing_if = "Vec::is_empty")]
46 pub api: Vec<crate::library::ApiUnit>,
47}
48
49#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(rename_all = "lowercase")]
51pub enum AppKind {
52 #[default]
53 Cli,
54 Http,
55 Library,
56}
57
58impl AppKind {
59 fn is_cli(&self) -> bool {
60 *self == AppKind::Cli
61 }
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct WiredUnit {
66 pub name: String,
67 #[serde(rename = "crate")]
68 pub crate_name: String,
69 pub path: String,
70 #[serde(default)]
71 pub commands: Vec<String>,
72 #[serde(default, skip_serializing_if = "Vec::is_empty")]
74 pub routes: Vec<String>,
75 pub switch: String,
76 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub unit: Option<String>,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
81 pub shadow: Option<String>,
82 #[serde(default, skip_serializing_if = "Vec::is_empty")]
84 pub kept: Vec<String>,
85}
86
87impl State {
88 pub fn load(repo: &Path) -> Result<State> {
89 let path = repo.join(APP_DIR).join(STATE_FILE);
90 let text = std::fs::read_to_string(&path).with_context(|| {
91 format!(
92 "reading {}: run `rust-anything app front-door` first",
93 path.display()
94 )
95 })?;
96 serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))
97 }
98
99 fn save(&self, repo: &Path) -> Result<()> {
100 let path = repo.join(APP_DIR).join(STATE_FILE);
101 std::fs::write(&path, serde_json::to_string_pretty(self)? + "\n")
102 .with_context(|| format!("writing {}", path.display()))
103 }
104}
105
106#[derive(Debug, Clone, Default, Serialize)]
107pub struct Flag {
108 pub long: Option<String>,
109 pub short: Option<char>,
110 pub takes_value: bool,
111}
112
113fn package_name(name: &str) -> String {
114 let mut out: String = name
115 .chars()
116 .map(|c| {
117 if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
118 c.to_ascii_lowercase()
119 } else {
120 '-'
121 }
122 })
123 .collect();
124 out = out.trim_matches('-').to_string();
125 if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) {
126 out = format!("app-{out}").trim_end_matches('-').to_string();
127 }
128 out
129}
130
131pub fn kill_switch(crate_name: &str) -> String {
133 let name = crate_name.strip_suffix("-rs").unwrap_or(crate_name);
134 format!(
135 "{KILL_SWITCH_PREFIX}{}",
136 ident(name).trim_start_matches("unit_").to_uppercase()
137 )
138}
139
140pub(crate) fn ident(name: &str) -> String {
141 let mut out: String = name
142 .chars()
143 .map(|c| {
144 if c.is_ascii_alphanumeric() {
145 c.to_ascii_lowercase()
146 } else {
147 '_'
148 }
149 })
150 .collect();
151 let keywords = [
152 "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn",
153 "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref",
154 "return", "self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use",
155 "where", "while", "async", "await", "dyn", "gen", "try",
156 ];
157 if out.is_empty()
158 || out.starts_with(|c: char| c.is_ascii_digit())
159 || keywords.contains(&out.as_str())
160 {
161 out = format!("unit_{out}");
162 }
163 out
164}
165
166fn infer_cli(
169 cases: &[(Vec<String>, bool)],
170) -> (Vec<String>, BTreeMap<String, BTreeMap<String, Flag>>) {
171 let commands: BTreeSet<String> = cases
172 .iter()
173 .filter(|(args, ok)| *ok && args.first().is_some_and(|a| app::is_word(a)))
174 .map(|(args, _)| args[0].clone())
175 .collect();
176 let mut flags: BTreeMap<String, BTreeMap<String, Flag>> = BTreeMap::new();
177 for (args, ok) in cases {
178 if !ok {
179 continue;
180 }
181 let (key, rest) = match args.split_first() {
182 Some((first, rest)) if commands.contains(first) => (first.clone(), rest),
183 _ if commands.is_empty() => (String::new(), args.as_slice()),
184 _ => continue,
185 };
186 let entry = flags.entry(key).or_default();
187 for arg in rest {
188 if arg == "--" {
189 break;
190 }
191 if let Some(long) = arg.strip_prefix("--") {
192 let (name, has_value) = match long.split_once('=') {
193 Some((n, _)) => (n, true),
194 None => (long, false),
195 };
196 let valid = !name.is_empty()
197 && name
198 .chars()
199 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
200 if valid {
201 let id = if name == "args" { "flag-args" } else { name };
202 let flag = entry.entry(id.to_string()).or_default();
203 flag.long = Some(name.to_string());
204 flag.takes_value |= has_value;
205 }
206 } else if let Some(short) = arg.strip_prefix('-') {
207 let mut chars = short.chars();
208 if let (Some(c), None) = (chars.next(), chars.next())
209 && c.is_ascii_alphabetic()
210 {
211 entry.entry(format!("short-{c}")).or_default().short = Some(c);
212 }
213 }
214 }
215 }
216 (commands.into_iter().collect(), flags)
217}
218
219fn arg_lines(flags: Option<&BTreeMap<String, Flag>>, indent: &str) -> String {
220 let mut out = String::new();
221 for (id, flag) in flags.into_iter().flatten() {
222 let mut line = format!("{indent}.arg(Arg::new({id:?})");
223 if let Some(long) = &flag.long {
224 line += &format!(".long({long:?})");
225 }
226 if let Some(short) = flag.short {
227 line += &format!(".short({short:?})");
228 }
229 line += if flag.takes_value {
230 ".num_args(1).action(ArgAction::Append).value_parser(value_parser!(OsString)))"
231 } else {
232 ".action(ArgAction::Count))"
233 };
234 out += &line;
235 out.push('\n');
236 }
237 out += &format!("{indent}.arg(rest())\n");
238 out
239}
240
241fn cli_rs(
242 name: &str,
243 commands: &[String],
244 flags: &BTreeMap<String, BTreeMap<String, Flag>>,
245) -> String {
246 let any_flags = flags.values().any(|f| !f.is_empty());
247 let imports = if any_flags {
248 "Arg, ArgAction, Command, value_parser"
249 } else {
250 "Arg, Command, value_parser"
251 };
252 let mut out = format!(
253 "use std::ffi::OsString;\n\n\
254 use clap::{{{imports}}};\n\n\
255 /// The command `units::dispatch` gets when argv names no subcommand.\n\
256 pub const ROOT: &str = {name:?};\n\n\
257 fn rest() -> Arg {{\n \
258 Arg::new(\"args\")\n \
259 .num_args(0..)\n \
260 .trailing_var_arg(true)\n \
261 .allow_hyphen_values(true)\n \
262 .value_parser(value_parser!(OsString))\n\
263 }}\n\n\
264 /// Routes argv to a command. Anything this parser rejects runs the original, so it never\n\
265 /// has to match every way the original accepts its arguments.\n\
266 pub fn command() -> Command {{\n \
267 Command::new(ROOT)\n \
268 .disable_help_flag(true)\n \
269 .disable_version_flag(true)\n"
270 );
271 if commands.is_empty() {
272 out += &arg_lines(flags.get(""), " ");
273 } else {
274 out += " .disable_help_subcommand(true)\n .args_conflicts_with_subcommands(true)\n .arg(rest())\n";
275 for command in commands {
276 out += &format!(
277 " .subcommand(\n Command::new({command:?})\n .disable_help_flag(true)\n"
278 );
279 out += &arg_lines(flags.get(command), " ");
280 out += " )\n";
281 }
282 }
283 out.truncate(out.trim_end().len());
284 out += "\n}\n";
285 out
286}
287
288pub(crate) const MAIN_RS: &str = "mod cli;
289mod original;
290mod units;
291
292use std::ffi::OsString;
293use std::process::ExitCode;
294
295fn main() -> ExitCode {
296 original::report_fallbacks();
297 let argv: Vec<OsString> = std::env::args_os().collect();
298 if let Ok(matches) = cli::command().try_get_matches_from(&argv) {
299 let (command, sub) = matches.subcommand().unwrap_or((cli::ROOT, &matches));
300 if let Some(code) = units::dispatch(command, sub) {
301 return code;
302 }
303 }
304 original::run(&argv[1..])
305}
306";
307
308fn original_rs(run: &[String]) -> String {
309 let words: Vec<String> = run.iter().map(|w| format!("{w:?}")).collect();
310 format!(
311 "use std::ffi::OsString;
312use std::io::Write;
313use std::path::Path;
314use std::process::{{Command, ExitCode, ExitStatus}};
315
316const ROOT: &str = concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/../..\");
317const RUN: &[&str] = &[{}];
318const FALLBACK_LOG: &str = \"{}\";
319
320fn resolve(word: &str) -> OsString {{
321 if word.starts_with('-') {{
322 return word.into();
323 }}
324 let path = Path::new(ROOT).join(word);
325 let looks_like_path = word.contains('/') || word.contains('\\\\') || path.is_file();
326 if looks_like_path && path.exists() {{
327 return std::path::absolute(&path).unwrap_or(path).into_os_string();
328 }}
329 word.into()
330}}
331
332fn log() -> Option<std::fs::File> {{
333 let path = std::env::var_os(FALLBACK_LOG)?;
334 std::fs::OpenOptions::new()
335 .create(true)
336 .append(true)
337 .open(path)
338 .ok()
339}}
340
341/// Tells `rust-anything app replay` this build counts its fallbacks, even when it makes none.
342pub fn report_fallbacks() {{
343 let _ = log();
344}}
345
346/// Runs the original with the same arguments, stdin and environment, and passes its output and
347/// exit code through. Each call is one fallback.
348pub fn run(args: &[OsString]) -> ExitCode {{
349 if let Some(mut file) = log() {{
350 let line: Vec<String> = args
351 .iter()
352 .map(|a| a.to_string_lossy().into_owned())
353 .collect();
354 let _ = writeln!(file, \"{{}}\", line.join(\" \"));
355 }}
356 let Some((program, rest)) = RUN.split_first() else {{
357 return ExitCode::from(127);
358 }};
359 let mut command = Command::new(resolve(program));
360 command.args(rest.iter().map(|w| resolve(w))).args(args);
361 #[cfg(windows)]
362 if Path::new(program)
363 .file_stem()
364 .and_then(|name| name.to_str())
365 .is_some_and(|name| [\"python\", \"python3\", \"py\"]
366 .iter()
367 .any(|candidate| name.eq_ignore_ascii_case(candidate)))
368 && std::env::var_os(\"PYTHONIOENCODING\").is_none()
369 {{
370 command.env(\"PYTHONIOENCODING\", \"utf-8\");
371 }}
372 let status = command.status();
373 match status {{
374 Ok(status) => ExitCode::from(exit_code(status)),
375 Err(e) => {{
376 eprintln!(\"front door: cannot run the original `{{}}`: {{e}}\", RUN.join(\" \"));
377 ExitCode::from(127)
378 }}
379 }}
380}}
381
382fn exit_code(status: ExitStatus) -> u8 {{
383 if let Some(code) = status.code() {{
384 return (code & 0xff) as u8;
385 }}
386 #[cfg(unix)]
387 {{
388 use std::os::unix::process::ExitStatusExt;
389 if let Some(signal) = status.signal() {{
390 return (128 + signal) as u8;
391 }}
392 }}
393 1
394}}
395",
396 words.join(", "),
397 app::FALLBACK_ENV
398 )
399}
400
401fn units_rs(state: &State) -> String {
402 let mut out = format!(
403 "//! Generated by `rust-anything app wire` from {STATE_FILE}; it is rewritten on every wire.\n\n\
404 use std::process::ExitCode;\n\n\
405 use clap::ArgMatches;\n\n"
406 );
407 if state.units.is_empty() {
408 out += "pub fn dispatch(_command: &str, _matches: &ArgMatches) -> Option<ExitCode> {\n None\n}\n";
409 return out;
410 }
411 for unit in &state.units {
412 out += &format!("mod {};\n", ident(&unit.name));
413 }
414 out += &format!(
415 "\n/// `{KILL_SWITCH_PREFIX}<NAME>=original` sends that unit back to the original.\n\
416 fn sent_to_original(unit: &str) -> bool {{\n \
417 std::env::var(format!(\"{KILL_SWITCH_PREFIX}{{unit}}\")).is_ok_and(|v| v == \"original\")\n\
418 }}\n\n\
419 pub fn dispatch(command: &str, matches: &ArgMatches) -> Option<ExitCode> {{\n \
420 match command {{\n"
421 );
422 for unit in &state.units {
423 let pattern: Vec<String> = unit.commands.iter().map(|c| format!("{c:?}")).collect();
424 let switch = unit
425 .switch
426 .strip_prefix(KILL_SWITCH_PREFIX)
427 .unwrap_or(&unit.switch);
428 out += &format!(
429 " {} if !sent_to_original({switch:?}) => Some({}::run(command, matches)),\n",
430 pattern.join(" | "),
431 ident(&unit.name)
432 );
433 }
434 out += " _ => None,\n }\n}\n";
435 out
436}
437
438fn glue_rs(crate_name: &str) -> String {
439 let krate = crate_name.replace('-', "_");
440 format!(
441 "//! Glue from the front door to `{crate_name}`: parse the arguments, call `{krate}::port`,\n\
442 //! print what the original prints and return its exit code.\n\n\
443 use std::ffi::OsString;\n\
444 use std::process::ExitCode;\n\n\
445 use clap::ArgMatches;\n\n\
446 pub fn run(command: &str, matches: &ArgMatches) -> ExitCode {{\n \
447 let args: Vec<&OsString> = matches\n \
448 .get_many::<OsString>(\"args\")\n \
449 .into_iter()\n \
450 .flatten()\n \
451 .collect();\n \
452 unimplemented!(\"glue for `{{command}}` {{args:?}}: call {krate}::port\")\n\
453 }}\n"
454 )
455}
456
457pub(crate) fn rustfmt(file: &Path) {
458 let _ = Command::new("rustfmt")
459 .args(["--edition", "2024"])
460 .arg(file)
461 .output();
462}
463
464pub(crate) fn cargo_build(app_dir: &Path, target_dir: Option<&Path>) -> Result<PathBuf> {
465 let mut cmd = Command::new("cargo");
466 cmd.args([
467 "build",
468 "--message-format=json-render-diagnostics",
469 "--manifest-path",
470 ])
471 .arg(app_dir.join("Cargo.toml"));
472 if let Some(dir) = target_dir {
473 cmd.env("CARGO_TARGET_DIR", dir);
474 }
475 let out = cmd.output().context("running cargo")?;
476 ensure!(
477 out.status.success(),
478 "cargo build in {} failed:\n{}",
479 app_dir.display(),
480 String::from_utf8_lossy(&out.stderr)
481 );
482 let mut exe = None;
483 for line in String::from_utf8_lossy(&out.stdout).lines() {
484 let Ok(msg) = serde_json::from_str::<serde_json::Value>(line) else {
485 continue;
486 };
487 let is_bin = msg["target"]["kind"]
488 .as_array()
489 .is_some_and(|k| k.iter().any(|v| v == "bin"));
490 if msg["reason"] == "compiler-artifact"
491 && is_bin
492 && let Some(path) = msg["executable"].as_str()
493 {
494 exe = Some(PathBuf::from(path));
495 }
496 }
497 exe.context("cargo built no binary")
498}
499
500fn build_and_replay(repo: &Path, state: &State) -> Result<ReplayOutcome> {
501 if state.kind == AppKind::Library {
502 crate::library::cargo_build_lib(&repo.join(APP_DIR), None)?;
503 return crate::library::replay(repo, state, None);
504 }
505 let exe = cargo_build(&repo.join(APP_DIR), None)?;
506 app::replay(&ReplayOptions {
507 case: None,
508 repo,
509 build: Some(&app::shell_quote(&exe.to_string_lossy())),
510 timeout_secs: None,
511 port: None,
512 })
513}
514
515pub struct FrontDoorOptions<'a> {
516 pub repo: &'a Path,
517 pub library: bool,
519 pub check: bool,
521}
522
523#[derive(Debug, Serialize)]
524pub struct FrontDoorOutcome {
525 pub dir: PathBuf,
526 pub binary: String,
527 pub commands: Vec<String>,
528 pub routes: Vec<String>,
530 pub api: Vec<crate::library::ApiUnit>,
532 pub flags: BTreeMap<String, BTreeMap<String, Flag>>,
533 pub files: Vec<String>,
534 pub replay: Option<ReplayOutcome>,
535}
536
537pub fn front_door(opts: &FrontDoorOptions) -> Result<FrontDoorOutcome> {
538 let repo = opts
539 .repo
540 .canonical()
541 .with_context(|| format!("no folder {}", opts.repo.display()))?;
542 let config = app::Config::load(&repo)?;
543 let config = match config {
544 Some(c) if !opts.library => c,
545 _ => {
546 let report = crate::analyze::analyze(&repo)?;
547 let shape = crate::whole_app::whole_app(&repo, &report).shape;
548 ensure!(
549 opts.library || shape == "library",
550 "no recorded cases in {}: run `rust-anything app record` first (or --library if this {shape} is used as a library)",
551 app::cases_dir(&repo).display()
552 );
553 return library_front_door(&repo, opts, &report);
554 }
555 };
556 let dir = repo.join(APP_DIR);
557 ensure!(
558 !dir.exists(),
559 "{} already exists; the front door is yours once scaffolded (remove it to scaffold again)",
560 dir.display()
561 );
562 let binary = package_name(&config.name);
563 if let Some(http) = &config.http {
564 ensure!(
565 http.port.is_none(),
566 "the front door starts the original on a port of its own: make the original take its port from PORT or `{{port}}` in its command, then record again without --port"
567 );
568 let routes = crate::http::recorded_routes(&repo)?;
569 let state = State {
570 schema: SCHEMA.to_string(),
571 name: config.name.clone(),
572 commands: Vec::new(),
573 units: Vec::new(),
574 lifted: false,
575 kind: AppKind::Http,
576 routes: routes.clone(),
577 api: Vec::new(),
578 };
579 let files: Vec<(&str, String)> = vec![
580 ("Cargo.toml", http_door::cargo_toml(&binary, &config.name)),
581 (".gitignore", "/target\n".to_string()),
582 ("src/main.rs", http_door::main_rs()),
583 ("src/original.rs", http_door::original_rs(&config.run)),
584 ("src/units/mod.rs", http_door::units_rs(&state, false)),
585 ];
586 return finish_front_door(
587 &repo,
588 opts,
589 state,
590 files,
591 binary,
592 Vec::new(),
593 BTreeMap::new(),
594 routes,
595 );
596 }
597 let (commands, flags) = infer_cli(&app::recorded_args(&repo)?);
598 let files: Vec<(&str, String)> = vec![
599 (
600 "Cargo.toml",
601 format!(
602 "[package]\nname = \"{binary}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\
603 description = \"Front door for `{}`, generated by rust-anything: Rust owns the entry point, the original answers what is not ported yet\"\n\n\
604 [[bin]]\nname = \"{binary}\"\npath = \"src/main.rs\"\n\n\
605 [dependencies]\nclap = \"4\"\n\n\
606 [workspace]\n",
607 config.name
608 ),
609 ),
610 (".gitignore", "/target\n".to_string()),
611 ("src/main.rs", MAIN_RS.to_string()),
612 ("src/cli.rs", cli_rs(&config.name, &commands, &flags)),
613 ("src/original.rs", original_rs(&config.run)),
614 ];
615 let state = State {
616 schema: SCHEMA.to_string(),
617 name: config.name.clone(),
618 commands: commands.clone(),
619 units: Vec::new(),
620 lifted: false,
621 kind: AppKind::Cli,
622 routes: Vec::new(),
623 api: Vec::new(),
624 };
625 let mut files = files;
626 files.push(("src/units/mod.rs", units_rs(&state)));
627 finish_front_door(
628 &repo,
629 opts,
630 state,
631 files,
632 binary,
633 commands,
634 flags,
635 Vec::new(),
636 )
637}
638
639#[allow(clippy::too_many_arguments)]
640fn finish_front_door(
641 repo: &Path,
642 opts: &FrontDoorOptions,
643 state: State,
644 files: Vec<(&str, String)>,
645 binary: String,
646 commands: Vec<String>,
647 flags: BTreeMap<String, BTreeMap<String, Flag>>,
648 routes: Vec<String>,
649) -> Result<FrontDoorOutcome> {
650 let repo = repo.to_path_buf();
651 let dir = repo.join(APP_DIR);
652 let state_api = state.api.clone();
653 for (path, text) in &files {
654 let target = dir.join(path);
655 if let Some(parent) = target.parent() {
656 std::fs::create_dir_all(parent)?;
657 }
658 std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
659 }
660 if state.kind == AppKind::Library {
661 rustfmt(&dir.join("src/lib.rs"));
662 } else {
663 rustfmt(&dir.join("src/main.rs"));
664 }
665 state.save(&repo)?;
666 let replay = if opts.check {
667 Some(build_and_replay(&repo, &state)?)
668 } else {
669 None
670 };
671 let mut written: Vec<String> = files.iter().map(|(p, _)| p.to_string()).collect();
672 written.push(STATE_FILE.to_string());
673 Ok(FrontDoorOutcome {
674 dir,
675 binary,
676 commands,
677 routes,
678 api: state_api,
679 flags,
680 files: written,
681 replay,
682 })
683}
684
685fn library_front_door(
686 repo: &Path,
687 opts: &FrontDoorOptions,
688 report: &crate::analyze::Report,
689) -> Result<FrontDoorOutcome> {
690 let name = report
691 .packages
692 .first()
693 .map(|p| p.name.clone())
694 .filter(|n| !n.is_empty())
695 .or_else(|| repo.file_name().map(|n| n.to_string_lossy().into_owned()))
696 .unwrap_or_else(|| "lib".to_string());
697 let package = package_name(&name);
698 let state = State {
699 schema: SCHEMA.to_string(),
700 name: name.clone(),
701 commands: Vec::new(),
702 units: Vec::new(),
703 lifted: false,
704 kind: AppKind::Library,
705 routes: Vec::new(),
706 api: crate::library::public_api(repo, report),
707 };
708 ensure!(
709 !state.api.is_empty(),
710 "no exported function or class found to make a public API from"
711 );
712 let files: Vec<(&str, String)> = vec![
713 ("Cargo.toml", crate::library::cargo_toml(&package, &name)),
714 (".gitignore", "/target\n".to_string()),
715 ("src/lib.rs", crate::library::lib_rs(&state, false)),
716 ];
717 finish_front_door(
718 repo,
719 opts,
720 state,
721 files,
722 package,
723 Vec::new(),
724 BTreeMap::new(),
725 Vec::new(),
726 )
727}
728
729#[allow(clippy::too_many_arguments)]
730fn library_wire(
731 repo: &Path,
732 opts: &WireOptions,
733 mut state: State,
734 crate_dir: &Path,
735 crate_name: String,
736 name: String,
737 switch: String,
738 gate: Option<bool>,
739) -> Result<WireOutcome> {
740 ensure!(
741 opts.commands.is_empty() && opts.routes.is_empty(),
742 "{} is a library: a unit answers its own exports, so wire takes no --command or --route",
743 state.name
744 );
745 let manifest = crate::bridge::Manifest::load(crate_dir).with_context(|| {
746 format!(
747 "a library unit is a crate made by `bridge` (the original package calls it through its bindings), and {} has no manifest",
748 crate_dir.display()
749 )
750 })?;
751 let api = crate::library::api_unit(&state, &manifest.unit)?.clone();
752 let app_dir = repo.join(APP_DIR);
753 let previous = state.units.iter().position(|u| u.name == name);
754 let shadow = crate::library::shadow_for(
755 crate_dir,
756 previous.and_then(|i| state.units[i].shadow.as_deref()),
757 )?;
758 let path = match crate_dir.strip_prefix(repo.join("rust")) {
759 Ok(rel) => format!("../{}", rel.to_string_lossy().replace('\\', "/")),
760 Err(_) => crate_dir.to_string_lossy().into_owned(),
761 };
762 let entry = WiredUnit {
763 name: name.clone(),
764 crate_name: crate_name.clone(),
765 path: path.clone(),
766 commands: Vec::new(),
767 routes: Vec::new(),
768 switch: switch.clone(),
769 unit: Some(api.unit.clone()),
770 shadow: shadow.as_ref().map(|p| p.to_string_lossy().into_owned()),
771 kept: manifest.js_only.iter().map(|j| j.name.clone()).collect(),
772 };
773 match previous {
774 Some(i) => state.units[i] = entry,
775 None => state.units.push(entry),
776 }
777 let cargo_path = app_dir.join("Cargo.toml");
778 let mut doc: DocumentMut = std::fs::read_to_string(&cargo_path)?.parse()?;
779 let mut dep = InlineTable::new();
780 dep.insert("path", path.as_str().into());
781 doc["dependencies"][crate_name.as_str()] = value(dep);
782 std::fs::write(&cargo_path, doc.to_string())?;
783 if manifest.kind == crate::bridge::Kind::Pyo3 {
784 crate::library::allow_python_symbols(&app_dir)?;
785 }
786 let lib = app_dir.join("src/lib.rs");
787 std::fs::write(&lib, crate::library::lib_rs(&state, false))?;
788 rustfmt(&lib);
789 state.save(repo)?;
790 let replay = if opts.check {
791 Some(build_and_replay(repo, &state)?)
792 } else {
793 None
794 };
795 Ok(WireOutcome {
796 shadow,
797 unit: name,
798 crate_dir: crate_dir.to_path_buf(),
799 commands: Vec::new(),
800 routes: Vec::new(),
801 switch,
802 glue: lib,
803 glue_pending: false,
804 gate,
805 replay,
806 })
807}
808
809fn find_unit(repo: &Path, unit: &str) -> Result<PathBuf> {
810 let rust = repo.join("rust");
811 for candidate in [
812 rust.join(unit),
813 rust.join(format!("{unit}-rs")),
814 repo.join(unit),
815 PathBuf::from(unit),
816 ] {
817 if candidate.join("Cargo.toml").is_file() && candidate != repo.join(APP_DIR) {
818 return Ok(candidate.canonical()?);
819 }
820 }
821 let wanted = unit.trim_end_matches('/');
822 if let Ok(entries) = std::fs::read_dir(&rust) {
823 for entry in entries.flatten() {
824 if let Ok(m) = crate::bridge::Manifest::load(&entry.path())
825 && m.unit.trim_end_matches('/') == wanted
826 {
827 return Ok(entry.path().canonical()?);
828 }
829 }
830 }
831 bail!(
832 "no unit crate `{unit}`: give the crate folder (`rust/<name>`, as `bridge` made it) or the unit id"
833 )
834}
835
836pub struct WireOptions<'a> {
837 pub repo: &'a Path,
838 pub unit: &'a str,
840 pub commands: &'a [String],
842 pub routes: &'a [String],
845 pub skip_gate: bool,
847 pub check: bool,
848}
849
850#[derive(Debug, Serialize)]
851pub struct WireOutcome {
852 pub shadow: Option<PathBuf>,
854 pub unit: String,
855 pub crate_dir: PathBuf,
856 pub commands: Vec<String>,
857 pub routes: Vec<String>,
858 pub switch: String,
859 pub glue: PathBuf,
860 pub glue_pending: bool,
862 pub gate: Option<bool>,
863 pub replay: Option<ReplayOutcome>,
864}
865
866pub fn wire(opts: &WireOptions) -> Result<WireOutcome> {
867 let repo = opts
868 .repo
869 .canonical()
870 .with_context(|| format!("no folder {}", opts.repo.display()))?;
871 let mut state = State::load(&repo)?;
872 ensure!(
873 !state.lifted,
874 "the app is lifted: there is no fallback left to wire around; call the crate from src/units directly"
875 );
876 let app_dir = repo.join(APP_DIR);
877 let crate_dir = find_unit(&repo, opts.unit)?;
878 let manifest_text = std::fs::read_to_string(crate_dir.join("Cargo.toml"))?;
879 let unit_doc: DocumentMut = manifest_text.parse()?;
880 let crate_name = unit_doc
881 .get("package")
882 .and_then(|p| p.get("name"))
883 .and_then(|n| n.as_str())
884 .context("the unit's Cargo.toml has no package name")?
885 .to_string();
886 if let Some(kinds) = unit_doc
887 .get("lib")
888 .and_then(|l| l.get("crate-type"))
889 .and_then(|k| k.as_array())
890 {
891 ensure!(
892 kinds.iter().any(|k| k.as_str() == Some("rlib")),
893 "{crate_name} is not a Rust library: add \"rlib\" to `crate-type` in its Cargo.toml"
894 );
895 }
896 let name = crate_name
897 .strip_suffix("-rs")
898 .unwrap_or(&crate_name)
899 .to_string();
900 let switch = kill_switch(&crate_name);
901
902 let gate = if opts.skip_gate {
903 None
904 } else {
905 let outcome = crate::gate::gate(&crate_dir, &[])?;
906 if !outcome.passed {
907 let failed: Vec<String> = outcome
908 .checks
909 .iter()
910 .filter(|c| !c.passed)
911 .map(|c| c.name.to_string())
912 .collect();
913 bail!(
914 "{crate_name} does not pass gate ({}): run `rust-anything gate {}` and fix it before wiring",
915 failed.join(", "),
916 crate_dir.display()
917 );
918 }
919 Some(true)
920 };
921 if state.kind == AppKind::Library {
922 return library_wire(
923 &repo, opts, state, &crate_dir, crate_name, name, switch, gate,
924 );
925 }
926
927 let previous = state.units.iter().position(|u| u.name == name);
928 let http = state.kind == AppKind::Http;
929 ensure!(
930 !http || opts.commands.is_empty(),
931 "{} is a server: name what {name} answers with --route, not --command",
932 state.name
933 );
934 ensure!(
935 http || opts.routes.is_empty(),
936 "{} is a CLI: name what {name} answers with --command, not --route",
937 state.name
938 );
939 let routes = if !http {
940 Vec::new()
941 } else if opts.routes.is_empty() {
942 previous
943 .map(|i| state.units[i].routes.clone())
944 .filter(|r| !r.is_empty())
945 .with_context(|| format!("name the routes {name} answers with --route"))?
946 } else {
947 http_door::check_routes(&state, &name, opts.routes)?
948 .iter()
949 .map(http_door::Route::key)
950 .collect()
951 };
952 let commands = if http {
953 Vec::new()
954 } else if opts.commands.is_empty() {
955 previous
956 .map(|i| state.units[i].commands.clone())
957 .with_context(|| format!("name the commands {name} answers with --command"))?
958 } else {
959 opts.commands.to_vec()
960 };
961 let routable: Vec<&str> = state
962 .commands
963 .iter()
964 .map(String::as_str)
965 .chain([state.name.as_str()])
966 .collect();
967 for command in commands.iter().filter(|_| !http) {
968 ensure!(
969 routable.contains(&command.as_str()),
970 "the front door has no command `{command}` (it has: {}); add it to src/cli.rs and to `commands` in {}",
971 routable.join(", "),
972 app_dir.join(STATE_FILE).display()
973 );
974 if let Some(other) = state
975 .units
976 .iter()
977 .find(|u| u.name != name && u.commands.contains(command))
978 {
979 bail!("`{command}` is already wired to {}", other.name);
980 }
981 }
982 let path = match crate_dir.strip_prefix(repo.join("rust")) {
983 Ok(rel) => format!("../{}", rel.to_string_lossy().replace('\\', "/")),
984 Err(_) => crate_dir.to_string_lossy().into_owned(),
985 };
986 let entry = WiredUnit {
987 name: name.clone(),
988 crate_name: crate_name.clone(),
989 path: path.clone(),
990 commands: commands.clone(),
991 routes: routes.clone(),
992 switch: switch.clone(),
993 unit: None,
994 shadow: None,
995 kept: Vec::new(),
996 };
997 match previous {
998 Some(i) => state.units[i] = entry,
999 None => state.units.push(entry),
1000 }
1001
1002 let cargo_path = app_dir.join("Cargo.toml");
1003 let mut doc: DocumentMut = std::fs::read_to_string(&cargo_path)?.parse()?;
1004 let mut dep = InlineTable::new();
1005 dep.insert("path", path.as_str().into());
1006 doc["dependencies"][crate_name.as_str()] = value(dep);
1007 std::fs::write(&cargo_path, doc.to_string())?;
1008
1009 let glue = app_dir
1010 .join("src/units")
1011 .join(format!("{}.rs", ident(&name)));
1012 if !glue.exists() {
1013 let stub = if http {
1014 http_door::glue_rs(&crate_name)
1015 } else {
1016 glue_rs(&crate_name)
1017 };
1018 std::fs::write(&glue, stub)?;
1019 }
1020 let units = if http {
1021 http_door::units_rs(&state, false)
1022 } else {
1023 units_rs(&state)
1024 };
1025 std::fs::write(app_dir.join("src/units/mod.rs"), units)?;
1026 rustfmt(&app_dir.join("src/units/mod.rs"));
1027 state.save(&repo)?;
1028 let glue_pending = is_stub(&std::fs::read_to_string(&glue)?);
1029 let replay = if opts.check {
1030 Some(build_and_replay(&repo, &state)?)
1031 } else {
1032 None
1033 };
1034 Ok(WireOutcome {
1035 shadow: None,
1036 unit: name,
1037 crate_dir,
1038 commands,
1039 routes,
1040 switch,
1041 glue,
1042 glue_pending,
1043 gate,
1044 replay,
1045 })
1046}
1047
1048#[cfg(test)]
1049mod tests {
1050 use super::*;
1051
1052 fn case(args: &[&str], ok: bool) -> (Vec<String>, bool) {
1053 (args.iter().map(|a| a.to_string()).collect(), ok)
1054 }
1055
1056 #[test]
1057 fn commands_and_flags_come_from_successful_cases() {
1058 let (commands, flags) = infer_cli(&[
1059 case(&["div", "7", "2"], true),
1060 case(&["show", "--json", "-v", "x"], true),
1061 case(&["show", "--width=3"], true),
1062 case(&["nope"], false),
1063 case(&["--help"], true),
1064 ]);
1065 assert_eq!(commands, ["div", "show"]);
1066 let show = &flags["show"];
1067 assert!(!show["json"].takes_value);
1068 assert!(show["width"].takes_value);
1069 assert_eq!(show["short-v"].short, Some('v'));
1070 assert!(!flags.contains_key("div") || flags["div"].is_empty());
1071 let (none, root) = infer_cli(&[case(&["-n", "5", "file.txt"], true)]);
1072 assert!(none.is_empty());
1073 assert!(root[""].contains_key("short-n"));
1074 }
1075
1076 #[test]
1077 fn names_are_valid_rust() {
1078 assert_eq!(package_name("My Tool"), "my-tool");
1079 assert_eq!(package_name("7zip"), "app-7zip");
1080 assert_eq!(ident("text-kit"), "text_kit");
1081 assert_eq!(ident("mod"), "unit_mod");
1082 }
1083
1084 #[test]
1085 fn generated_fallback_matches_python_stems_case_insensitively() {
1086 let code = original_rs(&["Python.EXE".to_string()]);
1087 assert!(
1088 code.contains(".any(|candidate| name.eq_ignore_ascii_case(candidate))"),
1089 "{code}"
1090 );
1091 assert!(
1092 code.contains("var_os(\"PYTHONIOENCODING\").is_none()"),
1093 "{code}"
1094 );
1095 }
1096
1097 #[test]
1098 fn units_route_commands_behind_kill_switches() {
1099 let mut state = State {
1100 schema: SCHEMA.to_string(),
1101 name: "tcli".to_string(),
1102 commands: vec!["div".into(), "words".into()],
1103 units: Vec::new(),
1104 lifted: false,
1105 kind: AppKind::Cli,
1106 routes: Vec::new(),
1107 api: Vec::new(),
1108 };
1109 assert!(units_rs(&state).contains("None"));
1110 state.units.push(WiredUnit {
1111 name: "wordcount".into(),
1112 crate_name: "wordcount-rs".into(),
1113 path: "../wordcount-rs".into(),
1114 commands: vec!["words".into()],
1115 routes: Vec::new(),
1116 switch: "RUST_ANYTHING_UNIT_WORDCOUNT".into(),
1117 unit: None,
1118 shadow: None,
1119 kept: Vec::new(),
1120 });
1121 let code = units_rs(&state);
1122 assert!(code.contains("mod wordcount;"), "{code}");
1123 assert!(
1124 code.contains(
1125 "\"words\" if !sent_to_original(\"WORDCOUNT\") => Some(wordcount::run(command, matches)),"
1126 ),
1127 "{code}"
1128 );
1129 }
1130}