autumn-cli 0.4.0

CLI tool for the Autumn web framework
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! `autumn build` -- compile the app and pre-render static routes.
//!
//! Orchestrates three steps:
//! 1. `cargo build [--release] [-p <package>]` to compile the user's binary.
//! 2. In release mode: fingerprint every file under `static/`, write
//!    content-hashed copies alongside the originals, and emit
//!    `static/.autumn-manifest.json` so the static renderer can resolve
//!    fingerprinted URLs when pre-rendering HTML pages.
//! 3. Run the binary with `AUTUMN_BUILD_STATIC=1` so the runtime renders
//!    static routes to `dist/` instead of starting the HTTP server.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Command;

use sha2::{Digest, Sha256};

/// Run the static build pipeline.
pub fn run(debug: bool, package: Option<&str>) {
    eprintln!("\u{1F342} autumn build\n");

    let profile = if debug { "dev" } else { "release" };
    let mut cargo = Command::new("cargo");
    cargo.arg("build");
    if !debug {
        cargo.arg("--release");
    }
    if let Some(pkg) = package {
        cargo.args(["-p", pkg]);
    }

    eprintln!("Compiling ({profile} profile)...");
    let status = cargo.status().expect("failed to run cargo build");
    if !status.success() {
        eprintln!("\u{2717} Compilation failed");
        std::process::exit(1);
    }

    // Fingerprint before the static renderer so that `asset_url()` inside
    // pre-rendered templates resolves to the new hashed URLs rather than
    // plain paths or stale hashes from a previous build.
    if !debug {
        eprintln!("\nFingerprinting static assets...");
        fingerprint_static_assets();
    }

    let binary = find_binary(debug, package);
    eprintln!("\nRunning static renderer...\n");

    let status = Command::new(&binary)
        .env("AUTUMN_BUILD_STATIC", "1")
        .status()
        .unwrap_or_else(|e| {
            eprintln!("\u{2717} Failed to run {}: {e}", binary.display());
            std::process::exit(1);
        });

    if !status.success() {
        eprintln!("\n\u{2717} Static build failed");
        std::process::exit(1);
    }

    eprintln!("\n\u{1F342} Build complete!");
}

/// Fingerprint every file under `static/`, write content-hashed copies, and
/// emit `static/.autumn-manifest.json`.
fn fingerprint_static_assets() {
    fingerprint_assets_in(Path::new("static"));
}

/// Core fingerprinting implementation.
///
/// Accepts an explicit `static_dir` so both production code (which passes
/// `Path::new("static")` relative to CWD) and tests (which pass an absolute
/// temp-dir path) can exercise the same logic without changing the process CWD.
///
/// For each file `<static_dir>/css/autumn.css` the function:
/// 1. Computes the SHA-256 digest of its contents.
/// 2. Truncates the digest to 8 lowercase hex characters.
/// 3. Writes a copy named `<static_dir>/css/autumn.<hash8>.css`.
/// 4. Records `"css/autumn.css" -> "css/autumn.<hash8>.css"` in the manifest.
///
/// Existing fingerprinted copies recorded in the previous manifest are removed
/// first so stale hashes don't accumulate across builds.
fn fingerprint_assets_in(static_dir: &Path) {
    if !static_dir.exists() {
        return;
    }

    // Remove only the fingerprinted copies recorded in the previous manifest
    // so we never accidentally delete user-authored assets whose names happen
    // to match the `<stem>.<8hex>.<ext>` pattern (e.g. vendor.deadbeef.js).
    remove_previous_fingerprints(static_dir);

    let mut manifest_files: HashMap<String, String> = HashMap::new();
    collect_and_fingerprint(static_dir, static_dir, &mut manifest_files);

    let manifest = serde_json::json!({
        "version": "1",
        "files": manifest_files,
    });

    let manifest_path = static_dir.join(".autumn-manifest.json");
    match serde_json::to_string_pretty(&manifest) {
        Ok(json) => {
            if let Err(e) = std::fs::write(&manifest_path, json) {
                eprintln!("\u{2717} Failed to write asset manifest: {e}");
            } else {
                eprintln!(
                    "  \u{2713} Fingerprinted {} asset(s) \u{2192} {}",
                    manifest_files.len(),
                    manifest_path.display()
                );
            }
        }
        Err(e) => eprintln!("\u{2717} Failed to serialize asset manifest: {e}"),
    }
}

