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 status = Command::new(resolve(program))
360 .args(rest.iter().map(|w| resolve(w)))
361 .args(args)
362 .status();
363 match status {{
364 Ok(status) => ExitCode::from(exit_code(status)),
365 Err(e) => {{
366 eprintln!(\"front door: cannot run the original `{{}}`: {{e}}\", RUN.join(\" \"));
367 ExitCode::from(127)
368 }}
369 }}
370}}
371
372fn exit_code(status: ExitStatus) -> u8 {{
373 if let Some(code) = status.code() {{
374 return (code & 0xff) as u8;
375 }}
376 #[cfg(unix)]
377 {{
378 use std::os::unix::process::ExitStatusExt;
379 if let Some(signal) = status.signal() {{
380 return (128 + signal) as u8;
381 }}
382 }}
383 1
384}}
385",
386 words.join(", "),
387 app::FALLBACK_ENV
388 )
389}
390
391fn units_rs(state: &State) -> String {
392 let mut out = format!(
393 "//! Generated by `rust-anything app wire` from {STATE_FILE}; it is rewritten on every wire.\n\n\
394 use std::process::ExitCode;\n\n\
395 use clap::ArgMatches;\n\n"
396 );
397 if state.units.is_empty() {
398 out += "pub fn dispatch(_command: &str, _matches: &ArgMatches) -> Option<ExitCode> {\n None\n}\n";
399 return out;
400 }
401 for unit in &state.units {
402 out += &format!("mod {};\n", ident(&unit.name));
403 }
404 out += &format!(
405 "\n/// `{KILL_SWITCH_PREFIX}<NAME>=original` sends that unit back to the original.\n\
406 fn sent_to_original(unit: &str) -> bool {{\n \
407 std::env::var(format!(\"{KILL_SWITCH_PREFIX}{{unit}}\")).is_ok_and(|v| v == \"original\")\n\
408 }}\n\n\
409 pub fn dispatch(command: &str, matches: &ArgMatches) -> Option<ExitCode> {{\n \
410 match command {{\n"
411 );
412 for unit in &state.units {
413 let pattern: Vec<String> = unit.commands.iter().map(|c| format!("{c:?}")).collect();
414 let switch = unit
415 .switch
416 .strip_prefix(KILL_SWITCH_PREFIX)
417 .unwrap_or(&unit.switch);
418 out += &format!(
419 " {} if !sent_to_original({switch:?}) => Some({}::run(command, matches)),\n",
420 pattern.join(" | "),
421 ident(&unit.name)
422 );
423 }
424 out += " _ => None,\n }\n}\n";
425 out
426}
427
428fn glue_rs(crate_name: &str) -> String {
429 let krate = crate_name.replace('-', "_");
430 format!(
431 "//! Glue from the front door to `{crate_name}`: parse the arguments, call `{krate}::port`,\n\
432 //! print what the original prints and return its exit code.\n\n\
433 use std::ffi::OsString;\n\
434 use std::process::ExitCode;\n\n\
435 use clap::ArgMatches;\n\n\
436 pub fn run(command: &str, matches: &ArgMatches) -> ExitCode {{\n \
437 let args: Vec<&OsString> = matches\n \
438 .get_many::<OsString>(\"args\")\n \
439 .into_iter()\n \
440 .flatten()\n \
441 .collect();\n \
442 unimplemented!(\"glue for `{{command}}` {{args:?}}: call {krate}::port\")\n\
443 }}\n"
444 )
445}
446
447pub(crate) fn rustfmt(file: &Path) {
448 let _ = Command::new("rustfmt")
449 .args(["--edition", "2024"])
450 .arg(file)
451 .output();
452}
453
454pub(crate) fn cargo_build(app_dir: &Path, target_dir: Option<&Path>) -> Result<PathBuf> {
455 let mut cmd = Command::new("cargo");
456 cmd.args([
457 "build",
458 "--message-format=json-render-diagnostics",
459 "--manifest-path",
460 ])
461 .arg(app_dir.join("Cargo.toml"));
462 if let Some(dir) = target_dir {
463 cmd.env("CARGO_TARGET_DIR", dir);
464 }
465 let out = cmd.output().context("running cargo")?;
466 ensure!(
467 out.status.success(),
468 "cargo build in {} failed:\n{}",
469 app_dir.display(),
470 String::from_utf8_lossy(&out.stderr)
471 );
472 let mut exe = None;
473 for line in String::from_utf8_lossy(&out.stdout).lines() {
474 let Ok(msg) = serde_json::from_str::<serde_json::Value>(line) else {
475 continue;
476 };
477 let is_bin = msg["target"]["kind"]
478 .as_array()
479 .is_some_and(|k| k.iter().any(|v| v == "bin"));
480 if msg["reason"] == "compiler-artifact"
481 && is_bin
482 && let Some(path) = msg["executable"].as_str()
483 {
484 exe = Some(PathBuf::from(path));
485 }
486 }
487 exe.context("cargo built no binary")
488}
489
490fn build_and_replay(repo: &Path, state: &State) -> Result<ReplayOutcome> {
491 if state.kind == AppKind::Library {
492 crate::library::cargo_build_lib(&repo.join(APP_DIR), None)?;
493 return crate::library::replay(repo, state, None);
494 }
495 let exe = cargo_build(&repo.join(APP_DIR), None)?;
496 app::replay(&ReplayOptions {
497 case: None,
498 repo,
499 build: Some(&app::shell_quote(&exe.to_string_lossy())),
500 timeout_secs: None,
501 port: None,
502 })
503}
504
505pub struct FrontDoorOptions<'a> {
506 pub repo: &'a Path,
507 pub library: bool,
509 pub check: bool,
511}
512
513#[derive(Debug, Serialize)]
514pub struct FrontDoorOutcome {
515 pub dir: PathBuf,
516 pub binary: String,
517 pub commands: Vec<String>,
518 pub routes: Vec<String>,
520 pub api: Vec<crate::library::ApiUnit>,
522 pub flags: BTreeMap<String, BTreeMap<String, Flag>>,
523 pub files: Vec<String>,
524 pub replay: Option<ReplayOutcome>,
525}
526
527pub fn front_door(opts: &FrontDoorOptions) -> Result<FrontDoorOutcome> {
528 let repo = opts
529 .repo
530 .canonical()
531 .with_context(|| format!("no folder {}", opts.repo.display()))?;
532 let config = app::Config::load(&repo)?;
533 let config = match config {
534 Some(c) if !opts.library => c,
535 _ => {
536 let report = crate::analyze::analyze(&repo)?;
537 let shape = crate::whole_app::whole_app(&repo, &report).shape;
538 ensure!(
539 opts.library || shape == "library",
540 "no recorded cases in {}: run `rust-anything app record` first (or --library if this {shape} is used as a library)",
541 app::cases_dir(&repo).display()
542 );
543 return library_front_door(&repo, opts, &report);
544 }
545 };
546 let dir = repo.join(APP_DIR);
547 ensure!(
548 !dir.exists(),
549 "{} already exists; the front door is yours once scaffolded (remove it to scaffold again)",
550 dir.display()
551 );
552 let binary = package_name(&config.name);
553 if let Some(http) = &config.http {
554 ensure!(
555 http.port.is_none(),
556 "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"
557 );
558 let routes = crate::http::recorded_routes(&repo)?;
559 let state = State {
560 schema: SCHEMA.to_string(),
561 name: config.name.clone(),
562 commands: Vec::new(),
563 units: Vec::new(),
564 lifted: false,
565 kind: AppKind::Http,
566 routes: routes.clone(),
567 api: Vec::new(),
568 };
569 let files: Vec<(&str, String)> = vec![
570 ("Cargo.toml", http_door::cargo_toml(&binary, &config.name)),
571 (".gitignore", "/target\n".to_string()),
572 ("src/main.rs", http_door::main_rs()),
573 ("src/original.rs", http_door::original_rs(&config.run)),
574 ("src/units/mod.rs", http_door::units_rs(&state, false)),
575 ];
576 return finish_front_door(
577 &repo,
578 opts,
579 state,
580 files,
581 binary,
582 Vec::new(),
583 BTreeMap::new(),
584 routes,
585 );
586 }
587 let (commands, flags) = infer_cli(&app::recorded_args(&repo)?);
588 let files: Vec<(&str, String)> = vec![
589 (
590 "Cargo.toml",
591 format!(
592 "[package]\nname = \"{binary}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\
593 description = \"Front door for `{}`, generated by rust-anything: Rust owns the entry point, the original answers what is not ported yet\"\n\n\
594 [[bin]]\nname = \"{binary}\"\npath = \"src/main.rs\"\n\n\
595 [dependencies]\nclap = \"4\"\n\n\
596 [workspace]\n",
597 config.name
598 ),
599 ),
600 (".gitignore", "/target\n".to_string()),
601 ("src/main.rs", MAIN_RS.to_string()),
602 ("src/cli.rs", cli_rs(&config.name, &commands, &flags)),
603 ("src/original.rs", original_rs(&config.run)),
604 ];
605 let state = State {
606 schema: SCHEMA.to_string(),
607 name: config.name.clone(),
608 commands: commands.clone(),
609 units: Vec::new(),
610 lifted: false,
611 kind: AppKind::Cli,
612 routes: Vec::new(),
613 api: Vec::new(),
614 };
615 let mut files = files;
616 files.push(("src/units/mod.rs", units_rs(&state)));
617 finish_front_door(
618 &repo,
619 opts,
620 state,
621 files,
622 binary,
623 commands,
624 flags,
625 Vec::new(),
626 )
627}
628
629#[allow(clippy::too_many_arguments)]
630fn finish_front_door(
631 repo: &Path,
632 opts: &FrontDoorOptions,
633 state: State,
634 files: Vec<(&str, String)>,
635 binary: String,
636 commands: Vec<String>,
637 flags: BTreeMap<String, BTreeMap<String, Flag>>,
638 routes: Vec<String>,
639) -> Result<FrontDoorOutcome> {
640 let repo = repo.to_path_buf();
641 let dir = repo.join(APP_DIR);
642 let state_api = state.api.clone();
643 for (path, text) in &files {
644 let target = dir.join(path);
645 if let Some(parent) = target.parent() {
646 std::fs::create_dir_all(parent)?;
647 }
648 std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
649 }
650 if state.kind == AppKind::Library {
651 rustfmt(&dir.join("src/lib.rs"));
652 } else {
653 rustfmt(&dir.join("src/main.rs"));
654 }
655 state.save(&repo)?;
656 let replay = if opts.check {
657 Some(build_and_replay(&repo, &state)?)
658 } else {
659 None
660 };
661 let mut written: Vec<String> = files.iter().map(|(p, _)| p.to_string()).collect();
662 written.push(STATE_FILE.to_string());
663 Ok(FrontDoorOutcome {
664 dir,
665 binary,
666 commands,
667 routes,
668 api: state_api,
669 flags,
670 files: written,
671 replay,
672 })
673}
674
675fn library_front_door(
676 repo: &Path,
677 opts: &FrontDoorOptions,
678 report: &crate::analyze::Report,
679) -> Result<FrontDoorOutcome> {
680 let name = report
681 .packages
682 .first()
683 .map(|p| p.name.clone())
684 .filter(|n| !n.is_empty())
685 .or_else(|| repo.file_name().map(|n| n.to_string_lossy().into_owned()))
686 .unwrap_or_else(|| "lib".to_string());
687 let package = package_name(&name);
688 let state = State {
689 schema: SCHEMA.to_string(),
690 name: name.clone(),
691 commands: Vec::new(),
692 units: Vec::new(),
693 lifted: false,
694 kind: AppKind::Library,
695 routes: Vec::new(),
696 api: crate::library::public_api(repo, report),
697 };
698 ensure!(
699 !state.api.is_empty(),
700 "no exported function or class found to make a public API from"
701 );
702 let files: Vec<(&str, String)> = vec![
703 ("Cargo.toml", crate::library::cargo_toml(&package, &name)),
704 (".gitignore", "/target\n".to_string()),
705 ("src/lib.rs", crate::library::lib_rs(&state, false)),
706 ];
707 finish_front_door(
708 repo,
709 opts,
710 state,
711 files,
712 package,
713 Vec::new(),
714 BTreeMap::new(),
715 Vec::new(),
716 )
717}
718
719#[allow(clippy::too_many_arguments)]
720fn library_wire(
721 repo: &Path,
722 opts: &WireOptions,
723 mut state: State,
724 crate_dir: &Path,
725 crate_name: String,
726 name: String,
727 switch: String,
728 gate: Option<bool>,
729) -> Result<WireOutcome> {
730 ensure!(
731 opts.commands.is_empty() && opts.routes.is_empty(),
732 "{} is a library: a unit answers its own exports, so wire takes no --command or --route",
733 state.name
734 );
735 let manifest = crate::bridge::Manifest::load(crate_dir).with_context(|| {
736 format!(
737 "a library unit is a crate made by `bridge` (the original package calls it through its bindings), and {} has no manifest",
738 crate_dir.display()
739 )
740 })?;
741 let api = crate::library::api_unit(&state, &manifest.unit)?.clone();
742 let app_dir = repo.join(APP_DIR);
743 let previous = state.units.iter().position(|u| u.name == name);
744 let shadow = crate::library::shadow_for(
745 crate_dir,
746 previous.and_then(|i| state.units[i].shadow.as_deref()),
747 )?;
748 let path = match crate_dir.strip_prefix(repo.join("rust")) {
749 Ok(rel) => format!("../{}", rel.to_string_lossy().replace('\\', "/")),
750 Err(_) => crate_dir.to_string_lossy().into_owned(),
751 };
752 let entry = WiredUnit {
753 name: name.clone(),
754 crate_name: crate_name.clone(),
755 path: path.clone(),
756 commands: Vec::new(),
757 routes: Vec::new(),
758 switch: switch.clone(),
759 unit: Some(api.unit.clone()),
760 shadow: shadow.as_ref().map(|p| p.to_string_lossy().into_owned()),
761 kept: manifest.js_only.iter().map(|j| j.name.clone()).collect(),
762 };
763 match previous {
764 Some(i) => state.units[i] = entry,
765 None => state.units.push(entry),
766 }
767 let cargo_path = app_dir.join("Cargo.toml");
768 let mut doc: DocumentMut = std::fs::read_to_string(&cargo_path)?.parse()?;
769 let mut dep = InlineTable::new();
770 dep.insert("path", path.as_str().into());
771 doc["dependencies"][crate_name.as_str()] = value(dep);
772 std::fs::write(&cargo_path, doc.to_string())?;
773 if manifest.kind == crate::bridge::Kind::Pyo3 {
774 crate::library::allow_python_symbols(&app_dir)?;
775 }
776 let lib = app_dir.join("src/lib.rs");
777 std::fs::write(&lib, crate::library::lib_rs(&state, false))?;
778 rustfmt(&lib);
779 state.save(repo)?;
780 let replay = if opts.check {
781 Some(build_and_replay(repo, &state)?)
782 } else {
783 None
784 };
785 Ok(WireOutcome {
786 shadow,
787 unit: name,
788 crate_dir: crate_dir.to_path_buf(),
789 commands: Vec::new(),
790 routes: Vec::new(),
791 switch,
792 glue: lib,
793 glue_pending: false,
794 gate,
795 replay,
796 })
797}
798
799fn find_unit(repo: &Path, unit: &str) -> Result<PathBuf> {
800 let rust = repo.join("rust");
801 for candidate in [
802 rust.join(unit),
803 rust.join(format!("{unit}-rs")),
804 repo.join(unit),
805 PathBuf::from(unit),
806 ] {
807 if candidate.join("Cargo.toml").is_file() && candidate != repo.join(APP_DIR) {
808 return Ok(candidate.canonical()?);
809 }
810 }
811 let wanted = unit.trim_end_matches('/');
812 if let Ok(entries) = std::fs::read_dir(&rust) {
813 for entry in entries.flatten() {
814 if let Ok(m) = crate::bridge::Manifest::load(&entry.path())
815 && m.unit.trim_end_matches('/') == wanted
816 {
817 return Ok(entry.path().canonical()?);
818 }
819 }
820 }
821 bail!(
822 "no unit crate `{unit}`: give the crate folder (`rust/<name>`, as `bridge` made it) or the unit id"
823 )
824}
825
826pub struct WireOptions<'a> {
827 pub repo: &'a Path,
828 pub unit: &'a str,
830 pub commands: &'a [String],
832 pub routes: &'a [String],
835 pub skip_gate: bool,
837 pub check: bool,
838}
839
840#[derive(Debug, Serialize)]
841pub struct WireOutcome {
842 pub shadow: Option<PathBuf>,
844 pub unit: String,
845 pub crate_dir: PathBuf,
846 pub commands: Vec<String>,
847 pub routes: Vec<String>,
848 pub switch: String,
849 pub glue: PathBuf,
850 pub glue_pending: bool,
852 pub gate: Option<bool>,
853 pub replay: Option<ReplayOutcome>,
854}
855
856pub fn wire(opts: &WireOptions) -> Result<WireOutcome> {
857 let repo = opts
858 .repo
859 .canonical()
860 .with_context(|| format!("no folder {}", opts.repo.display()))?;
861 let mut state = State::load(&repo)?;
862 ensure!(
863 !state.lifted,
864 "the app is lifted: there is no fallback left to wire around; call the crate from src/units directly"
865 );
866 let app_dir = repo.join(APP_DIR);
867 let crate_dir = find_unit(&repo, opts.unit)?;
868 let manifest_text = std::fs::read_to_string(crate_dir.join("Cargo.toml"))?;
869 let unit_doc: DocumentMut = manifest_text.parse()?;
870 let crate_name = unit_doc
871 .get("package")
872 .and_then(|p| p.get("name"))
873 .and_then(|n| n.as_str())
874 .context("the unit's Cargo.toml has no package name")?
875 .to_string();
876 if let Some(kinds) = unit_doc
877 .get("lib")
878 .and_then(|l| l.get("crate-type"))
879 .and_then(|k| k.as_array())
880 {
881 ensure!(
882 kinds.iter().any(|k| k.as_str() == Some("rlib")),
883 "{crate_name} is not a Rust library: add \"rlib\" to `crate-type` in its Cargo.toml"
884 );
885 }
886 let name = crate_name
887 .strip_suffix("-rs")
888 .unwrap_or(&crate_name)
889 .to_string();
890 let switch = kill_switch(&crate_name);
891
892 let gate = if opts.skip_gate {
893 None
894 } else {
895 let outcome = crate::gate::gate(&crate_dir, &[])?;
896 if !outcome.passed {
897 let failed: Vec<String> = outcome
898 .checks
899 .iter()
900 .filter(|c| !c.passed)
901 .map(|c| c.name.to_string())
902 .collect();
903 bail!(
904 "{crate_name} does not pass gate ({}): run `rust-anything gate {}` and fix it before wiring",
905 failed.join(", "),
906 crate_dir.display()
907 );
908 }
909 Some(true)
910 };
911 if state.kind == AppKind::Library {
912 return library_wire(
913 &repo, opts, state, &crate_dir, crate_name, name, switch, gate,
914 );
915 }
916
917 let previous = state.units.iter().position(|u| u.name == name);
918 let http = state.kind == AppKind::Http;
919 ensure!(
920 !http || opts.commands.is_empty(),
921 "{} is a server: name what {name} answers with --route, not --command",
922 state.name
923 );
924 ensure!(
925 http || opts.routes.is_empty(),
926 "{} is a CLI: name what {name} answers with --command, not --route",
927 state.name
928 );
929 let routes = if !http {
930 Vec::new()
931 } else if opts.routes.is_empty() {
932 previous
933 .map(|i| state.units[i].routes.clone())
934 .filter(|r| !r.is_empty())
935 .with_context(|| format!("name the routes {name} answers with --route"))?
936 } else {
937 http_door::check_routes(&state, &name, opts.routes)?
938 .iter()
939 .map(http_door::Route::key)
940 .collect()
941 };
942 let commands = if http {
943 Vec::new()
944 } else if opts.commands.is_empty() {
945 previous
946 .map(|i| state.units[i].commands.clone())
947 .with_context(|| format!("name the commands {name} answers with --command"))?
948 } else {
949 opts.commands.to_vec()
950 };
951 let routable: Vec<&str> = state
952 .commands
953 .iter()
954 .map(String::as_str)
955 .chain([state.name.as_str()])
956 .collect();
957 for command in commands.iter().filter(|_| !http) {
958 ensure!(
959 routable.contains(&command.as_str()),
960 "the front door has no command `{command}` (it has: {}); add it to src/cli.rs and to `commands` in {}",
961 routable.join(", "),
962 app_dir.join(STATE_FILE).display()
963 );
964 if let Some(other) = state
965 .units
966 .iter()
967 .find(|u| u.name != name && u.commands.contains(command))
968 {
969 bail!("`{command}` is already wired to {}", other.name);
970 }
971 }
972 let path = match crate_dir.strip_prefix(repo.join("rust")) {
973 Ok(rel) => format!("../{}", rel.to_string_lossy().replace('\\', "/")),
974 Err(_) => crate_dir.to_string_lossy().into_owned(),
975 };
976 let entry = WiredUnit {
977 name: name.clone(),
978 crate_name: crate_name.clone(),
979 path: path.clone(),
980 commands: commands.clone(),
981 routes: routes.clone(),
982 switch: switch.clone(),
983 unit: None,
984 shadow: None,
985 kept: Vec::new(),
986 };
987 match previous {
988 Some(i) => state.units[i] = entry,
989 None => state.units.push(entry),
990 }
991
992 let cargo_path = app_dir.join("Cargo.toml");
993 let mut doc: DocumentMut = std::fs::read_to_string(&cargo_path)?.parse()?;
994 let mut dep = InlineTable::new();
995 dep.insert("path", path.as_str().into());
996 doc["dependencies"][crate_name.as_str()] = value(dep);
997 std::fs::write(&cargo_path, doc.to_string())?;
998
999 let glue = app_dir
1000 .join("src/units")
1001 .join(format!("{}.rs", ident(&name)));
1002 if !glue.exists() {
1003 let stub = if http {
1004 http_door::glue_rs(&crate_name)
1005 } else {
1006 glue_rs(&crate_name)
1007 };
1008 std::fs::write(&glue, stub)?;
1009 }
1010 let units = if http {
1011 http_door::units_rs(&state, false)
1012 } else {
1013 units_rs(&state)
1014 };
1015 std::fs::write(app_dir.join("src/units/mod.rs"), units)?;
1016 rustfmt(&app_dir.join("src/units/mod.rs"));
1017 state.save(&repo)?;
1018 let glue_pending = is_stub(&std::fs::read_to_string(&glue)?);
1019 let replay = if opts.check {
1020 Some(build_and_replay(&repo, &state)?)
1021 } else {
1022 None
1023 };
1024 Ok(WireOutcome {
1025 shadow: None,
1026 unit: name,
1027 crate_dir,
1028 commands,
1029 routes,
1030 switch,
1031 glue,
1032 glue_pending,
1033 gate,
1034 replay,
1035 })
1036}
1037
1038#[cfg(test)]
1039mod tests {
1040 use super::*;
1041
1042 fn case(args: &[&str], ok: bool) -> (Vec<String>, bool) {
1043 (args.iter().map(|a| a.to_string()).collect(), ok)
1044 }
1045
1046 #[test]
1047 fn commands_and_flags_come_from_successful_cases() {
1048 let (commands, flags) = infer_cli(&[
1049 case(&["div", "7", "2"], true),
1050 case(&["show", "--json", "-v", "x"], true),
1051 case(&["show", "--width=3"], true),
1052 case(&["nope"], false),
1053 case(&["--help"], true),
1054 ]);
1055 assert_eq!(commands, ["div", "show"]);
1056 let show = &flags["show"];
1057 assert!(!show["json"].takes_value);
1058 assert!(show["width"].takes_value);
1059 assert_eq!(show["short-v"].short, Some('v'));
1060 assert!(!flags.contains_key("div") || flags["div"].is_empty());
1061 let (none, root) = infer_cli(&[case(&["-n", "5", "file.txt"], true)]);
1062 assert!(none.is_empty());
1063 assert!(root[""].contains_key("short-n"));
1064 }
1065
1066 #[test]
1067 fn names_are_valid_rust() {
1068 assert_eq!(package_name("My Tool"), "my-tool");
1069 assert_eq!(package_name("7zip"), "app-7zip");
1070 assert_eq!(ident("text-kit"), "text_kit");
1071 assert_eq!(ident("mod"), "unit_mod");
1072 }
1073
1074 #[test]
1075 fn units_route_commands_behind_kill_switches() {
1076 let mut state = State {
1077 schema: SCHEMA.to_string(),
1078 name: "tcli".to_string(),
1079 commands: vec!["div".into(), "words".into()],
1080 units: Vec::new(),
1081 lifted: false,
1082 kind: AppKind::Cli,
1083 routes: Vec::new(),
1084 api: Vec::new(),
1085 };
1086 assert!(units_rs(&state).contains("None"));
1087 state.units.push(WiredUnit {
1088 name: "wordcount".into(),
1089 crate_name: "wordcount-rs".into(),
1090 path: "../wordcount-rs".into(),
1091 commands: vec!["words".into()],
1092 routes: Vec::new(),
1093 switch: "RUST_ANYTHING_UNIT_WORDCOUNT".into(),
1094 unit: None,
1095 shadow: None,
1096 kept: Vec::new(),
1097 });
1098 let code = units_rs(&state);
1099 assert!(code.contains("mod wordcount;"), "{code}");
1100 assert!(
1101 code.contains(
1102 "\"words\" if !sent_to_original(\"WORDCOUNT\") => Some(wordcount::run(command, matches)),"
1103 ),
1104 "{code}"
1105 );
1106 }
1107}