kayro-cli 0.1.0

Create, build, and run Kayro desktop apps for humans and agents
Documentation
use std::path::PathBuf;

use clap::{
    Args, Parser, Subcommand, ValueEnum,
    builder::styling::{AnsiColor, Effects, Styles},
};
use serde::Deserialize;

fn cli_styles() -> Styles {
    Styles::styled()
        .header(AnsiColor::Cyan.on_default() | Effects::BOLD)
        .usage(AnsiColor::Cyan.on_default() | Effects::BOLD)
        .literal(AnsiColor::Cyan.on_default())
        .placeholder(AnsiColor::BrightBlack.on_default())
        .valid(AnsiColor::Green.on_default())
        .invalid(AnsiColor::Yellow.on_default())
        .error(AnsiColor::Red.on_default() | Effects::BOLD)
}

/// Create, build, and run Kayro desktop applications.
#[derive(Debug, Parser)]
#[command(
    name = "kayro",
    version,
    about = "Create, build, and run Kayro desktop applications.",
    long_about = "Create, build, and run native Kayro desktop applications with a Vite frontend.",
    after_help = "Examples:\n  kayro new my-app\n  kayro dev\n  kayro build --arch arm64\n  kayro build --json --dry-run",
    propagate_version = true,
    max_term_width = 100,
    styles = cli_styles()
)]
#[allow(clippy::struct_excessive_bools)]
pub struct Cli {
    /// Emit stable newline-delimited JSON events on stdout.
    #[arg(long, global = true)]
    pub json: bool,

    /// Print the exact execution plan without starting any process.
    #[arg(long, global = true)]
    pub dry_run: bool,

    /// Hide command output while preserving errors and final artifacts.
    #[arg(short, long, global = true, conflicts_with = "verbose")]
    pub quiet: bool,

    /// Show exact subprocess commands and Cargo lifecycle output.
    #[arg(short, long, global = true, conflicts_with = "quiet")]
    pub verbose: bool,

    /// Control colored terminal output.
    #[arg(long, global = true, value_enum, default_value_t = ColorMode::Auto)]
    pub color: ColorMode,

    #[command(subcommand)]
    pub command: KayroCommand,
}

#[derive(Debug, Subcommand)]
pub enum KayroCommand {
    /// Create a complete Kayro app in a new directory.
    New(NewArgs),
    /// Add Kayro to an empty directory or an existing Vite project.
    Init(InitArgs),
    /// Start Vite, wait until it is ready, then run the native app.
    Dev(DevArgs),
    /// Generate types, build Vite, and create native distributables.
    Build(BuildArgs),
}

#[derive(Debug, Args)]
pub struct NewArgs {
    /// Project name. Used for the directory and package names.
    #[arg(value_name = "NAME")]
    pub name: String,

    /// Create the project at this exact path instead of ./NAME.
    #[arg(long, value_name = "DIR")]
    pub directory: Option<PathBuf>,

    #[command(flatten)]
    pub scaffold: ScaffoldOptions,
}

#[derive(Debug, Args)]
pub struct InitArgs {
    /// Directory to initialize.
    #[arg(value_name = "DIR", default_value = ".")]
    pub directory: PathBuf,

    /// Package name. Defaults to the directory name.
    #[arg(long, value_name = "NAME")]
    pub name: Option<String>,

    #[command(flatten)]
    pub scaffold: ScaffoldOptions,
}

#[derive(Debug, Args)]
pub struct ScaffoldOptions {
    /// Human-facing application name.
    #[arg(long, value_name = "NAME")]
    pub app_name: Option<String>,

    /// Reverse-DNS application identifier.
    #[arg(long, value_name = "ID")]
    pub identifier: Option<String>,

    /// Write the project without running Bun or generating Cargo.lock.
    #[arg(long, visible_alias = "skip-install")]
    pub no_install: bool,
}

#[derive(Debug, Args)]
pub struct DevArgs {
    #[command(flatten)]
    pub project: ProjectOptions,

