cargo-telar 0.2.1

Cargo subcommand for Telar apps: dev server with hot reload, and packaging into native installers.
//! The command-line surface: subcommands, flags and what each one dispatches to.

use clap::{Parser, Subcommand, ValueEnum};

use crate::runner::config::BackendArg;

#[derive(Parser)]
#[command(
    name = "cargo-telar",
    bin_name = "cargo telar",
    disable_help_subcommand = true
)]
pub(crate) struct Cli {
    #[command(subcommand)]
    pub(crate) command: Option<TelarCommand>,
}

#[derive(Subcommand)]
pub(crate) enum TelarCommand {
    /// Create a new project that already names one target
    New(NewArgs),
    /// Start the app with hot reload (default)
    Dev(DevArgs),
    /// Show all component previews with hot reload
    Preview(PreviewArgs),
    /// Build the app for distribution
    Build(BuildArgs),
    /// Render every preview component headlessly and report failures
    Test(TestArgs),
    /// Type-check the project, reporting `.rsx` errors on their own lines
    Check(CheckArgs),
    /// Bake every `.rsx` asset reference into `.telar/assets.rs`, so no project build runs the baker itself
    Bake,
    /// Transpile every `.rsx` into `.telar/build/`, so a project build wires the result instead of producing it
    Transpile,
    /// Check the development environment
    Doctor,
    /// Format every `.rsx` and `.rs` file in the project
    Fmt(FmtArgs),
    /// Rewrite every `.rsx` file into the one value grammar
    Migrate(MigrateArgs),
}

/// The whole of choosing a target: the generated `Cargo.toml` names one and lists the other three, each a single word.
#[derive(clap::Args)]
pub(crate) struct NewArgs {
    /// Directory to create the project in; its last segment is the package name
    pub(crate) path: std::path::PathBuf,
    /// Package name, when it should differ from the directory
    #[arg(long)]
    pub(crate) name: Option<String>,
    /// Target platform the project starts on
    #[arg(long, value_enum, default_value = "desktop")]
    pub(crate) target: Target,
}

/// Idempotent by construction: a file already in the new grammar comes out byte-identical, so running it twice is safe and `--check` is how a CI says a project is migrated.
#[derive(clap::Args)]
pub(crate) struct MigrateArgs {
    /// Report which files would change and exit non-zero, without writing
    #[arg(long)]
    pub(crate) check: bool,
    /// Directories or files to rewrite; defaults to the current directory
    pub(crate) paths: Vec<std::path::PathBuf>,
}

/// `cargo fmt` cannot do this job: it never sees a `.rsx` file, and the `.rs` modules a telar crate declares come out of a macro it does not expand, so it walks into `lib.rs` and stops there — reporting a clean tree it never looked at.
#[derive(clap::Args)]
pub(crate) struct FmtArgs {
    /// Report which files would change and exit non-zero, without writing
    #[arg(long)]
    pub(crate) check: bool,
    /// Directories or files to format; defaults to the current package or workspace
    pub(crate) paths: Vec<std::path::PathBuf>,
}

#[derive(clap::Args)]
pub(crate) struct CommonArgs {
    /// Package to use
    #[arg(short = 'p', long)]
    pub(crate) package: Option<String>,
    /// Additional Cargo features
    #[arg(short = 'F', long, value_name = "FEATURES")]
    pub(crate) features: Option<String>,
    /// Target platform; defaults to the one the package's own `default` feature names
    #[arg(long, value_enum)]
    pub(crate) target: Option<Target>,
    /// Renderer backend
    #[arg(long, value_enum)]
    pub(crate) backend: Option<BackendArg>,
    /// Which renderer a browser build draws with (`--target web`)
    #[arg(long, value_enum)]
    pub(crate) renderer: Option<WebRenderer>,
    /// Extra args passed directly to cargo (after --)
    #[arg(last = true)]
    pub(crate) cargo_args: Vec<String>,
}

