Skip to main content

libcrapapp/
cli.rs

1//! CLI implementation for the `cargo crapapp` subcommand.
2//!
3//! The public entrypoint is [`run_cli`]. It normalizes Cargo subcommand
4//! arguments, parses the command line, and dispatches to the build-manifest and
5//! bundling services.
6
7use std::env;
8use std::ffi::OsString;
9
10use anyhow::Result;
11use clap::{Parser, Subcommand, ValueEnum};
12
13use crate::services::{
14    BuildManifest, BuildManifestFormatter, Builder, CrapManifest, MANIFEST_PATH,
15};
16
17#[derive(Debug, Parser)]
18#[command(name = "crapapp")]
19#[command(about = "Build installers and self-contained app bundles from CRAP.toml")]
20struct Cli {
21    #[command(subcommand)]
22    command: Command,
23}
24
25#[derive(Debug, Subcommand)]
26enum Command {
27    /// Read and validate a CRAP.toml manifest.
28    Inspect {
29        /// Output format.
30        #[arg(short, long, value_enum, default_value_t = OutputFormat::Text)]
31        output: OutputFormat,
32    },
33    /// Build configured cargo packages for configured platform targets.
34    Build,
35}
36
37#[derive(Clone, Copy, Debug, ValueEnum)]
38enum OutputFormat {
39    Text,
40    Json,
41}
42
43pub fn run_cli() -> Result<()> {
44    let cli = Cli::parse_from(cargo_args());
45
46    match cli.command {
47        Command::Inspect { output } => {
48            let manifest = CrapManifest::load(MANIFEST_PATH)?;
49            let build_manifest = BuildManifest::from_crap_manifest(&manifest)?;
50            let output = BuildManifestFormatter::from(output);
51
52            print!("{}", build_manifest.display(output)?);
53        }
54        Command::Build => {
55            let manifest = CrapManifest::load(MANIFEST_PATH)?;
56            let build_manifest = BuildManifest::from_crap_manifest(&manifest)?;
57
58            Builder::new(&build_manifest).build()?;
59        }
60    }
61
62    Ok(())
63}
64
65impl From<OutputFormat> for BuildManifestFormatter {
66    fn from(value: OutputFormat) -> Self {
67        match value {
68            OutputFormat::Text => BuildManifestFormatter::Text,
69            OutputFormat::Json => BuildManifestFormatter::Json,
70        }
71    }
72}
73
74fn cargo_args() -> Vec<OsString> {
75    let mut args = env::args_os();
76    let mut normalized = Vec::new();
77
78    if let Some(bin) = args.next() {
79        normalized.push(bin);
80    }
81
82    match args.next() {
83        Some(arg) if arg == "crapapp" => {}
84        Some(arg) => normalized.push(arg),
85        None => {}
86    }
87
88    normalized.extend(args);
89    normalized
90}