run-what 0.94.0

HTML-first web framework powered by Rust. No JavaScript frameworks, no build steps—just HTML.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! Deploy command — deploy a wwwhat project to production.
//!
//! Supports three targets:
//! - `ssh`: Build release binary, rsync to VPS, install systemd service
//! - `docker`: Generate Dockerfile, build image, optionally push
//! - `static`: Pre-render all pages to static HTML files

use anyhow::{Context, Result};
use dialoguer::{Confirm, Input, Select, theme::ColorfulTheme};
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::process::Command;

use crate::prerender;

// ---------------------------------------------------------------------------
// Deploy configuration (persisted in wwwhat.toml under [deploy])
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DeployConfig {
    pub ssh: Option<SshConfig>,
    pub docker: Option<DockerConfig>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SshConfig {
    pub host: String,
    pub user: String,
    pub remote_dir: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DockerConfig {
    pub image: String,
    pub registry: Option<String>,
}

// ---------------------------------------------------------------------------
// Deploy targets
// ---------------------------------------------------------------------------

/// Deploy to a remote server via SSH + rsync
pub async fn deploy_ssh(
    project_path: &Path,
    host: Option<&str>,
    user: Option<&str>,
    remote_dir: Option<&str>,
    dry_run: bool,
    yes: bool,
) -> Result<()> {
    let toml_path = project_path.join("wwwhat.toml");
    let saved = load_deploy_config(&toml_path);

    // Resolve config: CLI args > saved config > interactive prompt
    let host = resolve_or_prompt(
        host,
        saved
            .as_ref()
            .and_then(|c| c.ssh.as_ref().map(|s| s.host.as_str())),
        "SSH host (e.g., 77.42.22.50)",
    )?;
    let user = resolve_or_prompt(
        user,
        saved
            .as_ref()
            .and_then(|c| c.ssh.as_ref().map(|s| s.user.as_str())),
        "SSH user",
    )?;
    let remote_dir = resolve_or_prompt(
        remote_dir,
        saved
            .as_ref()
            .and_then(|c| c.ssh.as_ref().map(|s| s.remote_dir.as_str())),
        "Remote directory (e.g., /opt/wwwhat)",
    )?;

    // Save config for next time
    save_deploy_config(
        &toml_path,
        &DeployConfig {
            ssh: Some(SshConfig {
                host: host.clone(),
                user: user.clone(),
                remote_dir: remote_dir.clone(),
            }),
            docker: saved.and_then(|c| c.docker),
        },
    )?;

    println!();
    println!("  Deploy to {}@{}:{}", user, host, remote_dir);
    println!();

    if !yes && !dry_run {
        if !Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt("  Proceed with deployment?")
            .default(true)
            .interact()?
        {
            println!("  Deployment cancelled.");
            return Ok(());
        }
    }

    // Step 1: Build release binary
    println!("  Building release binary...");
    let build_cmd = format!("cargo build --release --bin run-what");
    run_cmd(&build_cmd, dry_run)?;

    // Step 2: Rsync project files
    println!("  Syncing project files...");
    let project_str = project_path.to_string_lossy();
    let rsync_cmd = format!(
        "rsync -avz --exclude target --exclude .git --exclude '*.db' --exclude '*.db-journal' -e ssh {src}/ {user}@{host}:{dir}/project/",
        src = project_str,
        user = user,
        host = host,
        dir = remote_dir,
    );
    run_cmd(&rsync_cmd, dry_run)?;

    // Step 3: Copy release binary
    println!("  Copying binary...");
    let scp_cmd = format!(
        "scp target/release/run-what {}@{}:{}/run-what",
        user, host, remote_dir,
    );
    run_cmd(&scp_cmd, dry_run)?;

    // Step 4: Install systemd service
    println!("  Installing systemd service...");
    let service = format!(
        r#"[Unit]
Description=wwwhat web server
After=network.target

[Service]
ExecStart={dir}/run-what dev --path {dir}/project --host 0.0.0.0 --port 8085
Restart=always
WorkingDirectory={dir}

[Install]
WantedBy=multi-user.target"#,
        dir = remote_dir,
    );
    let install_cmd = format!(
        r#"ssh {}@{} "echo '{}' > /etc/systemd/system/wwwhat.service && systemctl daemon-reload && systemctl restart wwwhat""#,
        user,
        host,
        service.replace('\n', "\\n"),
    );
    run_cmd(&install_cmd, dry_run)?;

    println!();
    println!("  Deployment complete!");
    println!();

    Ok(())
}

/// Deploy via Docker — generate Dockerfile, build image, optionally push
pub async fn deploy_docker(
    project_path: &Path,
    image: Option<&str>,
    registry: Option<&str>,
    dry_run: bool,
    yes: bool,
) -> Result<()> {
    let toml_path = project_path.join("wwwhat.toml");
    let saved = load_deploy_config(&toml_path);

    let image = resolve_or_prompt(
        image,
        saved
            .as_ref()
            .and_then(|c| c.docker.as_ref().map(|s| s.image.as_str())),
        "Docker image name (e.g., wwwhat-app)",
    )?;

    // Save config
    save_deploy_config(
        &toml_path,
        &DeployConfig {
            ssh: saved.as_ref().and_then(|c| c.ssh.clone()),
            docker: Some(DockerConfig {
                image: image.clone(),
                registry: registry.map(String::from),
            }),
        },
    )?;

    // Generate Dockerfile if one doesn't exist
    let dockerfile_path = project_path.join("Dockerfile");
    if !dockerfile_path.exists() {
        println!("  Generating Dockerfile...");
        let dockerfile = generate_dockerfile();
        std::fs::write(&dockerfile_path, &dockerfile)?;
        println!("  Created {}", dockerfile_path.display());
    }

    // Generate .dockerignore if one doesn't exist
    let dockerignore_path = project_path.join(".dockerignore");
    if !dockerignore_path.exists() {
        let dockerignore = generate_dockerignore();
        std::fs::write(&dockerignore_path, &dockerignore)?;
        println!("  Created {}", dockerignore_path.display());
    }

    println!();
    println!("  Building Docker image: {}", image);

    if !yes && !dry_run {
        if !Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt("  Proceed with Docker build?")
            .default(true)
            .interact()?
        {
            println!("  Cancelled.");
            return Ok(());
        }
    }

    // Build image
    let build_cmd = format!("docker build -t {} {}", image, project_path.display());
    run_cmd(&build_cmd, dry_run)?;

    // Push if registry specified
    if let Some(reg) = registry {
        let full_tag = format!("{}/{}", reg, image);
        println!("  Tagging and pushing to {}...", reg);
        run_cmd(&format!("docker tag {} {}", image, full_tag), dry_run)?;
        run_cmd(&format!("docker push {}", full_tag), dry_run)?;
    }

    println!();
    println!("  Docker build complete!");
    println!();

    Ok(())
}

/// Deploy as static site — pre-render all pages
pub async fn deploy_static(project_path: &Path, output: &Path, dry_run: bool) -> Result<()> {
    if dry_run {
        println!(
            "  [dry-run] Would pre-render {} to {}",
            project_path.display(),
            output.display()
        );
        return Ok(());
    }

    println!();
    println!("  Building static site...");
    println!();

    let result = prerender::prerender(prerender::PreRenderConfig {
        project_path: project_path.to_path_buf(),
        output_path: output.to_path_buf(),
        minify: true,
    })
    .await?;

    println!();
    println!("  Static site ready!");
    println!("  Pages: {}", result.pages_rendered);
    println!("  Size:  {}", crate::format_bytes(result.total_bytes));
    println!("  Output: {}", output.display());

    if !result.pages_skipped.is_empty() {
        println!("  Skipped:");
        for page in &result.pages_skipped {
            println!("    - {}", page);
        }
    }

    println!();
    println!("  Deploy to any static host:");
    println!(
        "    Cloudflare Pages:  npx wrangler pages deploy {}",
        output.display()
    );
    println!(
        "    Netlify:           netlify deploy --dir {}",
        output.display()
    );
    println!("    Vercel:            vercel --prod {}", output.display());
    println!();

    Ok(())
}

/// Interactive prompt to choose deploy target
pub fn choose_deploy_target() -> Result<String> {
    let choices = &[
        "static  - Pre-render to HTML files (Cloudflare Pages, Netlify, etc.)",
        "ssh     - Deploy to a VPS via SSH (Hetzner, DigitalOcean, etc.)",
        "docker  - Build a Docker image",
    ];

    println!();
    let selection = Select::with_theme(&ColorfulTheme::default())
        .with_prompt("  Choose deploy target")
        .items(choices)
        .default(0)
        .interact()?;

    Ok(match selection {
        0 => "static".to_string(),
        1 => "ssh".to_string(),
        2 => "docker".to_string(),
        _ => unreachable!(),
    })
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Resolve a value from CLI arg, saved config, or interactive prompt
fn resolve_or_prompt(
    cli_value: Option<&str>,
    saved_value: Option<&str>,
    prompt: &str,
) -> Result<String> {
    if let Some(v) = cli_value {
        return Ok(v.to_string());
    }
    if let Some(v) = saved_value {
        return Ok(v.to_string());
    }
    let value: String = Input::with_theme(&ColorfulTheme::default())
        .with_prompt(format!("  {}", prompt))
        .interact_text()?;
    Ok(value)
}

/// Run a shell command, or print it in dry-run mode
fn run_cmd(cmd: &str, dry_run: bool) -> Result<()> {
    if dry_run {
        println!("  [dry-run] {}", cmd);
        return Ok(());
    }

    let status = Command::new("sh")
        .arg("-c")
        .arg(cmd)
        .status()
        .with_context(|| format!("Failed to execute: {}", cmd))?;

    if !status.success() {
        anyhow::bail!(
            "Command failed with exit code {}: {}",
            status.code().unwrap_or(-1),
            cmd
        );
    }

    Ok(())
}

/// Generate an optimized Dockerfile with cargo-chef caching
fn generate_dockerfile() -> String {
    r#"# Multi-stage build with cargo-chef for fast rebuilds
FROM lukemathwalker/cargo-chef:latest-rust-1.85 AS chef
WORKDIR /app

FROM chef AS planner
COPY . .
RUN cargo chef prepare --recipe-path recipe.json

FROM chef AS builder
COPY --from=planner /app/recipe.json recipe.json
RUN cargo chef cook --release --recipe-path recipe.json
COPY . .
RUN cargo build --release --bin run-what

FROM debian:bookworm-slim AS runtime
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
RUN useradd -m -s /bin/bash wwwhat
WORKDIR /app

COPY --from=builder /app/target/release/run-what /usr/local/bin/run-what
COPY . /app/project

USER wwwhat
EXPOSE 8085
CMD ["run-what", "dev", "--path", "/app/project", "--host", "0.0.0.0", "--port", "8085"]
"#
    .to_string()
}

/// Generate a .dockerignore to exclude build artifacts and database files
fn generate_dockerignore() -> String {
    r#"target/
.git/
*.db
*.db-journal
*.db-shm
*.db-wal
"#
    .to_string()
}

/// Load deploy config from wwwhat.toml's [deploy] section
fn load_deploy_config(toml_path: &Path) -> Option<DeployConfig> {
    let content = std::fs::read_to_string(toml_path).ok()?;
    let doc = content.parse::<toml_edit::DocumentMut>().ok()?;
    let deploy = doc.get("deploy")?;
    let deploy_str = deploy.to_string();
    toml::from_str::<DeployConfig>(&deploy_str).ok()
}

/// Save deploy config to wwwhat.toml's [deploy] section (preserving existing content)
fn save_deploy_config(toml_path: &Path, config: &DeployConfig) -> Result<()> {
    let content = std::fs::read_to_string(toml_path).unwrap_or_default();
    let mut doc = content
        .parse::<toml_edit::DocumentMut>()
        .unwrap_or_else(|_| toml_edit::DocumentMut::new());

    // Serialize deploy config to a TOML table
    let deploy_str = toml::to_string(config)?;
    let deploy_doc = deploy_str.parse::<toml_edit::DocumentMut>()?;

    // Replace or insert [deploy] section
    doc["deploy"] = deploy_doc.as_item().clone();

    std::fs::write(toml_path, doc.to_string())?;
    Ok(())
}

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

    #[test]
    fn test_generate_dockerfile() {
        let df = generate_dockerfile();
        assert!(df.contains("cargo-chef"));
        assert!(df.contains("run-what"));
        assert!(df.contains("bookworm-slim"));
        assert!(df.contains("EXPOSE 8085"));
    }

    #[test]
    fn test_deploy_config_roundtrip() {
        let config = DeployConfig {
            ssh: Some(SshConfig {
                host: "1.2.3.4".to_string(),
                user: "root".to_string(),
                remote_dir: "/opt/wwwhat".to_string(),
            }),
            docker: Some(DockerConfig {
                image: "my-app".to_string(),
                registry: Some("ghcr.io/user".to_string()),
            }),
        };
        let serialized = toml::to_string(&config).unwrap();
        let deserialized: DeployConfig = toml::from_str(&serialized).unwrap();
        assert_eq!(deserialized.ssh.as_ref().unwrap().host, "1.2.3.4");
        assert_eq!(deserialized.docker.as_ref().unwrap().image, "my-app");
    }
}