chyabrung-cli 0.2.4

The `chy` command line tool for Chyabrung: scaffolding, dev server with hot reload, builds, generators, migrations and one-command deploys
//! `chy docker`: write a multi-stage Dockerfile, `.dockerignore` and a
//! `docker-compose.yml` that runs the app with PostgreSQL and Redis.

use crate::util::{ok, CliResult};
use std::path::Path;
use std::process::Command;

/// Pinned Tailwind standalone CLI used when the app has `style/app.css`.
const TAILWIND_VERSION: &str = "v4.1.13";
/// Port the app listens on inside the container.
const PORT: u16 = 8000;

/// What the generated files need to know about the app.
#[derive(Debug, Clone, PartialEq)]
pub struct Plan {
    /// Package (and binary) name.
    pub app: String,
    /// Library crate name, for the WASM build.
    pub lib: String,
    /// `rust:<version>-slim-bookworm` tag.
    pub rust_version: String,
    /// Build Tailwind CSS from `style/app.css`.
    pub css: bool,
    /// `wasm-bindgen-cli` version when the app hydrates islands.
    pub wasm_bindgen: Option<String>,
    /// Pass `--locked` (a `Cargo.lock` exists).
    pub locked: bool,
}

/// `chy docker`
pub fn run(force: bool) -> CliResult {
    let cargo = std::fs::read_to_string("Cargo.toml").map_err(|_| "no Cargo.toml here — run inside a Chyabrung app".to_string())?;
    if cargo.contains("workspace = true") {
        return Err("this crate inherits from a parent workspace, so it can't build from its own directory. `chy docker` needs a standalone app like the ones `chy new` creates".into());
    }
    let plan = plan(&cargo)?;
    let files = [
        ("Dockerfile", dockerfile(&plan)),
        (".dockerignore", dockerignore().to_string()),
        ("docker-compose.yml", compose(&plan)),
    ];
    // Check all first so nothing is half-written.
    let existing: Vec<&str> = files.iter().map(|(p, _)| *p).filter(|p| Path::new(p).exists()).collect();
    if !existing.is_empty() && !force {
        return Err(format!("{} already exist{} (use --force to overwrite)", existing.join(", "), if existing.len() == 1 { "s" } else { "" }));
    }
    for (path, content) in files {
        std::fs::write(path, content).map_err(|e| format!("cannot write {path}: {e}"))?;
        ok(&format!("wrote {path}"));
    }
    let warnings = feature_warnings(&cargo);
    for warning in warnings {
        println!("  \x1b[33mnote:\x1b[0m {warning}");
    }
    println!("  next: docker compose up --build   (then open http://localhost:{PORT})");
    Ok(())
}

fn plan(cargo: &str) -> CliResult<Plan> {
    let app = crate::util::package_name()?;
    let table: toml::Table = cargo.parse().map_err(|e| format!("Cargo.toml: {e}"))?;
    let lib = table
        .get("lib")
        .and_then(|l| l.get("name"))
        .and_then(|n| n.as_str())
        .map(str::to_owned)
        .unwrap_or_else(|| app.clone())
        .replace('-', "_");
    let lock = std::fs::read_to_string("Cargo.lock").ok();
    let wasm_bindgen = if crate::build::supports_hydration() {
        let v = lock.as_deref().and_then(|l| locked_version(l, "wasm-bindgen"));
        Some(v.ok_or("this app builds WASM islands; run `cargo generate-lockfile` first so the Dockerfile can pin wasm-bindgen-cli to the same version")?)
    } else {
        None
    };
    Ok(Plan {
        app,
        lib,
        rust_version: rust_version().unwrap_or_else(|| "1".into()),
        css: Path::new("style/app.css").exists(),
        wasm_bindgen,
        locked: lock.is_some(),
    })
}

/// `rustc 1.99.0 (...)` → `1.99`.
fn rust_version() -> Option<String> {
    let out = Command::new("rustc").arg("--version").output().ok()?;
    parse_rust_version(&String::from_utf8_lossy(&out.stdout))
}

fn parse_rust_version(s: &str) -> Option<String> {
    let v = s.split_whitespace().nth(1)?;
    if v.contains('-') {
        return None; // nightly/beta: no matching official image
    }
    let mut parts = v.split('.');
    Some(format!("{}.{}", parts.next()?, parts.next()?))
}

/// The version of `name` in a `Cargo.lock`.
fn locked_version(lock: &str, name: &str) -> Option<String> {
    let t: toml::Table = lock.parse().ok()?;
    t.get("package")?
        .as_array()?
        .iter()
        .find(|p| p.get("name").and_then(|n| n.as_str()) == Some(name))?
        .get("version")?
        .as_str()
        .map(str::to_owned)
}