    /// Override the development URL from kayro.toml.
    #[arg(long, value_name = "URL", conflicts_with_all = ["host", "port"])]
    pub dev_url: Option<String>,

    /// Override only the Vite host while keeping the configured scheme and port.
    #[arg(long, value_name = "HOST")]
    pub host: Option<String>,

    /// Override only the Vite port while keeping the configured scheme and host.
    #[arg(long, value_name = "PORT")]
    pub port: Option<u16>,

    /// Seconds to wait for Vite before failing.
    #[arg(long, value_name = "SECONDS", default_value_t = 30)]
    pub ready_timeout: u64,

    /// Skip automatic generation of src/kayro.gen.ts.
    #[arg(long)]
    pub skip_types: bool,

    #[command(flatten)]
    pub cargo: CargoOptions,
}

#[derive(Debug, Args)]
#[allow(clippy::struct_excessive_bools)] // These map directly to independent CLI switches.
pub struct BuildArgs {
    #[command(flatten)]
    pub project: ProjectOptions,

    /// Rust target triple passed directly to Cargo.
    #[arg(long, value_name = "TRIPLE", conflicts_with = "arch")]
    pub target: Option<String>,

    /// Convenience architecture mapped onto the host operating system.
    #[arg(long, value_enum, conflicts_with = "target")]
    pub arch: Option<Architecture>,

    /// Cargo profile. Defaults to release.
    #[arg(long, value_name = "NAME", conflicts_with = "debug")]
    pub profile: Option<String>,

    /// Build with Cargo's dev profile.
    #[arg(long)]
    pub debug: bool,

    /// Override Cargo's target directory.
    #[arg(long, value_name = "DIR")]
    pub target_dir: Option<PathBuf>,

    /// Build only the Vite frontend.
    #[arg(long, conflicts_with = "native_only")]
    pub frontend_only: bool,

    /// Build only the native executable.
    #[arg(long, conflicts_with = "frontend_only")]
    pub native_only: bool,

    /// Skip automatic generation of src/kayro.gen.ts.
    #[arg(long)]
    pub skip_types: bool,

    /// Skip native installer and application bundle generation.
    #[arg(long, conflicts_with_all = ["bundles", "bundle_dir"])]
    pub no_bundle: bool,

    /// Package formats. Defaults to dmg, nsis, or appimage for the target OS.
    #[arg(
        long,
        value_enum,
        value_delimiter = ',',
        value_name = "FORMAT",
        conflicts_with = "frontend_only"
    )]
    pub bundles: Vec<BundleFormat>,

    /// Directory for generated installers and bundles.
    #[arg(long, value_name = "DIR", conflicts_with = "frontend_only")]
    pub bundle_dir: Option<PathBuf>,

    #[command(flatten)]
    pub cargo: CargoOptions,
}

#[derive(Debug, Args)]
pub struct ProjectOptions {
    /// Start project discovery from this directory.
    #[arg(
        long = "project",
        visible_alias = "project-dir",
        value_name = "DIR",
        conflicts_with = "config"
    )]
    pub project_dir: Option<PathBuf>,

    /// Use an explicit kayro.toml file.
    #[arg(long, value_name = "FILE")]
    pub config: Option<PathBuf>,
}

impl BuildArgs {
    pub fn profile(&self) -> &str {
        if self.debug {
            "dev"
        } else {
            self.profile.as_deref().unwrap_or("release")
        }
    }
}

#[derive(Debug, Args)]
pub struct CargoOptions {
    /// Enable one or more Cargo features. May be repeated or comma-separated.
    #[arg(long, value_delimiter = ',', value_name = "FEATURE")]
    pub features: Vec<String>,

    /// Disable Cargo's default features.
    #[arg(long)]
    pub no_default_features: bool,

    /// Allow Cargo.lock updates. Builds are locked by default.
    #[arg(long)]
    pub unlocked: bool,

    /// Run Cargo without accessing the network.
    #[arg(long)]
    pub offline: bool,

