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