use anyhow::{bail, Context, Result};
use clap::ValueEnum;
use figment::{
providers::{Format, Toml},
Figment,
};
use serde::Deserialize;
use std::{path::Path, process::Command};
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum FrontendDriver {
React,
#[default]
None,
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProjectConfig {
pub frontend: FrontendConfig,
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FrontendConfig {
pub driver: FrontendDriver,
}
impl ProjectConfig {
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\"."),
}
}
}
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 {
pub fn dependencies_installed(self, root: &Path) -> bool {
self == Self::None
|| root
.join(if cfg!(windows) {
"frontend/node_modules/.bin/vite.cmd"
} else {
"frontend/node_modules/.bin/vite"
})
.is_file()
}
pub fn version_command(self, root: &Path) -> Option<Command> {
(self == Self::React).then(|| Pnpm::command(root, &["--version"]))
}
pub fn as_str(self) -> &'static str {
match self {
Self::React => "react",
Self::None => "none",
}
}
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(())
}
pub fn install_command(self, root: &Path) -> Option<Command> {
if self.dependencies_installed(root) {
return None;
}
let mut command = Pnpm::command(root, &["install"]);
if root.join("frontend/pnpm-lock.yaml").is_file() {
command.arg("--frozen-lockfile");
}
Some(command)
}
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)
}
}
}
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!("pnpm-lock.yaml"),
frontend_file!("pnpm-workspace.yaml"),
frontend_file!("tools/api-contracts/package.json"),
frontend_file!("tools/api-contracts/index.mjs"),
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"),
];