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(
651                    &config.run,
652                    http.fresh.is_empty(),
653                    http.ready_secs.unwrap_or(60),
654                    http.ready_request.as_deref(),
655                ),
656            ),
657            ("src/units/mod.rs", http_door::units_rs(&state, false)),
658        ];
659        return finish_front_door(
660            &repo,
661            opts,
662            state,
663            files,
664            binary,
665            Vec::new(),
666            BTreeMap::new(),
667            routes,
668        );
669    }
670    let (commands, flags) = infer_cli(&app::recorded_args(&repo)?);
671    let files: Vec<(&str, String)> = vec![
672        (
673            "Cargo.toml",
674            format!(
675                "[package]\nname = \"{binary}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\
676                 description = \"Front door for `{}`, generated by rust-anything: Rust owns the entry point, the original answers what is not ported yet\"\n\n\
677                 [[bin]]\nname = \"{binary}\"\npath = \"src/main.rs\"\n\n\
678                 [dependencies]\nclap = \"4\"\n\n\
679                 [workspace]\n",
680                config.name
681            ),
682        ),
683        (".gitignore", "/target\n".to_string()),
684        ("src/main.rs", MAIN_RS.to_string()),
685        ("src/cli.rs", cli_rs(&config.name, &commands, &flags)),
686        ("src/original.rs", original_rs(&config.run)),
687    ];
688    let state = State {
689        schema: SCHEMA.to_string(),
690        name: config.name.clone(),
691        commands: commands.clone(),
692        units: Vec::new(),
693        lifted: false,
694        kind: AppKind::Cli,
695        routes: Vec::new(),
696        api: Vec::new(),
697    };
698    let mut files = files;
699    files.push(("src/units/mod.rs", units_rs(&state)));
700    finish_front_door(
701        &repo,
702        opts,
703        state,
704        files,
705        binary,
706        commands,
707        flags,
708        Vec::new(),
709    )
710}
711
712#[allow(clippy::too_many_arguments)]
713fn finish_front_door(
714    repo: &Path,
715    opts: &FrontDoorOptions,
716    state: State,
717    files: Vec<(&str, String)>,
718    binary: String,
719    commands: Vec<String>,
720    flags: BTreeMap<String, BTreeMap<String, Flag>>,
721    routes: Vec<String>,
722) -> Result<FrontDoorOutcome> {
723    let repo = repo.to_path_buf();
724    let dir = repo.join(APP_DIR);
725    let state_api = state.api.clone();
726    for (path, text) in &files {
727        let target = dir.join(path);
728        if let Some(parent) = target.parent() {
729            std::fs::create_dir_all(parent)?;
730        }
731        std::fs::write(&target, text).with_context(|| format!("writing {}", target.display()))?;
732    }
733    if state.kind == AppKind::Library {
734        rustfmt(&dir.join("src/lib.rs"));
735    } else {
736        rustfmt(&dir.join("src/main.rs"));
737    }
738    state.save(&repo)?;
739    let replay = if opts.check {
740        Some(build_and_replay(&repo, &state)?)
741    } else {
742        None
743    };
744    let mut written: Vec<String> = files.iter().map(|(p, _)| p.to_string()).collect();
745    written.push(STATE_FILE.to_string());
746    Ok(FrontDoorOutcome {
747        dir,
748        binary,
749        commands,
750        routes,
751        api: state_api,
752        flags,
753        files: written,
754        replay,
755    })
756}
757
758fn library_front_door(
759    repo: &Path,
760    opts: &FrontDoorOptions,
761    report: &crate::analyze::Report,
762) -> Result<FrontDoorOutcome> {
763    let name = report
764        .packages
765        .first()
766        .map(|p| p.name.clone())
767        .filter(|n| !n.is_empty())
768        .or_else(|| repo.file_name().map(|n| n.to_string_lossy().into_owned()))
769        .unwrap_or_else(|| "lib".to_string());
770    let package = package_name(&name);
771    let state = State {
772        schema: SCHEMA.to_string(),
773        name: name.clone(),
774        commands: Vec::new(),
775        units: Vec::new(),
776        lifted: false,
777        kind: AppKind::Library,
778        routes: Vec::new(),
779        api: crate::library::public_api(repo, report),
780    };
781    ensure!(
782        !state.api.is_empty(),
783        "no exported function or class found to make a public API from"
784    );
785    let files: Vec<(&str, String)> = vec![
786        ("Cargo.toml", crate::library::cargo_toml(&package, &name)),
787        (".gitignore", "/target\n".to_string()),
788        ("src/lib.rs", crate::library::lib_rs(&state, false)),
789    ];
790    finish_front_door(
791        repo,
792        opts,
793        state,
794        files,
795        package,
796        Vec::new(),
797        BTreeMap::new(),
798        Vec::new(),
799    )
800}
801
802#[allow(clippy::too_many_arguments)]
803fn library_wire(
804    repo: &Path,
805    opts: &WireOptions,
806    mut state: State,
807    crate_dir: &Path,
808    crate_name: String,
809    name: String,
810    switch: String,
811    gate: Option<bool>,
812) -> Result<WireOutcome> {
813    ensure!(
814        opts.commands.is_empty() && opts.routes.is_empty(),
815        "{} is a library: a unit answers its own exports, so wire takes no --command or --route",
816        state.name
817    );
818    let manifest = crate::bridge::Manifest::load(crate_dir).with_context(|| {
819        format!(
820            "a library unit is a crate made by `bridge` (the original package calls it through its bindings), and {} has no manifest",
821            crate_dir.display()
822        )
823    })?;
824    let api = crate::library::api_unit(&state, &manifest.unit)?.clone();
825    let app_dir = repo.join(APP_DIR);
826    let previous = state.units.iter().position(|u| u.name == name);
827    let shadow = crate::library::shadow_for(
828        crate_dir,
829        previous.and_then(|i| state.units[i].shadow.as_deref()),
830    )?;
831    let path = match crate_dir.strip_prefix(repo.join("rust")) {
832        Ok(rel) => format!("../{}", rel.to_string_lossy().replace('\\', "/")),
833        Err(_) => crate_dir.to_string_lossy().into_owned(),
834    };
835    let entry = WiredUnit {
836        name: name.clone(),
837        crate_name: crate_name.clone(),
838        path: path.clone(),
839        commands: Vec::new(),
840        routes: Vec::new(),
841        switch: switch.clone(),
842        unit: Some(api.unit.clone()),
843        shadow: shadow.as_ref().map(|p| p.to_string_lossy().into_owned()),
844        kept: manifest.js_only.iter().map(|j| j.name.clone()).collect(),
845    };
846    match previous {
847        Some(i) => state.units[i] = entry,
848        None => state.units.push(entry),
849    }
850    let cargo_path = app_dir.join("Cargo.toml");
851    let mut doc: DocumentMut = std::fs::read_to_string(&cargo_path)?.parse()?;
852    let mut dep = InlineTable::new();
853    dep.insert("path", path.as_str().into());
854    doc["dependencies"][crate_name.as_str()] = value(dep);
855    std::fs::write(&cargo_path, doc.to_string())?;
856    if manifest.kind == crate::bridge::Kind::Pyo3 {
857        crate::library::allow_python_symbols(&app_dir)?;
858    }
859    let lib = app_dir.join("src/lib.rs");
860    std::fs::write(&lib, crate::library::lib_rs(&state, false))?;
861    rustfmt(&lib);
862    state.save(repo)?;
863    let replay = if opts.check {
864        Some(build_and_replay(repo, &state)?)
865    } else {
866        None
867    };
868    Ok(WireOutcome {
869        shadow,
870        unit: name,
871        crate_dir: crate_dir.to_path_buf(),
872        commands: Vec::new(),
873        routes: Vec::new(),
874        switch,
875        glue: lib,
876        glue_pending: false,
877        gate,
878        replay,
879    })
880}
881
882fn find_unit(repo: &Path, unit: &str) -> Result<PathBuf> {
883    let rust = repo.join("rust");
884    for candidate in [
885        rust.join(unit),
886        rust.join(format!("{unit}-rs")),
887        repo.join(unit),
888        PathBuf::from(unit),
889    ] {
890        if candidate.join("Cargo.toml").is_file() && candidate != repo.join(APP_DIR) {
891            return Ok(candidate.canonical()?);
892        }
893    }
894    let wanted = unit.trim_end_matches('/');
895    if let Ok(entries) = std::fs::read_dir(&rust) {
896        for entry in entries.flatten() {
897            if let Ok(m) = crate::bridge::Manifest::load(&entry.path())
898                && m.unit.trim_end_matches('/') == wanted
899            {
900                return Ok(entry.path().canonical()?);
901            }
902        }
903    }
904    bail!(
905        "no unit crate `{unit}`: give the crate folder (`rust/<name>`, as `bridge` made it) or the unit id"
906    )
907}
908
909pub struct WireOptions<'a> {
910    pub repo: &'a Path,
911    /// Unit crate folder, its name under `rust/`, or the unit id it was bridged from.
912    pub unit: &'a str,
913    /// Commands the unit answers; kept from the last wire when empty.
914    pub commands: &'a [String],
915    /// Servers: routes the unit answers (`GET /users/{id}`, `/path` for any method, `*` for
916    /// everything else); kept from the last wire when empty.
917    pub routes: &'a [String],
918    /// Wire without running `gate` on the unit first (when it just passed).
919    pub skip_gate: bool,
920    pub check: bool,
921}
922
923#[derive(Debug, Serialize)]
924pub struct WireOutcome {
925    /// Libraries: the drop-in the original package imports in place of the unit.
926    pub shadow: Option<PathBuf>,
927    pub unit: String,
928    pub crate_dir: PathBuf,
929    pub commands: Vec<String>,
930    pub routes: Vec<String>,
931    pub switch: String,
932    pub glue: PathBuf,
933    /// The glue file still holds the generated stub.
934    pub glue_pending: bool,
935    pub gate: Option<bool>,
936    pub replay: Option<ReplayOutcome>,
937}
938
939pub fn wire(opts: &WireOptions) -> Result<WireOutcome> {
940    let repo = opts
941        .repo
942        .canonical()
943        .with_context(|| format!("no folder {}", opts.repo.display()))?;
944    let mut state = State::load(&repo)?;
945    ensure!(
946        !state.lifted,
947        "the app is lifted: there is no fallback left to wire around; call the crate from src/units directly"
948    );
949    let app_dir = repo.join(APP_DIR);
950    let crate_dir = find_unit(&repo, opts.unit)?;
951    let manifest_text = std::fs::read_to_string(crate_dir.join("Cargo.toml"))?;
952    let unit_doc: DocumentMut = manifest_text.parse()?;
953    let crate_name = unit_doc
954        .get("package")
955        .and_then(|p| p.get("name"))
956        .and_then(|n| n.as_str())
957        .context("the unit's Cargo.toml has no package name")?
958        .to_string();
959    if let Some(kinds) = unit_doc
960        .get("lib")
961        .and_then(|l| l.get("crate-type"))
962        .and_then(|k| k.as_array())
963    {
964        ensure!(
965            kinds.iter().any(|k| k.as_str() == Some("rlib")),
966            "{crate_name} is not a Rust library: add \"rlib\" to `crate-type` in its Cargo.toml"
967        );
968    }
969    let name = crate_name
970        .strip_suffix("-rs")
971        .unwrap_or(&crate_name)
972        .to_string();
973    let switch = kill_switch(&crate_name);
974
975    let gate = if opts.skip_gate {
976        None
977    } else {
978        let outcome = crate::gate::gate(&crate_dir, &[])?;
979        if !outcome.passed {
980            let failed: Vec<String> = outcome
981                .checks
982                .iter()
983                .filter(|c| !c.passed)
984                .map(|c| c.name.to_string())
985                .collect();
986            bail!(
987                "{crate_name} does not pass gate ({}): run `rust-anything gate {}` and fix it before wiring",
988                failed.join(", "),
989                crate_dir.display()
990            );
991        }
992        Some(true)
993    };
994    if state.kind == AppKind::Library {
995        return library_wire(
996            &repo, opts, state, &crate_dir, crate_name, name, switch, gate,
997        );
998    }
999
1000    let previous = state.units.iter().position(|u| u.name == name);
1001    let http = state.kind == AppKind::Http;
1002    ensure!(
1003        !http || opts.commands.is_empty(),
1004        "{} is a server: name what {name} answers with --route, not --command",
1005        state.name
1006    );
1007    ensure!(
1008        http || opts.routes.is_empty(),
1009        "{} is a CLI: name what {name} answers with --command, not --route",
1010        state.name
1011    );
1012    let routes = if !http {
1013        Vec::new()
1014    } else if opts.routes.is_empty() {
1015        previous
1016            .map(|i| state.units[i].routes.clone())
1017            .filter(|r| !r.is_empty())
1018            .with_context(|| format!("name the routes {name} answers with --route"))?
1019    } else {
1020        http_door::check_routes(&state, &name, opts.routes)?
1021            .iter()
1022            .map(http_door::Route::key)
1023            .collect()
1024    };
1025    let commands = if http {
1026        Vec::new()
1027    } else if opts.commands.is_empty() {
1028        previous
1029            .map(|i| state.units[i].commands.clone())
1030            .with_context(|| format!("name the commands {name} answers with --command"))?
1031    } else {
1032        opts.commands.to_vec()
1033    };
1034    let routable: Vec<&str> = state
1035        .commands
1036        .iter()
1037        .map(String::as_str)
1038        .chain([state.name.as_str()])
1039        .collect();
1040    for command in commands.iter().filter(|_| !http) {
1041        ensure!(
1042            routable.contains(&command.as_str()),
1043            "the front door has no command `{command}` (it has: {}); add it to src/cli.rs and to `commands` in {}",
1044            routable.join(", "),
1045            app_dir.join(STATE_FILE).display()
1046        );
1047        if let Some(other) = state
1048            .units
1049            .iter()
1050            .find(|u| u.name != name && u.commands.contains(command))
1051        {
1052            bail!("`{command}` is already wired to {}", other.name);
1053        }
1054    }
1055    let path = match crate_dir.strip_prefix(repo.join("rust")) {
1056        Ok(rel) => format!("../{}", rel.to_string_lossy().replace('\\', "/")),
1057        Err(_) => crate_dir.to_string_lossy().into_owned(),
1058    };
1059    let entry = WiredUnit {
1060        name: name.clone(),
1061        crate_name: crate_name.clone(),
1062        path: path.clone(),
1063        commands: commands.clone(),
1064        routes: routes.clone(),
1065        switch: switch.clone(),
1066        unit: None,
1067        shadow: None,
1068        kept: Vec::new(),
1069    };
1070    match previous {
1071        Some(i) => state.units[i] = entry,
1072        None => state.units.push(entry),
1073    }
1074
1075    let cargo_path = app_dir.join("Cargo.toml");
1076    let mut doc: DocumentMut = std::fs::read_to_string(&cargo_path)?.parse()?;
1077    let mut dep = InlineTable::new();
1078    dep.insert("path", path.as_str().into());
1079    doc["dependencies"][crate_name.as_str()] = value(dep);
1080    std::fs::write(&cargo_path, doc.to_string())?;
1081
1082    let glue = app_dir
1083        .join("src/units")
1084        .join(format!("{}.rs", ident(&name)));
1085    if !glue.exists() {
1086        let stub = if http {
1087            http_door::glue_rs(&crate_name)
1088        } else {
1089            glue_rs(&crate_name)
1090        };
1091        std::fs::write(&glue, stub)?;
1092    }
1093    let units = if http {
1094        http_door::units_rs(&state, false)
1095    } else {
1096        units_rs(&state)
1097    };
1098    std::fs::write(app_dir.join("src/units/mod.rs"), units)?;
1099    rustfmt(&app_dir.join("src/units/mod.rs"));
1100    state.save(&repo)?;
1101    let glue_pending = is_stub(&std::fs::read_to_string(&glue)?);
1102    let replay = if opts.check {
1103        Some(build_and_replay(&repo, &state)?)
1104    } else {
1105        None
1106    };
1107    Ok(WireOutcome {
1108        shadow: None,
1109        unit: name,
1110        crate_dir,
1111        commands,
1112        routes,
1113        switch,
1114        glue,
1115        glue_pending,
1116        gate,
1117        replay,
1118    })
1119}
1120
1121#[cfg(test)]
1122mod tests {
1123    use super::*;
1124
1125    fn case(args: &[&str], ok: bool) -> (Vec<String>, bool) {
1126        (args.iter().map(|a| a.to_string()).collect(), ok)
1127    }
1128
1129    #[test]
1130    fn commands_and_flags_come_from_successful_cases() {
1131        let (commands, flags) = infer_cli(&[
1132            case(&["div", "7", "2"], true),
1133            case(&["show", "--json", "-v", "x"], true),
1134            case(&["show", "--width=3"], true),
1135            case(&["nope"], false),
1136            case(&["--help"], true),
1137        ]);
1138        assert_eq!(commands, ["div", "show"]);
1139        let show = &flags["show"];
1140        assert!(!show["json"].takes_value);
1141        assert!(show["width"].takes_value);
1142        assert_eq!(show["short-v"].short, Some('v'));
1143        assert!(!flags.contains_key("div") || flags["div"].is_empty());
1144        let (none, root) = infer_cli(&[case(&["-n", "5", "file.txt"], true)]);
1145        assert!(none.is_empty());
1146        assert!(root[""].contains_key("short-n"));
1147    }
1148
1149    #[test]
1150    fn names_are_valid_rust() {
1151        assert_eq!(package_name("My Tool"), "my-tool");
1152        assert_eq!(package_name("7zip"), "app-7zip");
1153        assert_eq!(ident("text-kit"), "text_kit");
1154        assert_eq!(ident("mod"), "unit_mod");
1155    }
1156
1157    #[test]
1158    fn generated_fallback_matches_python_stems_case_insensitively() {
1159        let code = original_rs(&["Python.EXE".to_string()]);
1160        assert!(
1161            code.contains(".any(|candidate| name.eq_ignore_ascii_case(candidate))"),
1162            "{code}"
1163        );
1164        assert!(
1165            code.contains("var_os(\"PYTHONIOENCODING\").is_none()"),
1166            "{code}"
1167        );
1168    }
1169
1170    #[test]
1171    fn units_route_commands_behind_kill_switches() {
1172        let mut state = State {
1173            schema: SCHEMA.to_string(),
1174            name: "tcli".to_string(),
1175            commands: vec!["div".into(), "words".into()],
1176            units: Vec::new(),
1177            lifted: false,
1178            kind: AppKind::Cli,
1179            routes: Vec::new(),
1180            api: Vec::new(),
1181        };
1182        assert!(units_rs(&state).contains("None"));
1183        state.units.push(WiredUnit {
1184            name: "wordcount".into(),
1185            crate_name: "wordcount-rs".into(),
1186            path: "../wordcount-rs".into(),
1187            commands: vec!["words".into()],
1188            routes: Vec::new(),
1189            switch: "RUST_ANYTHING_UNIT_WORDCOUNT".into(),
1190            unit: None,
1191            shadow: None,
1192            kept: Vec::new(),
1193        });
1194        let code = units_rs(&state);
1195        assert!(code.contains("mod wordcount;"), "{code}");
1196        assert!(
1197            code.contains(
1198                "\"words\" if !sent_to_original(\"WORDCOUNT\") => Some(wordcount::run(command, matches)),"
1199            ),
1200            "{code}"
1201        );
1202    }
1203}