Skip to main content

rust_anything/
front_door.rs

1//! The front door: `rust/app`, a Rust binary that owns a CLI's entry point from day one and runs
2//! the original for every command not ported yet, and `wire`, which hands commands to a unit's
3//! `port.rs` behind a kill switch.
4
5use 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
23/// The glue file still holds the stub `wire` wrote, however rustfmt wrapped it.
24pub(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/// `rust/app/rust-anything.json`: the commands the front door routes and the units wired to them.
30#[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    /// Servers: the requests recorded, as `METHOD /path`, to choose routes from.
42    #[serde(default, skip_serializing_if = "Vec::is_empty")]
43    pub routes: Vec<String>,
44    /// Libraries: the public API, unit by unit.
45    #[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    /// Servers: the routes the unit answers.
73    #[serde(default, skip_serializing_if = "Vec::is_empty")]
74    pub routes: Vec<String>,
75    pub switch: String,
76    /// Libraries: the unit id the crate ports.
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub unit: Option<String>,
79    /// Libraries: the shadow drop-in the original package imports in place of the unit.
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub shadow: Option<String>,
82    /// Libraries: exports that stay in the original language.
83    #[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
131/// `RUST_ANYTHING_UNIT_<NAME>`, the variable that sends a unit back to the original.
132pub 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
166/// The commands (first arguments of cases the original ran successfully) and the flags seen with
167/// each; the key `""` holds the flags of an app without commands.
168fn 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, PathBuf}};
314use std::process::{{Command, ExitCode, ExitStatus}};
315
316const ROOT: &str = match option_env!(\"RUST_ANYTHING_REPO\") {{
317    Some(root) => root,
318    None => concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/../..\"),
319}};
320const RUN: &[&str] = &[{}];
321const FALLBACK_LOG: &str = \"{}\";
322const ORIGINAL_BASE: &str = \"RUST_ANYTHING_ORIGINAL_BASE\";
323
324/// Where an installed package finds `node_modules/...`: the folder its launcher resolved the
325/// original from, else the nearest one above this binary while it sits inside `node_modules`.
326fn installed(word: &str) -> Option<OsString> {{
327    if !word.starts_with(\"node_modules/\") {{
328        return None;
329    }}
330    if let Some(base) = std::env::var_os(ORIGINAL_BASE) {{
331        let path = Path::new(&base).join(word);
332        if path.exists() {{
333            return Some(path.into_os_string());
334        }}
335    }}
336    let exe = std::env::current_exe().ok()?.canonicalize().ok()?;
337    if !exe.components().any(|c| c.as_os_str() == \"node_modules\") {{
338        return None;
339    }}
340    exe.ancestors()
341        .skip(1)
342        .map(|dir| dir.join(word))
343        .find(|path| path.exists())
344        .map(PathBuf::into_os_string)
345}}
346
347fn resolve(word: &str) -> OsString {{
348    if word.starts_with('-') {{
349        return word.into();
350    }}
351    if let Some(path) = installed(word) {{
352        return path;
353    }}
354    let path = Path::new(ROOT).join(word);
355    let looks_like_path = word.contains('/') || word.contains('\\\\') || path.is_file();
356    if looks_like_path && path.exists() {{
357        return std::path::absolute(&path).unwrap_or(path).into_os_string();
358    }}
359    word.into()
360}}
361
362fn log() -> Option<std::fs::File> {{
363    let path = std::env::var_os(FALLBACK_LOG)?;
364    std::fs::OpenOptions::new()
365        .create(true)
366        .append(true)
367        .open(path)
368        .ok()
369}}
370
371/// Tells `rust-anything app replay` this build counts its fallbacks, even when it makes none.
372pub fn report_fallbacks() {{
373    let _ = log();
374}}
375
376/// Runs the original with the same arguments, stdin and environment, and passes its output and
377/// exit code through. Each call is one fallback.
378pub fn run(args: &[OsString]) -> ExitCode {{
379    run_with(args, None)
380}}
381
382/// For glue that read stdin and then declines the case: runs the original with `input` as its
383/// stdin. Each call is one fallback.
384#[allow(dead_code)]
385pub fn run_with_stdin(args: &[OsString], input: &[u8]) -> ExitCode {{
386    run_with(args, Some(input))
387}}
388
389fn run_with(args: &[OsString], input: Option<&[u8]>) -> ExitCode {{
390    if let Some(mut file) = log() {{
391        let line: Vec<String> = args
392            .iter()
393            .map(|a| a.to_string_lossy().into_owned())
394            .collect();
395        let _ = writeln!(file, \"{{}}\", line.join(\" \"));
396    }}
397    let Some((program, rest)) = RUN.split_first() else {{
398        return ExitCode::from(127);
399    }};
400    let mut command = Command::new(resolve(program));
401    command.args(rest.iter().map(|w| resolve(w))).args(args);
402    #[cfg(windows)]
403    if Path::new(program)
404        .file_stem()
405        .and_then(|name| name.to_str())
406        .is_some_and(|name| [\"python\", \"python3\", \"py\"]
407            .iter()
408            .any(|candidate| name.eq_ignore_ascii_case(candidate)))
409        && std::env::var_os(\"PYTHONIOENCODING\").is_none()
410    {{
411        command.env(\"PYTHONIOENCODING\", \"utf-8\");
412    }}
413    let status = match input {{
414        None => command.status(),
415        Some(input) => command
416            .stdin(std::process::Stdio::piped())
417            .spawn()
418            .and_then(|mut child| {{
419                if let Some(mut pipe) = child.stdin.take() {{
420                    let _ = pipe.write_all(input);
421                }}
422                child.wait()
423            }}),
424    }};
425    match status {{
426        Ok(status) => ExitCode::from(exit_code(status)),
427        Err(e) => {{
428            eprintln!(\"front door: cannot run the original `{{}}`: {{e}}\", RUN.join(\" \"));
429            ExitCode::from(127)
430        }}
431    }}
432}}
433
434fn exit_code(status: ExitStatus) -> u8 {{
435    if let Some(code) = status.code() {{
436        return (code & 0xff) as u8;
437    }}
438    #[cfg(unix)]
439    {{
440        use std::os::unix::process::ExitStatusExt;
441        if let Some(signal) = status.signal() {{
442            return (128 + signal) as u8;
443        }}
444    }}
445    1
446}}
447",
448        words.join(", "),
449        app::FALLBACK_ENV
450    )
451}
452
453fn units_rs(state: &State) -> String {
454    let mut out = format!(
455        "//! Generated by `rust-anything app wire` from {STATE_FILE}; it is rewritten on every wire.\n\n\
456         use std::process::ExitCode;\n\n\
457         use clap::ArgMatches;\n\n"
458    );
459    if state.units.is_empty() {
460        out += "pub fn dispatch(_command: &str, _matches: &ArgMatches) -> Option<ExitCode> {\n    None\n}\n";
461        return out;
462    }
463    for unit in &state.units {
464        out += &format!("mod {};\n", ident(&unit.name));
465    }
466    out += &format!(
467        "\n/// `{KILL_SWITCH_PREFIX}<NAME>=original` sends that unit back to the original.\n\
468         fn sent_to_original(unit: &str) -> bool {{\n    \
469             std::env::var(format!(\"{KILL_SWITCH_PREFIX}{{unit}}\")).is_ok_and(|v| v == \"original\")\n\
470         }}\n\n\
471         pub fn dispatch(command: &str, matches: &ArgMatches) -> Option<ExitCode> {{\n    \
472             match command {{\n"
473    );
474    for unit in &state.units {
475        let pattern: Vec<String> = unit.commands.iter().map(|c| format!("{c:?}")).collect();
476        let switch = unit
477            .switch
478            .strip_prefix(KILL_SWITCH_PREFIX)
479            .unwrap_or(&unit.switch);
480        out += &format!(
481            "        {} if !sent_to_original({switch:?}) => Some({}::run(command, matches)),\n",
482            pattern.join(" | "),
483            ident(&unit.name)
484        );
485    }
486    out += "        _ => None,\n    }\n}\n";
487    out
488}
489
490fn glue_rs(crate_name: &str) -> String {
491    let krate = crate_name.replace('-', "_");
492    format!(
493        "//! Glue from the front door to `{crate_name}`: parse the arguments, call `{krate}::port`,\n\
494         //! print what the original prints and return its exit code. A case the port does not\n\
495         //! cover yet goes back with `crate::original::run(&argv[1..])`, or\n\
496         //! `crate::original::run_with_stdin(&argv[1..], &input)` once stdin was read.\n\n\
497         use std::ffi::OsString;\n\
498         use std::process::ExitCode;\n\n\
499         use clap::ArgMatches;\n\n\
500         pub fn run(command: &str, matches: &ArgMatches) -> ExitCode {{\n    \
501             let args: Vec<&OsString> = matches\n        \
502                 .get_many::<OsString>(\"args\")\n        \
503                 .into_iter()\n        \
504                 .flatten()\n        \
505                 .collect();\n    \
506             unimplemented!(\"glue for `{{command}}` {{args:?}}: call {krate}::port\")\n\
507         }}\n"
508    )
509}
510
511pub(crate) fn rustfmt(file: &Path) {
512    let _ = Command::new("rustfmt")
513        .args(["--edition", "2024"])
514        .arg(file)
515        .output();
516}
517
518/// Set when rust-anything builds a front door: the repository the original runs from, so a
519/// `rust/` that is a symlink to a folder elsewhere still finds it.
520pub(crate) const REPO_ENV: &str = "RUST_ANYTHING_REPO";
521
522pub(crate) fn cargo_build(app_dir: &Path, target_dir: Option<&Path>) -> Result<PathBuf> {
523    let mut cmd = Command::new("cargo");
524    cmd.args([
525        "build",
526        "--message-format=json-render-diagnostics",
527        "--manifest-path",
528    ])
529    .arg(app_dir.join("Cargo.toml"));
530    if let Some(repo) = app_dir.parent().and_then(Path::parent)
531        && let Ok(repo) = repo.canonical()
532    {
533        cmd.env(REPO_ENV, repo);
534    }
535    if let Some(dir) = target_dir {
536        cmd.env("CARGO_TARGET_DIR", dir);
537    }
538    let out = cmd.output().context("running cargo")?;
539    ensure!(
540        out.status.success(),
541        "cargo build in {} failed:\n{}",
542        app_dir.display(),
543        String::from_utf8_lossy(&out.stderr)
544    );
545    let mut exe = None;
546    for line in String::from_utf8_lossy(&out.stdout).lines() {
547        let Ok(msg) = serde_json::from_str::<serde_json::Value>(line) else {
548            continue;
549        };
550        let is_bin = msg["target"]["kind"]
551            .as_array()
552            .is_some_and(|k| k.iter().any(|v| v == "bin"));
553        if msg["reason"] == "compiler-artifact"
554            && is_bin
555            && let Some(path) = msg["executable"].as_str()
556        {
557            exe = Some(PathBuf::from(path));
558        }
559    }
560    exe.context("cargo built no binary")
561}
562
563fn build_and_replay(repo: &Path, state: &State) -> Result<ReplayOutcome> {
564    let app_dir = repo.join(APP_DIR);
565    let target_dir = app_dir.join("target");
566    if state.kind == AppKind::Library {
567        crate::library::cargo_build_lib(&app_dir, Some(&target_dir))?;
568        return crate::library::replay(repo, state, None);
569    }
570    let exe = cargo_build(&app_dir, Some(&target_dir))?;
571    app::replay(&ReplayOptions {
572        case: None,
573        repo,
574        build: Some(&app::shell_quote(&exe.to_string_lossy())),
575        timeout_secs: None,
576        port: None,
577    })
578}
579
580pub struct FrontDoorOptions<'a> {
581    pub repo: &'a Path,
582    /// Treat the repository as a library even when it has a `main` (a demo, a test runner).
583    pub library: bool,
584    /// Build the front door and replay the recorded cases against it.
585    pub check: bool,
586}
587
588#[derive(Debug, Serialize)]
589pub struct FrontDoorOutcome {
590    pub dir: PathBuf,
591    pub binary: String,
592    pub commands: Vec<String>,
593    /// Servers: the recorded requests, as `METHOD /path`.
594    pub routes: Vec<String>,
595    /// Libraries: the public API, unit by unit.
596    pub api: Vec<crate::library::ApiUnit>,
597    pub flags: BTreeMap<String, BTreeMap<String, Flag>>,
598    pub files: Vec<String>,
599    pub replay: Option<ReplayOutcome>,
600}
601
602pub fn front_door(opts: &FrontDoorOptions) -> Result<FrontDoorOutcome> {
603    let repo = opts
604        .repo
605        .canonical()
606        .with_context(|| format!("no folder {}", opts.repo.display()))?;
607    let config = app::Config::load(&repo)?;
608    let config = match config {
609        Some(c) if !opts.library => c,
610        _ => {
611            let report = crate::analyze::analyze(&repo)?;
612            let shape = crate::whole_app::whole_app(&repo, &report).shape;
613            ensure!(
614                opts.library || shape == "library",
615                "no recorded cases in {}: run `rust-anything app record` first (or --library if this {shape} is used as a library)",
616                app::cases_dir(&repo).display()
617            );
618            return library_front_door(&repo, opts, &report);
619        }
620    };
621    let dir = repo.join(APP_DIR);
622    ensure!(
623        !dir.exists(),
624        "{} already exists; the front door is yours once scaffolded (remove it to scaffold again)",
625        dir.display()
626    );
627    let binary = package_name(&config.name);
628    if let Some(http) = &config.http {
629        ensure!(
630            http.port.is_none(),
631            "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"
632        );
633        let routes = crate::http::recorded_routes(&repo)?;
634        let state = State {
635            schema: SCHEMA.to_string(),
636            name: config.name.clone(),
637            commands: Vec::new(),
638            units: Vec::new(),
639            lifted: false,
640            kind: AppKind::Http,
641            routes: routes.clone(),
642            api: Vec::new(),
643        };
644        let files: Vec<(&str, String)> = vec![
645            ("Cargo.toml", http_door::cargo_toml(&binary, &config.name)),
646            (".gitignore", "/target\n".to_string()),
647            ("src/main.rs", http_door::main_rs()),
648            (
649                "src/original.rs",
650                http_door::original_rs(&config.run, http.fresh.is_empty()),
651            ),
652            ("src/units/mod.rs", http_door::units_rs(&state, false)),
653        ];
654        return finish_front_door(
655            &repo,
656            opts,
657            state,
658            files,
659            binary,
660            Vec::new(),
661            BTreeMap::new(),
662            routes,
663        );
664    }
665    let (commands, flags) = infer_cli(&app::recorded_args(&repo)?);
666    let files: Vec<(&str, String)> = vec![
667        (
668            "Cargo.toml",
669            format!(
670                "[package]\nname = \"{binary}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\
671                 description = \"Front door for `{}`, generated by rust-anything: Rust owns the entry point, the original answers what is not ported yet\"\n\n\
672                 [[bin]]\nname = \"{binary}\"\npath = \"src/main.rs\"\n\n\
673                 [dependencies]\nclap = \"4\"\n\n\
674                 [workspace]\n",
675                config.name
676            ),
677        ),
678        (".gitignore", "/target\n".to_string()),
679        ("src/main.rs", MAIN_RS.to_string()),
680        ("src/cli.rs", cli_rs(&config.name, &commands, &flags)),
681        ("src/original.rs", original_rs(&config.run)),
682    ];
683    let state = State {
684        schema: SCHEMA.to_string(),
685        name: config.name.clone(),
686        commands: commands.clone(),
687        units: Vec::new(),
688        lifted: false,
689        kind: AppKind::Cli,
690        routes: Vec::new(),
691        api: Vec::new(),
692    };
693    let mut files = files;
694    files.push(("src/units/mod.rs", units_rs(&state)));
695    finish_front_door(
696        &repo,
697        opts,
698        state,
699        files,
700        binary,
701        commands,
702        flags,
703        Vec::new(),
704    )
705}
706
707#[allow(clippy::too_many_arguments)]
708fn finish_front_door(
709    repo: &Path,
710    opts: &FrontDoorOptions,
711    state: State,
712    files: Vec<(&str, String)>,
713    binary: String,
714    commands: Vec<String>,
715    flags: BTreeMap<String, BTreeMap<String, Flag>>,
716    routes: Vec<String>,
717) -> Result<FrontDoorOutcome> {
718    let repo = repo.to_path_buf();
719    let dir = repo.join(APP_DIR);
720    let state_api = state.api.clone();
721    for (path, text) in &files {
722        let target = dir.join(path);
723        if let Some(parent) = target.parent() {
724            std::fs::create_dir_all(parent)?;
725        }
726        std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
727    }
728    if state.kind == AppKind::Library {
729        rustfmt(&dir.join("src/lib.rs"));
730    } else {
731        rustfmt(&dir.join("src/main.rs"));
732    }
733    state.save(&repo)?;
734    let replay = if opts.check {
735        Some(build_and_replay(&repo, &state)?)
736    } else {
737        None
738    };
739    let mut written: Vec<String> = files.iter().map(|(p, _)| p.to_string()).collect();
740    written.push(STATE_FILE.to_string());
741    Ok(FrontDoorOutcome {
742        dir,
743        binary,
744        commands,
745        routes,
746        api: state_api,
747        flags,
748        files: written,
749        replay,
750    })
751}
752
753fn library_front_door(
754    repo: &Path,
755    opts: &FrontDoorOptions,
756    report: &crate::analyze::Report,
757) -> Result<FrontDoorOutcome> {
758    let name = report
759        .packages
760        .first()
761        .map(|p| p.name.clone())
762        .filter(|n| !n.is_empty())
763        .or_else(|| repo.file_name().map(|n| n.to_string_lossy().into_owned()))
764        .unwrap_or_else(|| "lib".to_string());
765    let package = package_name(&name);
766    let state = State {
767        schema: SCHEMA.to_string(),
768        name: name.clone(),
769        commands: Vec::new(),
770        units: Vec::new(),
771        lifted: false,
772        kind: AppKind::Library,
773        routes: Vec::new(),
774        api: crate::library::public_api(repo, report),
775    };
776    ensure!(
777        !state.api.is_empty(),
778        "no exported function or class found to make a public API from"
779    );
780    let files: Vec<(&str, String)> = vec![
781        ("Cargo.toml", crate::library::cargo_toml(&package, &name)),
782        (".gitignore", "/target\n".to_string()),
783        ("src/lib.rs", crate::library::lib_rs(&state, false)),
784    ];
785    finish_front_door(
786        repo,
787        opts,
788        state,
789        files,
790        package,
791        Vec::new(),
792        BTreeMap::new(),
793        Vec::new(),
794    )
795}
796
797#[allow(clippy::too_many_arguments)]
798fn library_wire(
799    repo: &Path,
800    opts: &WireOptions,
801    mut state: State,
802    crate_dir: &Path,
803    crate_name: String,
804    name: String,
805    switch: String,
806    gate: Option<bool>,
807) -> Result<WireOutcome> {
808    ensure!(
809        opts.commands.is_empty() && opts.routes.is_empty(),
810        "{} is a library: a unit answers its own exports, so wire takes no --command or --route",
811        state.name
812    );
813    let manifest = crate::bridge::Manifest::load(crate_dir).with_context(|| {
814        format!(
815            "a library unit is a crate made by `bridge` (the original package calls it through its bindings), and {} has no manifest",
816            crate_dir.display()
817        )
818    })?;
819    let api = crate::library::api_unit(&state, &manifest.unit)?.clone();
820    let app_dir = repo.join(APP_DIR);
821    let previous = state.units.iter().position(|u| u.name == name);
822    let shadow = crate::library::shadow_for(
823        crate_dir,
824        previous.and_then(|i| state.units[i].shadow.as_deref()),
825    )?;
826    let path = match crate_dir.strip_prefix(repo.join("rust")) {
827        Ok(rel) => format!("../{}", rel.to_string_lossy().replace('\\', "/")),
828        Err(_) => crate_dir.to_string_lossy().into_owned(),
829    };
830    let entry = WiredUnit {
831        name: name.clone(),
832        crate_name: crate_name.clone(),
833        path: path.clone(),
834        commands: Vec::new(),
835        routes: Vec::new(),
836        switch: switch.clone(),
837        unit: Some(api.unit.clone()),
838        shadow: shadow.as_ref().map(|p| p.to_string_lossy().into_owned()),
839        kept: manifest.js_only.iter().map(|j| j.name.clone()).collect(),
840    };
841    match previous {
842        Some(i) => state.units[i] = entry,
843        None => state.units.push(entry),
844    }
845    let cargo_path = app_dir.join("Cargo.toml");
846    let mut doc: DocumentMut = std::fs::read_to_string(&cargo_path)?.parse()?;
847    let mut dep = InlineTable::new();
848    dep.insert("path", path.as_str().into());
849    doc["dependencies"][crate_name.as_str()] = value(dep);
850    std::fs::write(&cargo_path, doc.to_string())?;
851    if manifest.kind == crate::bridge::Kind::Pyo3 {
852        crate::library::allow_python_symbols(&app_dir)?;
853    }
854    let lib = app_dir.join("src/lib.rs");
855    std::fs::write(&lib, crate::library::lib_rs(&state, false))?;
856    rustfmt(&lib);
857    state.save(repo)?;
858    let replay = if opts.check {
859        Some(build_and_replay(repo, &state)?)
860    } else {
861        None
862    };
863    Ok(WireOutcome {
864        shadow,
865        unit: name,
866        crate_dir: crate_dir.to_path_buf(),
867        commands: Vec::new(),
868        routes: Vec::new(),
869        switch,
870        glue: lib,
871        glue_pending: false,
872        gate,
873        replay,
874    })
875}
876
877fn find_unit(repo: &Path, unit: &str) -> Result<PathBuf> {
878    let rust = repo.join("rust");
879    for candidate in [
880        rust.join(unit),
881        rust.join(format!("{unit}-rs")),
882        repo.join(unit),
883        PathBuf::from(unit),
884    ] {
885        if candidate.join("Cargo.toml").is_file() && candidate != repo.join(APP_DIR) {
886            return Ok(candidate.canonical()?);
887        }
888    }
889    let wanted = unit.trim_end_matches('/');
890    if let Ok(entries) = std::fs::read_dir(&rust) {
891        for entry in entries.flatten() {
892            if let Ok(m) = crate::bridge::Manifest::load(&entry.path())
893                && m.unit.trim_end_matches('/') == wanted
894            {
895                return Ok(entry.path().canonical()?);
896            }
897        }
898    }
899    bail!(
900        "no unit crate `{unit}`: give the crate folder (`rust/<name>`, as `bridge` made it) or the unit id"
901    )
902}
903
904pub struct WireOptions<'a> {
905    pub repo: &'a Path,
906    /// Unit crate folder, its name under `rust/`, or the unit id it was bridged from.
907    pub unit: &'a str,
908    /// Commands the unit answers; kept from the last wire when empty.
909    pub commands: &'a [String],
910    /// Servers: routes the unit answers (`GET /users/{id}`, `/path` for any method, `*` for
911    /// everything else); kept from the last wire when empty.
912    pub routes: &'a [String],
913    /// Wire without running `gate` on the unit first (when it just passed).
914    pub skip_gate: bool,
915    pub check: bool,
916}
917
918#[derive(Debug, Serialize)]
919pub struct WireOutcome {
920    /// Libraries: the drop-in the original package imports in place of the unit.
921    pub shadow: Option<PathBuf>,
922    pub unit: String,
923    pub crate_dir: PathBuf,
924    pub commands: Vec<String>,
925    pub routes: Vec<String>,
926    pub switch: String,
927    pub glue: PathBuf,
928    /// The glue file still holds the generated stub.
929    pub glue_pending: bool,
930    pub gate: Option<bool>,
931    pub replay: Option<ReplayOutcome>,
932}
933
934pub fn wire(opts: &WireOptions) -> Result<WireOutcome> {
935    let repo = opts
936        .repo
937        .canonical()
938        .with_context(|| format!("no folder {}", opts.repo.display()))?;
939    let mut state = State::load(&repo)?;
940    ensure!(
941        !state.lifted,
942        "the app is lifted: there is no fallback left to wire around; call the crate from src/units directly"
943    );
944    let app_dir = repo.join(APP_DIR);
945    let crate_dir = find_unit(&repo, opts.unit)?;
946    let manifest_text = std::fs::read_to_string(crate_dir.join("Cargo.toml"))?;
947    let unit_doc: DocumentMut = manifest_text.parse()?;
948    let crate_name = unit_doc
949        .get("package")
950        .and_then(|p| p.get("name"))
951        .and_then(|n| n.as_str())
952        .context("the unit's Cargo.toml has no package name")?
953        .to_string();
954    if let Some(kinds) = unit_doc
955        .get("lib")
956        .and_then(|l| l.get("crate-type"))
957        .and_then(|k| k.as_array())
958    {
959        ensure!(
960            kinds.iter().any(|k| k.as_str() == Some("rlib")),
961            "{crate_name} is not a Rust library: add \"rlib\" to `crate-type` in its Cargo.toml"
962        );
963    }
964    let name = crate_name
965        .strip_suffix("-rs")
966        .unwrap_or(&crate_name)
967        .to_string();
968    let switch = kill_switch(&crate_name);
969
970    let gate = if opts.skip_gate {
971        None
972    } else {
973        let outcome = crate::gate::gate(&crate_dir, &[])?;
974        if !outcome.passed {
975            let failed: Vec<String> = outcome
976                .checks
977                .iter()
978                .filter(|c| !c.passed)
979                .map(|c| c.name.to_string())
980                .collect();
981            bail!(
982                "{crate_name} does not pass gate ({}): run `rust-anything gate {}` and fix it before wiring",
983                failed.join(", "),
984                crate_dir.display()
985            );
986        }
987        Some(true)
988    };
989    if state.kind == AppKind::Library {
990        return library_wire(
991            &repo, opts, state, &crate_dir, crate_name, name, switch, gate,
992        );
993    }
994
995    let previous = state.units.iter().position(|u| u.name == name);
996    let http = state.kind == AppKind::Http;
997    ensure!(
998        !http || opts.commands.is_empty(),
999        "{} is a server: name what {name} answers with --route, not --command",
1000        state.name
1001    );
1002    ensure!(
1003        http || opts.routes.is_empty(),
1004        "{} is a CLI: name what {name} answers with --command, not --route",
1005        state.name
1006    );
1007    let routes = if !http {
1008        Vec::new()
1009    } else if opts.routes.is_empty() {
1010        previous
1011            .map(|i| state.units[i].routes.clone())
1012            .filter(|r| !r.is_empty())
1013            .with_context(|| format!("name the routes {name} answers with --route"))?
1014    } else {
1015        http_door::check_routes(&state, &name, opts.routes)?
1016            .iter()
1017            .map(http_door::Route::key)
1018            .collect()
1019    };
1020    let commands = if http {
1021        Vec::new()
1022    } else if opts.commands.is_empty() {
1023        previous
1024            .map(|i| state.units[i].commands.clone())
1025            .with_context(|| format!("name the commands {name} answers with --command"))?
1026    } else {
1027        opts.commands.to_vec()
1028    };
1029    let routable: Vec<&str> = state
1030        .commands
1031        .iter()
1032        .map(String::as_str)
1033        .chain([state.name.as_str()])
1034        .collect();
1035    for command in commands.iter().filter(|_| !http) {
1036        ensure!(
1037            routable.contains(&command.as_str()),
1038            "the front door has no command `{command}` (it has: {}); add it to src/cli.rs and to `commands` in {}",
1039            routable.join(", "),
1040            app_dir.join(STATE_FILE).display()
1041        );
1042        if let Some(other) = state
1043            .units
1044            .iter()
1045            .find(|u| u.name != name && u.commands.contains(command))
1046        {
1047            bail!("`{command}` is already wired to {}", other.name);
1048        }
1049    }
1050    let path = match crate_dir.strip_prefix(repo.join("rust")) {
1051        Ok(rel) => format!("../{}", rel.to_string_lossy().replace('\\', "/")),
1052        Err(_) => crate_dir.to_string_lossy().into_owned(),
1053    };
1054    let entry = WiredUnit {
1055        name: name.clone(),
1056        crate_name: crate_name.clone(),
1057        path: path.clone(),
1058        commands: commands.clone(),
1059        routes: routes.clone(),
1060        switch: switch.clone(),
1061        unit: None,
1062        shadow: None,
1063        kept: Vec::new(),
1064    };
1065    match previous {
1066        Some(i) => state.units[i] = entry,
1067        None => state.units.push(entry),
1068    }
1069
1070    let cargo_path = app_dir.join("Cargo.toml");
1071    let mut doc: DocumentMut = std::fs::read_to_string(&cargo_path)?.parse()?;
1072    let mut dep = InlineTable::new();
1073    dep.insert("path", path.as_str().into());
1074    doc["dependencies"][crate_name.as_str()] = value(dep);
1075    std::fs::write(&cargo_path, doc.to_string())?;
1076
1077    let glue = app_dir
1078        .join("src/units")
1079        .join(format!("{}.rs", ident(&name)));
1080    if !glue.exists() {
1081        let stub = if http {
1082            http_door::glue_rs(&crate_name)
1083        } else {
1084            glue_rs(&crate_name)
1085        };
1086        std::fs::write(&glue, stub)?;
1087    }
1088    let units = if http {
1089        http_door::units_rs(&state, false)
1090    } else {
1091        units_rs(&state)
1092    };
1093    std::fs::write(app_dir.join("src/units/mod.rs"), units)?;
1094    rustfmt(&app_dir.join("src/units/mod.rs"));
1095    state.save(&repo)?;
1096    let glue_pending = is_stub(&std::fs::read_to_string(&glue)?);
1097    let replay = if opts.check {
1098        Some(build_and_replay(&repo, &state)?)
1099    } else {
1100        None
1101    };
1102    Ok(WireOutcome {
1103        shadow: None,
1104        unit: name,
1105        crate_dir,
1106        commands,
1107        routes,
1108        switch,
1109        glue,
1110        glue_pending,
1111        gate,
1112        replay,
1113    })
1114}
1115
1116#[cfg(test)]
1117mod tests {
1118    use super::*;
1119
1120    fn case(args: &[&str], ok: bool) -> (Vec<String>, bool) {
1121        (args.iter().map(|a| a.to_string()).collect(), ok)
1122    }
1123
1124    #[test]
1125    fn commands_and_flags_come_from_successful_cases() {
1126        let (commands, flags) = infer_cli(&[
1127            case(&["div", "7", "2"], true),
1128            case(&["show", "--json", "-v", "x"], true),
1129            case(&["show", "--width=3"], true),
1130            case(&["nope"], false),
1131            case(&["--help"], true),
1132        ]);
1133        assert_eq!(commands, ["div", "show"]);
1134        let show = &flags["show"];
1135        assert!(!show["json"].takes_value);
1136        assert!(show["width"].takes_value);
1137        assert_eq!(show["short-v"].short, Some('v'));
1138        assert!(!flags.contains_key("div") || flags["div"].is_empty());
1139        let (none, root) = infer_cli(&[case(&["-n", "5", "file.txt"], true)]);
1140        assert!(none.is_empty());
1141        assert!(root[""].contains_key("short-n"));
1142    }
1143
1144    #[test]
1145    fn names_are_valid_rust() {
1146        assert_eq!(package_name("My Tool"), "my-tool");
1147        assert_eq!(package_name("7zip"), "app-7zip");
1148        assert_eq!(ident("text-kit"), "text_kit");
1149        assert_eq!(ident("mod"), "unit_mod");
1150    }
1151
1152    #[test]
1153    fn generated_fallback_matches_python_stems_case_insensitively() {
1154        let code = original_rs(&["Python.EXE".to_string()]);
1155        assert!(
1156            code.contains(".any(|candidate| name.eq_ignore_ascii_case(candidate))"),
1157            "{code}"
1158        );
1159        assert!(
1160            code.contains("var_os(\"PYTHONIOENCODING\").is_none()"),
1161            "{code}"
1162        );
1163    }
1164
1165    #[test]
1166    fn units_route_commands_behind_kill_switches() {
1167        let mut state = State {
1168            schema: SCHEMA.to_string(),
1169            name: "tcli".to_string(),
1170            commands: vec!["div".into(), "words".into()],
1171            units: Vec::new(),
1172            lifted: false,
1173            kind: AppKind::Cli,
1174            routes: Vec::new(),
1175            api: Vec::new(),
1176        };
1177        assert!(units_rs(&state).contains("None"));
1178        state.units.push(WiredUnit {
1179            name: "wordcount".into(),
1180            crate_name: "wordcount-rs".into(),
1181            path: "../wordcount-rs".into(),
1182            commands: vec!["words".into()],
1183            routes: Vec::new(),
1184            switch: "RUST_ANYTHING_UNIT_WORDCOUNT".into(),
1185            unit: None,
1186            shadow: None,
1187            kept: Vec::new(),
1188        });
1189        let code = units_rs(&state);
1190        assert!(code.contains("mod wordcount;"), "{code}");
1191        assert!(
1192            code.contains(
1193                "\"words\" if !sent_to_original(\"WORDCOUNT\") => Some(wordcount::run(command, matches)),"
1194            ),
1195            "{code}"
1196        );
1197    }
1198}