autumn-cli 0.10.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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! Tailwind CSS CLI download and verification for `autumn setup`.
//!
//! Downloads the correct platform-specific Tailwind CSS standalone binary,
//! verifies its SHA-256 checksum against the `sha256sums.txt` file published with
//! each release, and installs it to `<target-dir>/autumn/tailwindcss` (or
//! `.exe` on Windows) — `<target-dir>` is `cargo metadata`'s
//! `target_directory`, the same resolution `autumn dev` and the scaffold's
//! generated `build.rs` use, so all three agree when `CARGO_TARGET_DIR` is set.

use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

use sha2::{Digest, Sha256};

/// Pinned Tailwind CSS release version.
///
/// This is now the single pin for BOTH surfaces: the dev loop (`autumn setup`)
/// and the production image, whose generated Dockerfile calls `autumn setup`
/// rather than curling the binary itself (issue #1615). Keep it in step with
/// `TAILWIND_VERSION` in `templates/Dockerfile.tmpl`, which the `autumn new`
/// image still pins directly — a `repo_hygiene`-style test would otherwise be
/// the only thing standing between the two surfaces and a silent version skew.
const TAILWIND_VERSION: &str = "v4.1.4";

/// Base URL for Tailwind CSS release assets.
const RELEASE_BASE_URL: &str = "https://github.com/tailwindlabs/tailwindcss/releases/download";

/// Errors that can occur during the setup process.
#[derive(Debug, thiserror::Error)]
pub enum SetupError {
    /// The current OS/architecture combination is not supported.
    #[error("unsupported platform: os={0}, arch={1}")]
    UnsupportedPlatform(String, String),

