run-what 1.7.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
//! Bundle command: package a What app as a standalone executable project.
//!
//! Generates a Rust project that embeds all project files via `include_bytes!()`.
//! The resulting binary extracts files at runtime, starts the server, and opens a browser.

use anyhow::{Context, Result, bail};
use flate2::Compression;
use flate2::write::GzEncoder;
use std::fs;
use std::path::Path;
use std::process::Command;
use walkdir::WalkDir;

/// Directories to include in the bundle archive.
const BUNDLE_DIRS: &[&str] = &[
    "site",
    "pages", // legacy fallback
    "components",
    "static",
    "layouts",
    "partials",
    "emails",
];

/// Create a standalone bundle from a What project.
///
/// Generates a Rust project at `output/` containing:
/// - `project.tar.gz`: compressed archive of all project files
/// - `Cargo.toml`: depends on `what-core` from crates.io
/// - `src/main.rs`: extracts archive, starts server, opens browser
///
/// If `compile` is true, also runs `cargo build --release` and copies the binary.
pub fn create_bundle(path: &Path, output: &Path, compile: bool) -> Result<()> {
    let project_path = fs::canonicalize(path)
        .with_context(|| format!("Project directory not found: {}", path.display()))?;

    // Verify it's a What project
    let config_path = what_core::resolve_config_path(&project_path);
    if !config_path.exists() {
        bail!(
            "No what.toml (or legacy wwwhat.toml) found in {}. Is this a What project?",
            project_path.display()
        );
    }

    println!("  Bundling project: {}", project_path.display());

    // Create output directory
    fs::create_dir_all(output)
        .with_context(|| format!("Could not create output directory: {}", output.display()))?;
    fs::create_dir_all(output.join("src"))?;

    // Step 1: Create tar.gz archive of project files
    let archive_path = output.join("project.tar.gz");
    let file_count = create_archive(&project_path, &archive_path)?;
    println!("  Archived {} files into project.tar.gz", file_count);

    // Step 2: Generate Cargo.toml
    let cargo_toml = generate_cargo_toml();
    fs::write(output.join("Cargo.toml"), cargo_toml)?;

    // Step 3: Generate src/main.rs
    let main_rs = generate_main_rs();
    fs::write(output.join("src").join("main.rs"), main_rs)?;

    println!("  Generated standalone project at {}", output.display());

    if compile {
        println!("  Compiling release binary...");
        let cargo_toml_path = output.join("Cargo.toml");
        let original_manifest = fs::read_to_string(&cargo_toml_path)?;

        if let Some(local_manifest) = local_compile_manifest(&original_manifest) {
            fs::write(&cargo_toml_path, local_manifest)?;
        }

        let status = Command::new("cargo")
            .arg("build")
            .arg("--release")
            .current_dir(output)
            .status()
            .context("Failed to run cargo build")?;

        fs::write(&cargo_toml_path, original_manifest)?;

        if !status.success() {
            bail!("Compilation failed");
        }

        // Find the binary name from the output directory
        let binary_name = "what-app";
        let binary_src = output.join("target").join("release").join(binary_name);
        if binary_src.exists() {
            let binary_dst = output.join(binary_name);
            fs::copy(&binary_src, &binary_dst)?;
            println!("  Binary ready: {}", binary_dst.display());
        }
    } else {
        println!();
        println!("  To compile:");
        println!("    cd {} && cargo build --release", output.display());
        println!();
        println!(
            "  The binary will be at {}/target/release/what-app",
            output.display()
        );
    }

    Ok(())
}

