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