    /// A network request failed.
    #[error("download failed: {0}")]
    Download(#[from] reqwest::Error),

    /// The downloaded binary does not match its expected checksum.
    #[error("checksum mismatch: expected {expected}, got {actual}")]
    ChecksumMismatch {
        /// The checksum we expected (from `sha256sums.txt`).
        expected: String,
        /// The checksum we actually computed.
        actual: String,
    },

    /// An I/O operation failed.
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// Failed to parse `sha256sums.txt`.
    #[error("failed to parse checksum file: {0}")]
    ChecksumParse(String),

    /// Could not resolve the Cargo target directory via `cargo metadata`.
    #[error("could not resolve target directory: {0}")]
    TargetDir(String),
}

/// Run the `autumn setup` subcommand.
///
/// Downloads Tailwind CSS to `<target-dir>/autumn/tailwindcss` (or `.exe` on
/// Windows), honoring `CARGO_TARGET_DIR` via `cargo metadata`.
/// If the binary already exists, the version marker names the current pin,
/// and `force` is false, exits early; a stale or missing marker triggers a
/// re-download so a pin bump actually lands (issue #2387).
pub fn run(force: bool) {
    if let Err(e) = execute(force) {
        eprintln!("Error: {e}");
        std::process::exit(1);
    }
}

/// Name of the sidecar file recording which Tailwind pin is on disk.
///
/// `execute` short-circuits only when this marker sits next to the binary and
/// names the current pin. Older CLIs wrote no marker, so a marker-less binary
/// is treated as an unknown version and re-downloaded once — the first run
/// under this CLI self-heals every existing checkout (issue #2387).
const VERSION_MARKER_FILE: &str = ".tailwindcss.version";

/// Read the version marker, if any. The contents are trimmed so a trailing
/// newline (or stray whitespace) never counts as a different version.
fn read_installed_version(marker_path: &Path) -> Option<String> {
    fs::read_to_string(marker_path)
        .ok()
        .map(|s| s.trim().to_owned())
}

/// Record the installed pin next to the binary.
fn write_version_marker(marker_path: &Path) -> Result<(), SetupError> {
    fs::write(marker_path, format!("{TAILWIND_VERSION}\n"))?;
    Ok(())
}

/// The reuse decision: reuse only when NOT forced and the on-disk marker
/// names the current pin. A stale or missing marker means re-download.
fn should_reuse_binary(force: bool, installed: Option<&str>) -> bool {
    !force && installed.is_some_and(|v| v == TAILWIND_VERSION)
}

/// Inner implementation so tests can call this without `process::exit`.
fn execute(force: bool) -> Result<(), SetupError> {
    let binary_name = detect_platform(std::env::consts::OS, std::env::consts::ARCH)?;
    let install_dir = target_autumn_dir()?;
    let dest = install_path(&install_dir);
    let marker_path = install_dir.join(VERSION_MARKER_FILE);

    if !force && dest.exists() {
        let installed = read_installed_version(&marker_path);
        if should_reuse_binary(force, installed.as_deref()) {
            println!(
                "Tailwind CLI {TAILWIND_VERSION} already installed at {}",
                dest.display()
            );
            return Ok(());
        }
        // A stale marker (pin bumped) or no marker at all (binary installed
        // by an older CLI): re-download so the bump actually lands. The
        // re-download self-heals marker-less installs, and the marker written
        // below makes the next run a fast no-op again.
        match installed.as_deref() {
            Some(stale) => println!(
                "Installed Tailwind CLI {stale} does not match pinned {TAILWIND_VERSION}; re-downloading..."
            ),
            None => println!(
                "Tailwind CLI binary has no version marker; re-downloading {TAILWIND_VERSION}..."
            ),
        }
    }

    fs::create_dir_all(&install_dir)?;

    let download_url = format!("{RELEASE_BASE_URL}/{TAILWIND_VERSION}/{binary_name}");
    let checksums_url = format!("{RELEASE_BASE_URL}/{TAILWIND_VERSION}/sha256sums.txt");

    println!("Downloading Tailwind CSS {TAILWIND_VERSION} ({binary_name})...");

    let expected_hash = fetch_expected_checksum(&checksums_url, &binary_name)?;
    let tmp_path = install_dir.join(".tailwindcss.tmp");
    download_with_progress(&download_url, &tmp_path)?;

    let actual_hash = sha256_file(&tmp_path)?;
    verify_checksum(&expected_hash, &actual_hash)?;

    fs::rename(&tmp_path, &dest)?;

    #[cfg(unix)]
    set_executable(&dest)?;

    // Record the pin only once the binary is fully in place: a failed
    // install must never leave a marker for a binary that is not there.
    write_version_marker(&marker_path)?;

    println!(
        "Tailwind CLI {TAILWIND_VERSION} installed to {}",
        dest.display()
    );
    Ok(())
}

/// Return the Tailwind release asset name for the given OS and architecture.
pub fn detect_platform(os: &str, arch: &str) -> Result<String, SetupError> {
    let platform = match (os, arch) {
        ("linux", "x86_64") => "tailwindcss-linux-x64",
        ("linux", "aarch64") => "tailwindcss-linux-arm64",
        ("macos", "x86_64") => "tailwindcss-macos-x64",
        ("macos", "aarch64") => "tailwindcss-macos-arm64",
        ("windows", "x86_64") => "tailwindcss-windows-x64.exe",
        _ => {
            return Err(SetupError::UnsupportedPlatform(
                os.to_owned(),
                arch.to_owned(),
            ));
        }
    };
    Ok(platform.to_owned())
}

fn install_path(dir: &Path) -> PathBuf {
    if cfg!(windows) {
        dir.join("tailwindcss.exe")
    } else {
        dir.join("tailwindcss")
    }
}

/// The `autumn/` install directory, resolved the SAME way `autumn dev` (and
/// the scaffold's generated `build.rs`) resolve it — via `cargo metadata`'s
/// `target_directory` — rather than a `target`-relative literal.
///
/// Before this, `setup` wrote to `./target/autumn` unconditionally while
/// `dev` looked in `$CARGO_TARGET_DIR/autumn` whenever that variable was set
/// (common in CI, shared-cache setups, and workspaces): `setup` would
/// "succeed" while writing the binary somewhere `dev` and the generated
/// `build.rs` would never look, so the CSS rebuild silently never ran.
fn target_autumn_dir() -> Result<PathBuf, SetupError> {
    crate::dev::resolve_target_directory()
        .map(|dir| dir.join("autumn"))
        .map_err(SetupError::TargetDir)
}

fn fetch_expected_checksum(url: &str, binary_name: &str) -> Result<String, SetupError> {
    let body = crate::http::fetch_text(url)?;
    parse_checksum_file(&body, binary_name)
}

pub fn parse_checksum_file(body: &str, binary_name: &str) -> Result<String, SetupError> {
    for line in body.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let mut parts = line.split_whitespace();
        let hash_part = parts.next().unwrap_or_default();
        let file_part = parts.next().unwrap_or_default();

        let file_part = file_part.strip_prefix("./").unwrap_or(file_part);
        if file_part == binary_name {
            if hash_part.len() != 64 || !hash_part.chars().all(|c| c.is_ascii_hexdigit()) {
                return Err(SetupError::ChecksumParse(format!(
                    "expected 64-char hex digest, got: {hash_part}"
                )));
            }
            return Ok(hash_part.to_ascii_lowercase());
        }
    }