/// Walk `dir` recursively, hash each regular file, write a fingerprinted copy,
/// and record the mapping in `out`.
fn collect_and_fingerprint(root: &Path, dir: &Path, out: &mut HashMap<String, String>) {
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(e) => {
            eprintln!("  \u{26A0} Could not read {}: {e}", dir.display());
            return;
        }
    };

    for entry in entries.flatten() {
        let path = entry.path();
        let file_name = entry.file_name();
        let name_str = file_name.to_string_lossy();

        // Skip hidden files (the manifest itself, .DS_Store, etc.).
        if name_str.starts_with('.') {
            continue;
        }

        if path.is_dir() {
            collect_and_fingerprint(root, &path, out);
            continue;
        }

        // Skip files that already look fingerprinted (safety guard).
        if is_fingerprinted_filename(&name_str) {
            continue;
        }

        let contents = match std::fs::read(&path) {
            Ok(c) => c,
            Err(e) => {
                eprintln!("  \u{26A0} Could not read {}: {e}", path.display());
                continue;
            }
        };

        let hash = {
            let mut hasher = Sha256::new();
            hasher.update(&contents);
            let result = hasher.finalize();
            hex::encode(&result[..4]) // 4 bytes = 8 hex chars
        };

        // Build the fingerprinted filename: stem + hash + extension.
        let stem = path
            .file_stem()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_default();
        let ext = path
            .extension()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_default();
        let fp_name = if ext.is_empty() {
            format!("{stem}.{hash}")
        } else {
            format!("{stem}.{hash}.{ext}")
        };
        let fp_path = path.with_file_name(&fp_name);

        if let Err(e) = std::fs::write(&fp_path, &contents) {
            eprintln!("  \u{26A0} Could not write {}: {e}", fp_path.display());
            continue;
        }

        // Record logical path -> fingerprinted path (both relative to static/).
        if let (Ok(logical), Ok(fingerprinted)) =
            (path.strip_prefix(root), fp_path.strip_prefix(root))
        {
            out.insert(
                logical.to_string_lossy().replace('\\', "/"),
                fingerprinted.to_string_lossy().replace('\\', "/"),
            );
        }
    }
}

/// Delete only the fingerprinted copies that were written by the previous
/// build, identified by the values listed in `static/.autumn-manifest.json`.
///
/// This avoids accidentally removing user-authored assets whose filenames
/// happen to match the `<stem>.<8hex>.<ext>` pattern (e.g. `vendor.deadbeef.js`).
fn remove_previous_fingerprints(static_dir: &Path) {
    let manifest_path = static_dir.join(".autumn-manifest.json");
    let Ok(contents) = std::fs::read_to_string(&manifest_path) else {
        return; // No previous manifest — nothing to clean up.
    };
    let Ok(manifest) = serde_json::from_str::<serde_json::Value>(&contents) else {
        return;
    };
    let Some(files) = manifest["files"].as_object() else {
        return;
    };
    for fingerprinted_rel in files.values() {
        if let Some(rel) = fingerprinted_rel.as_str() {
            // Reject any path that tries to escape the static directory.
            // The manifest is written by this tool and should never contain
            // traversal components, but guard against tampered manifests.
            if rel.contains("..") || Path::new(rel).is_absolute() {
                continue;
            }
            let fp_path = static_dir.join(rel);
            if fp_path.exists() {
                let _ = std::fs::remove_file(&fp_path);
            }
        }
    }
}

/// Returns `true` when `filename` matches either fingerprinted pattern:
/// - `<stem>.<8hex>.<ext>` for files with an extension
/// - `<stem>.<8hex>` for extensionless files (e.g. `CNAME`)
fn is_fingerprinted_filename(filename: &str) -> bool {
    let parts: Vec<&str> = filename.split('.').collect();
    let hash_candidate = match parts.len() {
        n if n >= 3 => parts[n - 2],
        2 => parts[1],
        _ => return false,
    };
    hash_candidate.len() == 8
        && hash_candidate
            .bytes()
            .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}