/// Create a tar.gz archive of all project files.
fn create_archive(project_path: &Path, archive_path: &Path) -> Result<usize> {
    let file = fs::File::create(archive_path)?;
    let enc = GzEncoder::new(file, Compression::default());
    let mut tar = tar::Builder::new(enc);
    let mut count = 0;

    // Add the config file (what.toml, or legacy wwwhat.toml) under its own name
    let config_path = what_core::resolve_config_path(project_path);
    if config_path.exists() {
        let name = config_path.file_name().unwrap().to_string_lossy().into_owned();
        tar.append_path_with_name(&config_path, &name)?;
        count += 1;
    }

    // Add each directory that exists
    for dir_name in BUNDLE_DIRS {
        let dir_path = project_path.join(dir_name);
        if dir_path.is_dir() {
            for entry in WalkDir::new(&dir_path).into_iter().filter_map(|e| e.ok()) {
                let entry_path = entry.path();
                if entry_path.is_file() {
                    let relative = entry_path.strip_prefix(project_path)?;
                    tar.append_path_with_name(entry_path, relative)?;
                    count += 1;
                }
            }
        }
    }

    // Add static directory
    let static_path = project_path.join("static");
    if static_path.is_dir() {
        // Already handled above via BUNDLE_DIRS
    }

    tar.into_inner()?.finish()?;
    Ok(count)
}

/// Generate the Cargo.toml for the standalone project.
fn generate_cargo_toml() -> String {
    let version = env!("CARGO_PKG_VERSION");
    format!(
        r#"[package]
name = "what-app"
version = "0.1.0"
edition = "2021"

[workspace]

[[bin]]
name = "what-app"
path = "src/main.rs"

[dependencies]
what-core = "{version}"
tokio = {{ version = "1", features = ["full"] }}
flate2 = "1"
tar = "0.4"
open = "5"
anyhow = "1"
tracing = "0.1"
tracing-subscriber = {{ version = "0.3", features = ["env-filter"] }}
"#
    )
}

fn local_compile_manifest(manifest: &str) -> Option<String> {
    let cli_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let core_dir = cli_dir.parent()?.join("what-core");

    if !core_dir.join("Cargo.toml").exists() {
        return None;
    }

    Some(format!(
        "{manifest}\n[patch.crates-io]\nwhat-core = {{ path = {:?} }}\n",
        core_dir
    ))
}