    Err(SetupError::ChecksumParse(format!(
        "no checksum found for {binary_name}"
    )))
}

pub fn sha256_file(path: &Path) -> Result<String, SetupError> {
    let data = fs::read(path)?;
    Ok(sha256_bytes(&data))
}

pub fn sha256_bytes(data: &[u8]) -> String {
    let digest = Sha256::digest(data);
    hex::encode(digest)
}

pub fn verify_checksum(expected: &str, actual: &str) -> Result<(), SetupError> {
    if expected == actual {
        Ok(())
    } else {
        Err(SetupError::ChecksumMismatch {
            expected: expected.to_owned(),
            actual: actual.to_owned(),
        })
    }
}

fn download_with_progress(url: &str, dest: &Path) -> Result<(), SetupError> {
    let bytes = crate::http::fetch_bytes(url)?;
    let mut file = fs::File::create(dest)?;
    file.write_all(&bytes)?;
    Ok(())
}

#[cfg(unix)]
fn set_executable(path: &Path) -> Result<(), SetupError> {
    use std::os::unix::fs::PermissionsExt;
    let mut perms = fs::metadata(path)?.permissions();
    let mode = perms.mode() | 0o111;
    perms.set_mode(mode);
    fs::set_permissions(path, perms)?;
    Ok(())
}

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

    #[test]
    fn detect_platform_supported_combinations() {
        let cases = [
            ("linux", "x86_64", "tailwindcss-linux-x64"),
            ("linux", "aarch64", "tailwindcss-linux-arm64"),
            ("macos", "x86_64", "tailwindcss-macos-x64"),
            ("macos", "aarch64", "tailwindcss-macos-arm64"),
            ("windows", "x86_64", "tailwindcss-windows-x64.exe"),
        ];

        for (os, arch, expected) in cases {
            let name = detect_platform(os, arch)
                .unwrap_or_else(|_| panic!("should be supported: {os} {arch}"));
            assert_eq!(name, expected);
        }
    }

    #[test]
    fn detect_unsupported_os() {
        let err = detect_platform("freebsd", "x86_64").unwrap_err();
        assert!(matches!(err, SetupError::UnsupportedPlatform(_, _)));
        assert!(err.to_string().contains("freebsd"));
    }

    #[test]
    fn detect_unsupported_arch() {
        let err = detect_platform("linux", "riscv64").unwrap_err();
        assert!(matches!(err, SetupError::UnsupportedPlatform(_, _)));
        assert!(err.to_string().contains("riscv64"));
    }

    #[test]
    fn sha256_known_value() {
        let hash = sha256_bytes(b"");
        assert_eq!(
            hash,
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
    }

    #[test]
    fn sha256_hello_world() {
        let hash = sha256_bytes(b"hello world\n");
        assert_eq!(
            hash,
            "a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447"
        );
    }

    #[test]
    fn verify_checksum_match() {
        let hash = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789";
        assert!(verify_checksum(hash, hash).is_ok());
    }

    #[test]
    fn verify_checksum_mismatch() {
        let expected = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let actual = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
        let err = verify_checksum(expected, actual).unwrap_err();
        assert!(matches!(err, SetupError::ChecksumMismatch { .. }));
        assert!(err.to_string().contains(expected));
        assert!(err.to_string().contains(actual));
    }

    #[test]
    fn parse_finds_correct_binary() {
        let body = "\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa  ./tailwindcss-linux-x64
a948904f2f0f479b8f8564e9d7a8f22e32d13e73845f1b0ea0e2975a02c8b87f  ./tailwindcss-windows-x64.exe
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb  ./tailwindcss-macos-arm64
";
        let hash = parse_checksum_file(body, "tailwindcss-windows-x64.exe").unwrap();
        assert_eq!(
            hash,
            "a948904f2f0f479b8f8564e9d7a8f22e32d13e73845f1b0ea0e2975a02c8b87f"
        );
    }

    #[test]
    fn parse_works_without_prefix() {
        let body = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa  tailwindcss-linux-x64\n";
        let hash = parse_checksum_file(body, "tailwindcss-linux-x64").unwrap();
        assert_eq!(
            hash,
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        );
    }

    #[test]
    fn parse_uppercase_hex() {
        let body = "A948904F2F0F479B8F8564E9D7A8F22E32D13E73845F1B0EA0E2975A02C8B87F  tailwindcss-linux-x64\n";
        let hash = parse_checksum_file(body, "tailwindcss-linux-x64").unwrap();
        assert_eq!(
            hash,
            "a948904f2f0f479b8f8564e9d7a8f22e32d13e73845f1b0ea0e2975a02c8b87f"
        );
    }

    #[test]
    fn parse_empty_file_fails() {
        let err = parse_checksum_file("", "tailwindcss-linux-x64").unwrap_err();
        assert!(matches!(err, SetupError::ChecksumParse(_)));
    }

    #[test]
    fn parse_missing_binary_fails() {
        let body = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa  tailwindcss-linux-x64\n";
        let err = parse_checksum_file(body, "tailwindcss-windows-x64.exe").unwrap_err();
        assert!(matches!(err, SetupError::ChecksumParse(_)));
        assert!(err.to_string().contains("tailwindcss-windows-x64.exe"));
    }

    #[test]
    fn parse_non_hex_fails() {
        let body = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz  tailwindcss-linux-x64\n";
        let err = parse_checksum_file(body, "tailwindcss-linux-x64").unwrap_err();
        assert!(matches!(err, SetupError::ChecksumParse(_)));
    }

    #[test]
    fn sha256_file_matches_bytes() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        fs::write(tmp.path(), b"test data").unwrap();
        let file_hash = sha256_file(tmp.path()).unwrap();
        let byte_hash = sha256_bytes(b"test data");
        assert_eq!(file_hash, byte_hash);
    }

    #[test]
    fn install_path_is_correct() {
        let dir = Path::new("target/autumn");
        let path = install_path(dir);
        if cfg!(windows) {
            assert_eq!(path, PathBuf::from("target/autumn/tailwindcss.exe"));
        } else {
            assert_eq!(path, PathBuf::from("target/autumn/tailwindcss"));
        }
    }

    #[test]
    fn target_autumn_dir_agrees_with_dev_and_cargo_metadata() {
        // `autumn dev`'s `find_tailwind_cli` and the scaffold's generated
        // `build.rs` both resolve the install directory from the ACTUAL
        // Cargo target directory (via `cargo metadata` / `OUT_DIR`), not a
        // `target`-relative literal. Pinning that `setup` lands on the same
        // `<target_dir>/autumn` — via the same `resolve_target_directory`
        // helper `dev` uses — is what keeps the three from drifting apart
        // again under `CARGO_TARGET_DIR` (issue #2457).
        let dir = target_autumn_dir().expect("resolve target/autumn dir");
        assert_eq!(dir.file_name().and_then(|n| n.to_str()), Some("autumn"));
        assert_eq!(
            dir.parent(),
            crate::dev::resolve_target_directory().ok().as_deref(),
        );
    }

    #[test]
    #[ignore = "requires network access to download Tailwind binary"]
    fn download_and_verify_tailwind() {
        let tmp = tempfile::TempDir::new().unwrap();
        let install_dir = tmp.path().join("target/autumn");
        fs::create_dir_all(&install_dir).unwrap();

        let binary_name = detect_platform(std::env::consts::OS, std::env::consts::ARCH).unwrap();
        let download_url = format!("{RELEASE_BASE_URL}/{TAILWIND_VERSION}/{binary_name}");
        let checksums_url = format!("{RELEASE_BASE_URL}/{TAILWIND_VERSION}/sha256sums.txt");

        let expected_hash = fetch_expected_checksum(&checksums_url, &binary_name).unwrap();
        let dest = install_dir.join(".tailwindcss.tmp");
        download_with_progress(&download_url, &dest).unwrap();

        let actual_hash = sha256_file(&dest).unwrap();
        verify_checksum(&expected_hash, &actual_hash).unwrap();

        let meta = fs::metadata(&dest).unwrap();
        assert!(
            meta.len() > 1_000_000,
            "binary too small: {} bytes",
            meta.len()
        );
    }

    // Issue #2387: a pin bump must replace the binary without --force, while
    // the same-pin second run stays a fast no-op.
    #[test]
    fn reuse_decision_matches_marker_and_force() {
        // Marker names the current pin, not forced: reuse.
        assert!(should_reuse_binary(false, Some(TAILWIND_VERSION)));
        // Stale marker: the pin moved on, so re-download.
        assert!(!should_reuse_binary(false, Some("v4.1.0")));
        // No marker: a binary an older CLI installed is an unknown version.
        assert!(!should_reuse_binary(false, None));
        // --force always re-downloads, even when the marker is current.
        assert!(!should_reuse_binary(true, Some(TAILWIND_VERSION)));
        assert!(!should_reuse_binary(true, None));
    }

    #[test]
    fn version_marker_round_trips() {
        let tmp = tempfile::TempDir::new().unwrap();
        let marker = tmp.path().join(VERSION_MARKER_FILE);

        // Absent marker: unknown install, must not reuse.
        assert_eq!(read_installed_version(&marker), None);
        assert!(!should_reuse_binary(
            false,
            read_installed_version(&marker).as_deref()
        ));

        write_version_marker(&marker).unwrap();
        assert_eq!(
            read_installed_version(&marker).as_deref(),
            Some(TAILWIND_VERSION)
        );
        assert!(should_reuse_binary(
            false,
            read_installed_version(&marker).as_deref()
        ));
    }

    #[test]
    fn stale_version_marker_does_not_reuse() {
        let tmp = tempfile::TempDir::new().unwrap();
        let marker = tmp.path().join(VERSION_MARKER_FILE);
        fs::write(&marker, "v4.1.0\n").unwrap();

        assert_eq!(read_installed_version(&marker).as_deref(), Some("v4.1.0"));
        assert!(!should_reuse_binary(
            false,
            read_installed_version(&marker).as_deref()
        ));
    }

    #[test]
    fn marker_whitespace_does_not_change_the_version() {
        let tmp = tempfile::TempDir::new().unwrap();
        let marker = tmp.path().join(VERSION_MARKER_FILE);
        fs::write(&marker, format!("  {TAILWIND_VERSION}  \n")).unwrap();

        assert_eq!(
            read_installed_version(&marker).as_deref(),
            Some(TAILWIND_VERSION)
        );
        assert!(should_reuse_binary(
            false,
            read_installed_version(&marker).as_deref()
        ));
    }
}