capy-cli 0.3.0

The command-line interface for the Capy web framework.
Documentation
use anyhow::{bail, Context, Result};
use clap::ValueEnum;
use figment::{
    providers::{Format, Toml},
    Figment,
};
use serde::Deserialize;
use std::{path::Path, process::Command};

/// The frontend stacks supported by Capy.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum FrontendDriver {
    /// Vite, React, and TypeScript.
    React,
    /// A backend-only application (also the default for legacy projects).
    #[default]
    None,
}

/// Small, explicit project metadata loaded from `capy.toml`.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProjectConfig {
    /// Frontend selection. Legacy projects without a manifest are backend-only.
    pub frontend: FrontendConfig,
}

/// Frontend configuration; the directory is conventionally `frontend/`.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FrontendConfig {
    /// Tooling to generate, develop, and build the frontend.
    pub driver: FrontendDriver,
}

impl ProjectConfig {
    /// Load explicit metadata. Never infer a frontend from directory contents.
    pub fn load(root: &Path) -> Result<Self> {
        let path = root.join("capy.toml");
        match std::fs::metadata(&path) {
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
            Err(error) => Err(error).context("Could not read capy.toml"),
            Ok(_) => Figment::from(Toml::file(path))
                .extract()
                .context("Invalid capy.toml. Set [frontend] driver to \"react\" or \"none\"."),
        }
    }
}

// All package-manager-specific execution stays here. More managers can be added
// later without changing the process supervisor or application framework.
struct Pnpm;
impl Pnpm {
    fn command(root: &Path, args: &[&str]) -> Command {
        let mut command = Command::new(if cfg!(windows) { "pnpm.cmd" } else { "pnpm" });
        command.args(args).current_dir(root.join("frontend"));
        command
    }
}

impl FrontendDriver {
    /// Stable value written into project metadata.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::React => "react",
            Self::None => "none",
        }
    }

    /// Check required frontend files before starting any subprocesses.
    pub fn validate(self, root: &Path) -> Result<()> {
        if self == Self::React && !root.join("frontend/package.json").is_file() {
            bail!("Capy expects a React frontend in frontend/. Restore frontend/package.json or set [frontend] driver = \"none\" in capy.toml.");
        }
        Ok(())
    }

    /// Install missing dependencies; honor a committed lockfile when present.
    pub fn install_command(self, root: &Path) -> Option<Command> {
        if self == Self::None || root.join("frontend/node_modules/.bin/vite").is_file() {
            return None;
        }
        let mut command = Pnpm::command(root, &["install"]);
        if root.join("frontend/pnpm-lock.yaml").is_file() {
            command.arg("--frozen-lockfile");
        }
        Some(command)
    }

    /// Vite's development server with its backend origin provided by the CLI.
    pub fn dev_command(self, root: &Path, backend_url: &str, port: u16) -> Option<Command> {
        match self {
            Self::None => None,
            Self::React => {
                let mut command = Pnpm::command(root, &["run", "dev", "--logLevel", "info"]);
                command
                    .env("CAPY_BACKEND_URL", backend_url)
                    .env("CAPY_FRONTEND_PORT", port.to_string());
                Some(command)
            }
        }
    }

    /// Build assets, including TypeScript checking via the package build script.
    pub fn build_command(self, root: &Path) -> Option<Command> {
        match self {
            Self::None => None,
            Self::React => Some(Pnpm::command(root, &["run", "build"])),
        }
    }

    pub(crate) fn files(self) -> &'static [(&'static str, &'static str)] {
        match self {
            Self::None => &[],
            Self::React => REACT_FILES,
        }
    }
}

macro_rules! frontend_file {
    ($path:literal) => {
        (
            concat!("frontend/", $path),
            include_str!(concat!("../templates/frontend/", $path, ".txt")),
        )
    };
}

const REACT_FILES: &[(&str, &str)] = &[
    frontend_file!("package.json"),
    frontend_file!("index.html"),
    frontend_file!("vite.config.ts"),
    frontend_file!("tsconfig.json"),
    frontend_file!("tsconfig.app.json"),
    frontend_file!("tsconfig.node.json"),
    frontend_file!("src/App.tsx"),
    frontend_file!("src/main.tsx"),
    frontend_file!("src/style.css"),
    frontend_file!("src/lib/api.ts"),
    ("frontend/src/components/.gitkeep", ""),
    ("frontend/src/pages/.gitkeep", ""),
    ("frontend/src/hooks/.gitkeep", ""),
    (
        "frontend/public/capy.svg",
        include_str!("../templates/frontend/public/capy.svg"),
    ),
    ("frontend/.gitignore", "/node_modules\n/dist\n*.local\n"),
    ("routes/web.rs", "//! Web routes. React pages use the frontend SPA fallback.\n//! Register explicit HTTP routes here when needed; server-rendered Capy Views\n//! are a future feature.\nuse capy::Routes;\n\n/// Explicit web routes take precedence over the SPA.\npub fn routes() -> Routes {\n    Routes::new()\n}\n"),
];