/// Generate the main.rs for the standalone project.
fn generate_main_rs() -> String {
    r#"//! Standalone What application.
//! Generated by `run-what bundle`. Edit freely.

use anyhow::Result;
use flate2::read::GzDecoder;
use std::path::PathBuf;
use tar::Archive;
use tracing::warn;

const PROJECT_DATA: &[u8] = include_bytes!("../project.tar.gz");

fn extract_project() -> Result<PathBuf> {
    // Use a stable temp directory based on data hash
    let hash = {
        let mut h: u64 = 5381;
        for &b in &PROJECT_DATA[..PROJECT_DATA.len().min(4096)] {
            h = h.wrapping_mul(33).wrapping_add(b as u64);
        }
        h
    };
    let extract_dir = std::env::temp_dir().join(format!("what-bundle-{:x}", hash));

    // Skip extraction if already done (config packed under either name)
    if what_core::resolve_config_path(&extract_dir).exists() {
        return Ok(extract_dir);
    }

    std::fs::create_dir_all(&extract_dir)?;

    let decoder = GzDecoder::new(PROJECT_DATA);
    let mut archive = Archive::new(decoder);
    archive.unpack(&extract_dir)?;

    Ok(extract_dir)
}

fn setup_persistence(extract_dir: &std::path::Path) -> Result<()> {
    let cwd = std::env::current_dir()?;

    // Ensure data/ and uploads/ directories exist in CWD for persistence
    for dir_name in &["data", "uploads"] {
        let cwd_dir = cwd.join(dir_name);
        let extract_target = extract_dir.join(dir_name);

        // Create the directory in CWD if it doesn't exist
        if !cwd_dir.exists() {
            std::fs::create_dir_all(&cwd_dir)?;
        }

        // Remove any existing dir in extract path and symlink to CWD
        if extract_target.exists() {
            std::fs::remove_dir_all(&extract_target).ok();
        }

        #[cfg(unix)]
        std::os::unix::fs::symlink(&cwd_dir, &extract_target)?;

        #[cfg(windows)]
        std::os::windows::fs::symlink_dir(&cwd_dir, &extract_target)?;
    }

    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::new("info"))
        .with_target(false)
        .compact()
        .init();

    let extract_dir = extract_project()?;
    setup_persistence(&extract_dir)?;

    let config_path = what_core::resolve_config_path(&extract_dir);
    let config = if config_path.exists() {
        what_core::Config::load(&config_path)?
    } else {
        what_core::Config::default()
    };

    let host = config.server.host.clone();
    let port = config.server.port;

    let state = what_core::server::AppState::with_dev_mode(config, extract_dir, false)?;

    if let Err(e) = state.init_datasources().await {
        eprintln!("Failed to initialize datasources: {}", e);
        std::process::exit(1);
    }

    let url = format!("http://{}:{}", host, port);

    println!();
    println!("  What app running!");
    println!();
    println!("  Local:   {}", url);
    println!();
    println!("  Data stored in: {}/data/", std::env::current_dir()?.display());
    println!("  Press Ctrl+C to stop");
    println!();

    // Open browser after a short delay
    let open_url = url.clone();
    tokio::spawn(async move {
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;
        if let Err(e) = open::that(&open_url) {
            warn!("Could not open browser: {}", e);
        }
    });

    let shutdown = async {
        tokio::signal::ctrl_c().await.ok();
    };

    what_core::server::serve_with_shutdown(state, shutdown).await?;

    Ok(())
}
"#
    .to_string()
}

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

    #[test]
    fn test_generate_cargo_toml_pins_current_version() {
        let toml = generate_cargo_toml();
        let version = env!("CARGO_PKG_VERSION");
        assert!(toml.contains(&format!("what-core = \"{}\"", version)));
        assert!(toml.contains("name = \"what-app\""));
    }

    #[test]
    fn test_generate_main_rs_contains_key_elements() {
        let main = generate_main_rs();
        assert!(main.contains("include_bytes!"));
        assert!(main.contains("extract_project"));
        assert!(main.contains("setup_persistence"));
        assert!(main.contains("serve_with_shutdown"));
        assert!(main.contains("open::that"));
    }

    #[test]
    fn test_create_archive_without_config() {
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("test.tar.gz");
        // No wwwhat.toml, but create_archive just archives what exists
        let result = create_archive(dir.path(), &archive_path);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0);
    }

    #[test]
    fn test_create_archive_includes_config() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("what.toml"), "[server]\nport = 8085").unwrap();
        let archive_path = dir.path().join("test.tar.gz");
        let count = create_archive(dir.path(), &archive_path).unwrap();
        assert_eq!(count, 1);
        assert!(archive_path.exists());
    }

    #[test]
    fn test_create_archive_includes_legacy_config_name() {
        // Projects still on the legacy wwwhat.toml name must bundle fine
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("wwwhat.toml"), "[server]\nport = 8085").unwrap();
        let archive_path = dir.path().join("test.tar.gz");
        let count = create_archive(dir.path(), &archive_path).unwrap();
        assert_eq!(count, 1);
    }

    #[test]
    fn test_create_archive_includes_site_dir() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("what.toml"), "[server]").unwrap();
        let site_dir = dir.path().join("site");
        fs::create_dir_all(&site_dir).unwrap();
        fs::write(site_dir.join("index.html"), "<h1>Hello</h1>").unwrap();
        fs::write(site_dir.join("about.html"), "<h1>About</h1>").unwrap();

        let archive_path = dir.path().join("test.tar.gz");
        let count = create_archive(dir.path(), &archive_path).unwrap();
        // what.toml + 2 html files
        assert_eq!(count, 3);
    }

    #[test]
    fn test_bundle_rejects_non_project_dir() {
        let dir = tempfile::tempdir().unwrap();
        let output = dir.path().join("bundle");
        let result = create_bundle(dir.path(), &output, false);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("what.toml"));
    }

    #[test]
    fn test_bundle_creates_complete_project() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("what.toml"), "[server]\nport = 8085").unwrap();
        let site_dir = dir.path().join("site");
        fs::create_dir_all(&site_dir).unwrap();
        fs::write(site_dir.join("index.html"), "<h1>Hello</h1>").unwrap();

        let output = dir.path().join("bundle");
        create_bundle(dir.path(), &output, false).unwrap();

        assert!(output.join("Cargo.toml").exists());
        assert!(output.join("src").join("main.rs").exists());
        assert!(output.join("project.tar.gz").exists());
    }
}