    /// Number of parallel Cargo jobs.
    #[arg(short = 'j', long, value_name = "N")]
    pub jobs: Option<usize>,

    /// Select a binary when the native package exposes more than one.
    #[arg(long, value_name = "NAME")]
    pub bin: Option<String>,

    /// Forward an additional argument to Cargo. May be repeated.
    #[arg(long, value_name = "ARG", allow_hyphen_values = true)]
    pub cargo_arg: Vec<String>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub enum Architecture {
    #[value(alias = "arm64")]
    Aarch64,
    #[value(name = "x86_64", alias = "x86-64", alias = "x64", alias = "amd64")]
    X86_64,
    #[value(alias = "x86")]
    I686,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, ValueEnum)]
pub enum ColorMode {
    /// Use colors when writing to an interactive terminal.
    #[default]
    Auto,
    /// Always emit ANSI colors.
    Always,
    /// Never emit ANSI colors.
    Never,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum BundleFormat {
    /// macOS application bundle.
    App,
    /// macOS disk image containing the application bundle.
    Dmg,
    /// Windows NSIS setup executable.
    #[value(alias = "setup")]
    Nsis,
    /// Windows MSI package generated with `WiX`.
    #[value(alias = "wix")]
    #[serde(alias = "wix")]
    Msi,
    /// Linux `AppImage` portable application.
    #[value(name = "appimage", alias = "app-image")]
    AppImage,
    /// Debian package.
    Deb,
}

impl Architecture {
    pub fn rust_name(self) -> &'static str {
        match self {
            Self::Aarch64 => "aarch64",
            Self::X86_64 => "x86_64",
            Self::I686 => "i686",
        }
    }
}

#[cfg(test)]
mod tests {
    use clap::Parser as _;

    use super::*;

    #[test]
    fn global_agent_flags_work_after_the_subcommand() {
        let cli = Cli::try_parse_from(["kayro", "build", "--arch", "arm64", "--json", "--dry-run"])
            .unwrap();

        assert!(cli.json);
        assert!(cli.dry_run);
        let KayroCommand::Build(build) = cli.command else {
            panic!("expected build command");
        };
        assert_eq!(build.arch, Some(Architecture::Aarch64));
        assert_eq!(build.profile(), "release");
    }

    #[test]
    fn target_and_architecture_are_mutually_exclusive() {
        let error = Cli::try_parse_from([
            "kayro",
            "build",
            "--arch",
            "x64",
            "--target",
            "aarch64-apple-darwin",
        ])
        .unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict);
    }

    #[test]
    fn bundle_formats_are_comma_separated_and_have_human_aliases() {
        let cli = Cli::try_parse_from([
            "kayro",
            "build",
            "--bundles",
            "app,dmg,setup,wix,appimage,deb",
        ])
        .unwrap();

        let KayroCommand::Build(build) = cli.command else {
            panic!("expected build command");
        };
        assert_eq!(
            build.bundles,
            [
                BundleFormat::App,
                BundleFormat::Dmg,
                BundleFormat::Nsis,
                BundleFormat::Msi,
                BundleFormat::AppImage,
                BundleFormat::Deb,
            ]
        );
    }

    #[test]
    fn executable_only_mode_conflicts_with_bundle_options() {
        let error =
            Cli::try_parse_from(["kayro", "build", "--no-bundle", "--bundles", "dmg"]).unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict);
    }

    #[test]
    fn new_is_non_interactive_and_fully_configurable() {
        let cli = Cli::try_parse_from([
            "kayro",
            "new",
            "hello-world",
            "--app-name",
            "Hello World",
            "--identifier",
            "dev.example.hello",
            "--no-install",
        ])
        .unwrap();

        let KayroCommand::New(new) = cli.command else {
            panic!("expected new command");
        };
        assert_eq!(new.name, "hello-world");
        assert_eq!(new.scaffold.app_name.as_deref(), Some("Hello World"));
        assert!(new.scaffold.no_install);
    }
}