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