/// Locate the compiled binary using `cargo metadata`.
///
/// When `package` is `Some`, matches by package name directly.
/// Otherwise falls back to matching the package whose manifest is in
/// the current directory.
fn find_binary(debug: bool, package: Option<&str>) -> PathBuf {
    let output = Command::new("cargo")
        .args(["metadata", "--format-version=1", "--no-deps"])
        .output()
        .expect("failed to run cargo metadata");

    if !output.status.success() {
        eprintln!("\u{2717} Failed to read cargo metadata");
        std::process::exit(1);
    }

    let metadata: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("parse cargo metadata");
    let cwd = std::env::current_dir().expect("current dir");

    resolve_binary_from_metadata(&metadata, debug, package, &cwd).unwrap_or_else(|error| {
        eprintln!("\u{2717} {error}");
        std::process::exit(1);
    })
}

fn resolve_binary_from_metadata(
    metadata: &serde_json::Value,
    debug: bool,
    package: Option<&str>,
    cwd: &Path,
) -> Result<PathBuf, String> {
    let target_dir = metadata["target_directory"]
        .as_str()
        .ok_or("target_directory missing from cargo metadata")?;
    let packages = metadata["packages"]
        .as_array()
        .ok_or("packages missing from cargo metadata")?;

    let matching_packages: Vec<_> = package.map_or_else(
        || {
            packages
                .iter()
                .filter(|pkg| {
                    pkg["manifest_path"]
                        .as_str()
                        .and_then(|manifest| Path::new(manifest).parent())
                        .is_some_and(|dir| dir.starts_with(cwd))
                })
                .collect()
        },
        |pkg_name| {
            packages
                .iter()
                .filter(|pkg| pkg["name"].as_str() == Some(pkg_name))
                .collect()
        },
    );

    let bin_name = matching_packages
        .iter()
        .find_map(|pkg| {
            pkg["targets"].as_array()?.iter().find_map(|t| {
                let is_bin = t["kind"].as_array()?.iter().any(|k| k == "bin");
                if is_bin {
                    t["name"].as_str().map(String::from)
                } else {
                    None
                }
            })
        })
        .ok_or_else(|| {
            package.map_or_else(
                || "no binary target found in current package".to_owned(),
                |pkg_name| format!("no binary target found in package '{pkg_name}'"),
            )
        })?;

    let profile_dir = if debug { "debug" } else { "release" };
    let mut path = PathBuf::from(target_dir);
    path.push(profile_dir);
    path.push(bin_name);

    if cfg!(windows) {
        path.set_extension("exe");
    }

    Ok(path)
}

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

    fn expected_binary(path: &str) -> PathBuf {
        let mut p = PathBuf::from(path);
        if cfg!(windows) {
            p.set_extension("exe");
        }
        p
    }

    fn sample_metadata(target_dir: &str, pkg_name: &str, manifest_dir: &str) -> serde_json::Value {
        serde_json::json!({
            "target_directory": target_dir,
            "packages": [{
                "name": pkg_name,
                "manifest_path": format!("{manifest_dir}/Cargo.toml"),
                "targets": [{
                    "name": pkg_name,
                    "kind": ["bin"],
                    "src_path": format!("{manifest_dir}/src/main.rs")
                }]
            }]
        })
    }

    #[test]
    fn resolve_binary_by_package_name() {
        let metadata = sample_metadata("/tmp/target", "hello", "/projects/hello");
        let result =
            resolve_binary_from_metadata(&metadata, true, Some("hello"), Path::new("/projects"));
        assert_eq!(result.unwrap(), expected_binary("/tmp/target/debug/hello"));
    }

    #[test]
    fn resolve_binary_by_cwd() {
        let metadata = sample_metadata("/tmp/target", "hello", "/projects/hello");
        let result =
            resolve_binary_from_metadata(&metadata, true, None, Path::new("/projects/hello"));
        assert_eq!(result.unwrap(), expected_binary("/tmp/target/debug/hello"));
    }

    #[test]
    fn resolve_binary_uses_release_profile() {
        let metadata = sample_metadata("/tmp/target", "hello", "/projects/hello");
        let result =
            resolve_binary_from_metadata(&metadata, false, Some("hello"), Path::new("/projects"));
        assert_eq!(
            result.unwrap(),
            expected_binary("/tmp/target/release/hello")
        );
    }

    #[test]
    fn resolve_binary_reports_missing_package() {
        let metadata = sample_metadata("/tmp/target", "hello", "/projects/hello");
        let result =
            resolve_binary_from_metadata(&metadata, true, Some("missing"), Path::new("/projects"));
        assert!(result.unwrap_err().contains("package 'missing'"));
    }

    #[test]
    fn resolve_binary_reports_missing_targets() {
        let metadata = serde_json::json!({
            "target_directory": "/tmp/target",
            "packages": [{
                "name": "hello",
                "manifest_path": "/projects/hello/Cargo.toml",
                "targets": []
            }]
        });

        let result =
            resolve_binary_from_metadata(&metadata, true, Some("hello"), Path::new("/projects"));
        assert!(result.unwrap_err().contains("package 'hello'"));
    }

    #[test]
    fn fingerprint_detection_positive() {
        assert!(is_fingerprinted_filename("autumn.a1b2c3d4.css"));
        assert!(is_fingerprinted_filename("app.00000000.js"));
        assert!(is_fingerprinted_filename("logo.deadbeef.png"));
        // extensionless fingerprinted files (e.g. CNAME -> CNAME.<hash>)
        assert!(is_fingerprinted_filename("CNAME.a1b2c3d4"));
        assert!(is_fingerprinted_filename("robots.deadbeef"));
    }

    #[test]
    fn fingerprint_detection_negative() {
        assert!(!is_fingerprinted_filename("autumn.css"));
        assert!(!is_fingerprinted_filename("htmx.min.js"));
        // hash too short
        assert!(!is_fingerprinted_filename("autumn.abc.css"));
        // hash too long
        assert!(!is_fingerprinted_filename("autumn.a1b2c3d4e5.css"));
        // uppercase hex not accepted
        assert!(!is_fingerprinted_filename("autumn.A1B2C3D4.css"));
        // non-hex chars
        assert!(!is_fingerprinted_filename("autumn.zzzzzzzz.css"));
        // bare name with no dot
        assert!(!is_fingerprinted_filename("CNAME"));
    }

    #[test]
    fn fingerprint_static_assets_writes_manifest_and_copies() {
        use tempfile::TempDir;

        let tmp = TempDir::new().unwrap();
        let static_dir = tmp.path().join("static");
        let css_dir = static_dir.join("css");
        std::fs::create_dir_all(&css_dir).unwrap();

        let css_content = b"body { color: red; }";
        std::fs::write(css_dir.join("autumn.css"), css_content).unwrap();

        // Call the inner function directly with an absolute path so the test
        // never touches the process-global CWD (which is racy on all platforms
        // and causes failures on Windows where CWD is a per-process lock).
        fingerprint_assets_in(&static_dir);

        // Manifest must exist.
        let manifest_path = static_dir.join(".autumn-manifest.json");
        assert!(manifest_path.exists(), "manifest must be written");

        let manifest: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&manifest_path).unwrap()).unwrap();

        let files = manifest["files"].as_object().unwrap();
        assert_eq!(files.len(), 1, "one asset fingerprinted");

        let fp = files["css/autumn.css"].as_str().unwrap();
        assert!(
            fp.starts_with("css/autumn."),
            "fingerprinted path has correct prefix"
        );
        assert!(
            std::path::Path::new(fp)
                .extension()
                .is_some_and(|ext| ext.eq_ignore_ascii_case("css")),
            "fingerprinted path has correct extension"
        );

        // The fingerprinted copy must exist.
        assert!(
            static_dir.join(fp).exists(),
            "fingerprinted copy must be written: {fp}"
        );
    }
}