/// Flags shared by the hot-reload commands (`dev` and `preview`).
#[derive(clap::Args)]
pub(crate) struct HotArgs {
    #[command(flatten)]
    pub(crate) common: CommonArgs,
    /// Build in release mode
    #[arg(long)]
    pub(crate) release: bool,
    /// Disable hot reload, restart process on changes instead
    #[arg(long)]
    pub(crate) no_hot_reload: bool,
}

#[derive(clap::Args)]
pub(crate) struct DevArgs {
    #[command(flatten)]
    pub(crate) hot: HotArgs,
    /// Devtools overlay
    #[arg(long, value_enum)]
    pub(crate) devtools: Option<DevtoolsArg>,
}

#[derive(clap::Args)]
pub(crate) struct PreviewArgs {
    #[command(flatten)]
    pub(crate) hot: HotArgs,
    /// Preview a specific component by name
    #[arg(long, conflicts_with = "list")]
    pub(crate) component: Option<String>,
    /// List all available previews and exit
    #[arg(long)]
    pub(crate) list: bool,
    /// Render every preview to a PNG in this directory and exit, with no window
    #[arg(long, value_name = "DIR", conflicts_with = "list")]
    pub(crate) png: Option<std::path::PathBuf>,
}

/// `cargo check` cannot do this job: a `.rsx` compiles to a generated file under `.telar/build/`, so every error past the parse stage names a file the author never wrote. The per-line source map beside each generated file is what puts them back, and nothing outside the VS Code extension read it before this.
#[derive(clap::Args)]
pub(crate) struct CheckArgs {
    #[command(flatten)]
    pub(crate) common: CommonArgs,
    /// Check tests, examples and benches too
    #[arg(long)]
    pub(crate) all_targets: bool,
}

#[derive(clap::Args)]
pub(crate) struct TestArgs {
    #[command(flatten)]
    pub(crate) common: CommonArgs,
    /// Build in release mode
    #[arg(long)]
    pub(crate) release: bool,
}

#[derive(clap::Args)]
pub(crate) struct BuildArgs {
    #[command(flatten)]
    pub(crate) common: CommonArgs,
    /// Output package format
    #[arg(long, value_name = "FORMAT")]
    pub(crate) format: Option<BuildFormat>,
}

#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
pub(crate) enum Target {
    /// A native window on Linux, macOS or Windows.
    Desktop,
    /// An Android device or emulator.
    Android,
    /// The terminal the command was run from.
    Tui,
    /// A browser, through WebAssembly.
    Web,
}

impl Target {
    /// The feature name that stands for this target, in both spellings a project can reach it by: its own `[features]` entry and `telar`'s.
    ///
    /// A browser has two of them, told apart by `--renderer`: `--renderer dom` is a build saying it will never draw pixels, and that is worth saying — the canvas renderer brings wgpu and a glyph shaper with it, and neither is reachable from a frame that becomes elements. Anything else keeps both, because `auto` has to be able to choose between them at load time.
    pub(crate) fn feature(self, renderer: Option<WebRenderer>) -> &'static str {
        match self {
            Self::Desktop => "desktop",
            Self::Android => "android",
            Self::Tui => "tui",
            Self::Web => match renderer {
                Some(WebRenderer::Dom) => "web-dom",
                _ => "web",
            },
        }
    }
}

/// How a browser build draws. Not a fallback order: a document is the other way of drawing an interface, and this is the build saying which one it wants. The page can still say otherwise at load time with `?telar-renderer=`.
#[derive(Clone, Copy, ValueEnum)]
pub(crate) enum WebRenderer {
    /// Pixels where the browser offers a GPU adapter, a document where it does not.
    Auto,
    /// Pixels on a canvas, through WebGPU.
    Canvas,
    /// Real elements, laid out by CSS.
    Dom,
}

impl WebRenderer {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Canvas => "canvas",
            Self::Dom => "dom",
        }
    }
}

#[derive(Clone, ValueEnum)]
pub(crate) enum DevtoolsArg {
    On,
    Off,
}

#[derive(Clone, ValueEnum)]
pub(crate) enum BuildFormat {
    Appimage,
    Deb,
    Dmg,
    Nsis,
    Apk,
    Dir,
}