cargo-telar 0.2.2

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),
    /// Scaffold a Telar project into an existing directory, without overwriting what's already there
    Init(InitArgs),
    /// 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),
    /// Test every preview and matrix cell headlessly: build and layout, play, accessibility and snapshots
    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,
    /// Package a `[telar] library` with the transpiled artifact a dependency is compiled from, after checking that the package carries all of it and that it answers for the sources; `--workspace` packages every publishable member in one cargo call
    Package(PackageArgs),
    /// Publish a `[telar] library` with the transpiled artifact a dependency is compiled from, after the same checks as `package`; the gitignored artifact does not make `cargo publish` refuse it, and `--workspace` publishes every publishable member in one cargo call
    Publish(PublishArgs),
    /// Check the development environment
    Doctor,
    /// Format every `.rsx` and `.rs` file in the project
    Fmt(FmtArgs),
    /// Apply the migrations a release needs; none exists yet
    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,
    /// Which renderer a `--target web` project starts on (`dom` writes `default = ["web-dom"]`)
    #[arg(long, value_enum)]
    pub(crate) renderer: Option<WebRenderer>,
    /// A `[telar] library` other crates depend on, instead of an application
    #[arg(long, conflicts_with_all = ["target", "renderer"])]
    pub(crate) lib: bool,
}

/// Same scaffold as `new`, into a directory that may already exist and hold files: only a name this would
/// itself write is a conflict, never anything else already sitting there.
#[derive(clap::Args)]
pub(crate) struct InitArgs {
    /// Directory to scaffold into; defaults to the current directory, whose name becomes the package name
    pub(crate) path: Option<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,
    /// Which renderer a `--target web` project starts on (`dom` writes `default = ["web-dom"]`)
    #[arg(long, value_enum)]
    pub(crate) renderer: Option<WebRenderer>,
    /// A `[telar] library` other crates depend on, instead of an application
    #[arg(long, conflicts_with_all = ["target", "renderer"])]
    pub(crate) lib: bool,
}

/// A library is compiled as a dependency from the artifact it ships, so packaging one is transpiling it, checking what `cargo package` would carry, and only then packaging. `--workspace` hands every publishable member to one `cargo package`, so each is verified against the in-tree versions of the others, plain crates and libraries alike.
#[derive(clap::Args)]
pub(crate) struct PackageArgs {
    /// Library to package; defaults to the package in the current directory
    #[arg(short = 'p', long, conflicts_with = "workspace")]
    pub(crate) package: Option<String>,
    /// Every workspace member that may be published, in one cargo call; the libraries among them are checked first
    #[arg(long)]
    pub(crate) workspace: bool,
    /// Only check that each library is ready to package, and exit non-zero when one is not
    #[arg(long)]
    pub(crate) check: bool,
    /// Extra args passed directly to `cargo package` (after --)
    #[arg(last = true)]
    pub(crate) cargo_args: Vec<String>,
}

/// Publishing a library is packaging it, then uploading what was checked: the same selection, transpile and readiness checks as `package`, then one `cargo publish --allow-dirty` over every selected member, which cargo orders by their dependencies on each other and verifies each against the in-tree versions of the rest.
#[derive(clap::Args)]
pub(crate) struct PublishArgs {
    /// Library to publish; defaults to the package in the current directory
    #[arg(short = 'p', long, conflicts_with = "workspace")]
    pub(crate) package: Option<String>,
    /// Every workspace member that may be published, in one cargo call; the libraries among them are checked first
    #[arg(long)]
    pub(crate) workspace: bool,
    /// Run every check and cargo's own, without uploading
    #[arg(long)]
    pub(crate) dry_run: bool,
    /// Extra args passed directly to `cargo publish` (after --), such as `--registry` or `--no-verify`
    #[arg(last = true)]
    pub(crate) cargo_args: Vec<String>,
}

/// Kept so scripts calling it keep working; with no migration to run, the arguments change nothing.
#[derive(clap::Args)]
#[expect(
    dead_code,
    reason = "accepted for compatibility, read once a release ships a migration"
)]
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 migrate; 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, Clone)]
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,
    /// The port a page served for development listens on (`--target web`); without it, 8080 or, when that is taken, a free one
    #[arg(long, value_name = "PORT")]
    pub(crate) port: Option<u16>,
}

#[derive(clap::Args)]
pub(crate) struct DevArgs {
    #[command(flatten)]
    pub(crate) hot: HotArgs,
    /// Devtools overlay: `on` builds the package's optional `telar-devtools` in, `off` leaves it out
    #[arg(long, value_enum)]
    pub(crate) devtools: Option<DevtoolsArg>,
}

#[derive(clap::Args)]
pub(crate) struct PreviewArgs {
    #[command(flatten)]
    pub(crate) hot: HotArgs,
    /// The preview to open, by the id `--list` prints, or a link the workshop copied. With the package's workshop already open, it moves there instead of opening another
    #[arg(value_name = "ID|LINK", conflicts_with_all = ["list", "png"])]
    pub(crate) preview: Option<String>,
    /// Narrow the workshop's sidebar to the previews whose title matches this
    #[arg(long, conflicts_with = "list")]
    pub(crate) component: Option<String>,
    /// List every preview by its id 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>,
    /// Export the workshop as a static site into this directory, with a page at the address of every preview, matrix and docs page (`--target web`)
    #[arg(long, value_name = "DIR", conflicts_with_all = ["list", "png", "preview", "component", "no_hot_reload"])]
    pub(crate) build: Option<std::path::PathBuf>,
    /// The path the exported site is served under, in place of `[telar.web] base`
    #[arg(long, value_name = "PATH", requires = "build")]
    pub(crate) base: Option<String>,
}

/// `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,
    /// Test only the previews, or matrix cells, whose id matches this glob (`*` any run, `?` one character)
    #[arg(long, value_name = "GLOB")]
    pub(crate) preview: Option<String>,
    /// What accessibility findings do: `off` checks nothing, `warn` reports them, `error` fails a preview on any error-level finding
    #[arg(long, value_enum, default_value = "warn")]
    pub(crate) a11y: A11yArg,
    /// Write the snapshot goldens that are missing or no longer match, instead of failing on them
    #[arg(long, conflicts_with = "no_snapshots")]
    pub(crate) update_snapshots: bool,
    /// Take no snapshots
    #[arg(long)]
    pub(crate) no_snapshots: bool,
    /// Also write the run's report to PATH, as `json` (report.json as is) or `junit` (XML)
    #[arg(long, num_args = 2, value_names = ["FORMAT", "PATH"])]
    pub(crate) report: Option<Vec<String>>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
pub(crate) enum A11yArg {
    Off,
    Warn,
    Error,
}

impl A11yArg {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Off => "off",
            Self::Warn => "warn",
            Self::Error => "error",
        }
    }
}

#[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>,
    /// Write every page of a web build ahead of time, readable before the app has loaded (`--target web`)
    #[arg(long)]
    pub(crate) prerender: bool,
}

#[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, Debug, 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,
}