fn feature_warnings(cargo: &str) -> Vec<String> {
    let dep = cargo.lines().find(|l| l.trim_start().starts_with("chyabrung ") || l.trim_start().starts_with("chyabrung=")).unwrap_or("");
    let full = dep.contains("\"full\"");
    let mut out = Vec::new();
    if !full && !dep.contains("\"postgres\"") {
        out.push("docker-compose.yml points DATABASE_URL at PostgreSQL, but the `postgres` feature is off: run `chy add postgres`".into());
    }
    if !full && !dep.contains("\"redis\"") {
        out.push("Redis is used through REDIS_URL only with the `redis` feature: run `chy add redis` (the app falls back to an in-memory cache without it)".into());
    }
    if cargo.contains("path = ") {
        out.push("Cargo.toml has `path = ...` dependencies; they are outside the Docker build context, so switch them to crates.io versions before building".into());
    }
    out
}

/// The Dockerfile.
pub fn dockerfile(p: &Plan) -> String {
    let locked = if p.locked { " --locked" } else { "" };
    let mut s = format!(
        r#"# syntax=docker/dockerfile:1
# Generated by `chy docker`. Build with `docker compose build` or `docker build .`.
# Cache mounts keep the cargo registry and target/ between builds, so a code
# change only recompiles your crate.

ARG RUST_VERSION={rust}
"#,
        rust = p.rust_version
    );
    if p.css {
        s.push_str(&format!(
            r#"
# ---- CSS: Tailwind standalone CLI ------------------------------------------------
FROM debian:bookworm-slim AS css
ARG TAILWIND_VERSION={TAILWIND_VERSION}
ARG TARGETARCH
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl \
 && rm -rf /var/lib/apt/lists/*
RUN arch=$([ "$TARGETARCH" = "arm64" ] && echo arm64 || echo x64) \
 && curl -fsSL -o /usr/local/bin/tailwindcss \
    "https://github.com/tailwindlabs/tailwindcss/releases/download/${{TAILWIND_VERSION}}/tailwindcss-linux-$arch" \
 && chmod +x /usr/local/bin/tailwindcss
WORKDIR /app
COPY . .
RUN tailwindcss -i style/app.css -o public/app.css --minify
"#
        ));
    }
    s.push_str(
        r#"
# ---- build ---------------------------------------------------------------------
FROM rust:${RUST_VERSION}-slim-bookworm AS build
WORKDIR /app
"#,
    );
    if let Some(v) = &p.wasm_bindgen {
        s.push_str(&format!(
            "RUN rustup target add wasm32-unknown-unknown \\\n && cargo install wasm-bindgen-cli --version {v} --locked\n"
        ));
    }
    s.push_str("COPY . .\n");
    if p.css {
        s.push_str("COPY --from=css /app/public/app.css public/app.css\n");
    }
    s.push_str(&format!(
        r#"RUN --mount=type=cache,target=/usr/local/cargo/registry \
    --mount=type=cache,target=/usr/local/cargo/git \
    --mount=type=cache,target=/app/target \
    set -eu; \
    cargo build --release{locked}; \
    mkdir -p /out/storage; \
    cp target/release/{app} /out/{app}; \
    for p in public migrations templates chyabrung.toml; do \
      if [ -e "$p" ]; then cp -r "$p" /out/; fi; \
    done"#,
        app = p.app
    ));
    if p.wasm_bindgen.is_some() {
        s.push_str(&format!(
            r#"; \
    cargo build --lib --release{locked} --target wasm32-unknown-unknown --no-default-features --features hydrate; \
    wasm-bindgen target/wasm32-unknown-unknown/release/{lib}.wasm --target web \
      --out-dir /out/dist/pkg --out-name app --no-typescript"#,
            lib = p.lib
        ));
    }
    s.push_str(&format!(
        r#"

# ---- runtime: glibc + CA certificates, no shell, runs as non-root ---------------
FROM gcr.io/distroless/cc-debian12:nonroot
WORKDIR /app
COPY --from=build --chown=65532:65532 /out /app
ENV APP_ENV=production \
    APP_HOST=0.0.0.0 \
    APP_PORT={PORT} \
    RUST_LOG=info
EXPOSE {PORT}
USER 65532:65532
ENTRYPOINT ["/app/{app}"]
"#,
        app = p.app
    ));
    s
}

/// Files kept out of the build context.
pub fn dockerignore() -> &'static str {
    "# Generated by `chy docker`\n/target\n/dist\n/storage\n/bin\n/node_modules\n.git\n.env\n.env.*\n!.env.example\n*.db\n*.db-*\nDockerfile\ndocker-compose.yml\n"
}

/// `docker-compose.yml`: app + PostgreSQL + Redis.
pub fn compose(p: &Plan) -> String {
    let db = p.app.replace('-', "_");
    format!(
        r#"# Generated by `chy docker`. Start everything with `docker compose up --build`.
# Values like ${{APP_KEY}} come from your shell or the .env file next to this one.
# For a real server, set APP_KEY and POSTGRES_PASSWORD to fresh secrets.

services:
  app:
    build: .
    ports:
      - "{PORT}:{PORT}"
    environment:
      APP_ENV: production
      APP_HOST: 0.0.0.0
      APP_PORT: "{PORT}"
      APP_KEY: ${{APP_KEY:?set APP_KEY (run `chy key:generate`)}}
      DATABASE_URL: postgres://chyabrung:${{POSTGRES_PASSWORD:-chyabrung}}@db:5432/{db}
      REDIS_URL: redis://redis:6379
      RUST_LOG: ${{RUST_LOG:-info}}
    volumes:
      - storage:/app/storage
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_healthy
    restart: unless-stopped

  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_USER: chyabrung
      POSTGRES_PASSWORD: ${{POSTGRES_PASSWORD:-chyabrung}}
      POSTGRES_DB: {db}
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U chyabrung -d {db}"]
      interval: 5s
      timeout: 3s
      retries: 10
    restart: unless-stopped
    # ports: ["5432:5432"]   # uncomment to reach the database from your machine

  redis:
    image: redis:7-alpine
    command: ["redis-server", "--appendonly", "yes"]
    volumes:
      - redisdata:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 10
    restart: unless-stopped

volumes:
  storage:
  pgdata:
  redisdata:
"#
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    fn plan(css: bool, wasm: bool) -> Plan {
        Plan {
            app: "my-app".into(),
            lib: "my_app".into(),
            rust_version: "1.99".into(),
            css,
            wasm_bindgen: wasm.then(|| "0.2.100".into()),
            locked: true,
        }
    }

    #[test]
    fn plain_dockerfile() {
        let d = dockerfile(&plan(false, false));
        assert!(d.contains("ARG RUST_VERSION=1.99"));
        assert!(d.contains("cargo build --release --locked;"));
        assert!(d.contains("cp target/release/my-app /out/my-app"));
        assert!(d.contains("ENTRYPOINT [\"/app/my-app\"]"));
        assert!(d.contains("APP_HOST=0.0.0.0"));
        assert!(!d.contains("tailwind"));
        assert!(!d.contains("wasm"));
        assert!(!d.contains("{{"), "unescaped braces");
    }

    #[test]
    fn css_and_wasm_dockerfile() {
        let d = dockerfile(&plan(true, true));
        assert!(d.contains("FROM debian:bookworm-slim AS css"));
        assert!(d.contains("releases/download/${TAILWIND_VERSION}/tailwindcss-linux-$arch"));
        assert!(d.contains("COPY --from=css /app/public/app.css public/app.css"));
        assert!(d.contains("cargo install wasm-bindgen-cli --version 0.2.100 --locked"));
        assert!(d.contains("release/my_app.wasm"));
        assert!(d.contains("--out-dir /out/dist/pkg"));
    }

    #[test]
    fn compose_file() {
        let c = compose(&plan(false, false));
        assert!(c.contains("DATABASE_URL: postgres://chyabrung:${POSTGRES_PASSWORD:-chyabrung}@db:5432/my_app"));
        assert!(c.contains("REDIS_URL: redis://redis:6379"));
        assert!(c.contains("condition: service_healthy"));
        assert!(c.contains("APP_KEY: ${APP_KEY:?"));
    }

    #[test]
    fn versions() {
        assert_eq!(parse_rust_version("rustc 1.99.0 (b940084d7 2026-09-28)").as_deref(), Some("1.99"));
        assert_eq!(parse_rust_version("rustc 1.100.0-nightly (abc 2026-11-01)"), None);
        let lock = "version = 4\n[[package]]\nname = \"wasm-bindgen\"\nversion = \"0.2.100\"\n";
        assert_eq!(locked_version(lock, "wasm-bindgen").as_deref(), Some("0.2.100"));
        assert_eq!(locked_version(lock, "serde"), None);
    }

    #[test]
    fn warns_about_missing_features() {
        let w = feature_warnings("[dependencies]\nchyabrung = { version = \"0.1\", features = [\"sqlite\"] }\n");
        assert_eq!(w.len(), 2);
        assert!(feature_warnings("[dependencies]\nchyabrung = { version = \"0.1\", features = [\"full\"] }\n").is_empty());
    }
}