whisker-cli 0.2.2

Whisker CLI: `whisker` and `cargo-whisker` (hybrid) — scaffold, doctor, and dev-loop Whisker apps.
Documentation
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
528
529
530
531
532
533
//! `whisker doctor` — environment health check.
//!
//! Mirrors `expo doctor` / `flutter doctor` in spirit: walk the local
//! machine for the toolchains and artifacts Whisker needs, report each as
//! ok / warning / error, and exit non-zero if any error is found.
//!
//! Each check is a pure inspection — no side effects (no installs, no
//! downloads). The user runs the fix themselves; we only diagnose.
//!
//! ## Output style
//! Section spinners ("Probing Android …") while each group runs, then
//! a fixed-width-aligned list with a small ✓/⚠/✗ glyph at the left.
//! Plain scrollback text — no boxes, no TUI takeover — so the result
//! is easy to copy/paste into an issue or hand to an AI assistant.

use anyhow::Result;
use indicatif::{ProgressBar, ProgressStyle};
use std::path::PathBuf;
use std::process::Command;
use std::time::Duration;

#[derive(clap::Args, Debug)]
pub struct Args {
    /// Skip the iOS section even on macOS hosts.
    #[arg(long)]
    pub no_ios: bool,
    /// Skip the Android section.
    #[arg(long)]
    pub no_android: bool,
}

pub fn run(args: Args) -> Result<()> {
    println!("{BOLD}whisker doctor{RESET}\n");

    let mut report = Report::default();

    report.add_section("Rust toolchain", check_rust);

    if !args.no_android {
        report.add_section("Android", check_android);
    }
    if !args.no_ios {
        report.add_section("iOS", check_ios);
    }

    // No Lynx section: Android pulls the Lynx aar from gradle's
    // `whiskerrs.github.io/lynx/maven` repository, and iOS resolves
    // the four Lynx xcframeworks via SPM's `binaryTarget(url:checksum:)`
    // declarations in `platforms/ios/Package.swift` during xcodebuild's
    // package-resolution step. Neither writes to `~/.cache/whisker/`;
    // the doctor has nothing useful to assert about Lynx before a
    // build runs.

    report.print_summary();
    if report.has_errors() {
        std::process::exit(1);
    }
    Ok(())
}

// ----- Style tokens ---------------------------------------------------------

const C_OK: &str = "\x1b[32m";
const C_WARN: &str = "\x1b[33m";
const C_ERR: &str = "\x1b[31m";
const DIM: &str = "\x1b[2m";
const BOLD: &str = "\x1b[1m";
const RESET: &str = "\x1b[0m";

#[derive(Clone, Copy)]
enum Status {
    Ok,
    Warn,
    Err,
}

struct Check {
    name: String,
    status: Status,
    detail: String,
}

impl Check {
    fn ok(name: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            status: Status::Ok,
            detail: detail.into(),
        }
    }
    fn warn(name: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            status: Status::Warn,
            detail: detail.into(),
        }
    }
    fn err(name: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            status: Status::Err,
            detail: detail.into(),
        }
    }
}

#[derive(Default)]
struct Report {
    ok: usize,
    warn: usize,
    err: usize,
}

impl Report {
    fn add_section<F: FnOnce() -> Vec<Check>>(&mut self, name: &str, body: F) {
        let pb = section_spinner(name);
        let checks = body();
        let (n_ok, n_warn, n_err) = tally(&checks);
        let summary = format!(
            "{n_ok}{n_warn}{n_err}",
            n_ok = n_ok,
            n_warn = n_warn,
            n_err = n_err,
        );
        pb.finish_and_clear();

        // Section header (bold)
        println!("{BOLD}{name}{RESET}  {DIM}{summary}{RESET}");

        // Compute aligned width of names (clamped so very long entries
        // don't push detail off-screen).
        let name_w = checks
            .iter()
            .map(|c| visible_width(&c.name))
            .max()
            .unwrap_or(0)
            .min(40);

        for c in &checks {
            let (glyph, col) = match c.status {
                Status::Ok => ("", C_OK),
                Status::Warn => ("", C_WARN),
                Status::Err => ("", C_ERR),
            };
            let pad = name_w.saturating_sub(visible_width(&c.name));
            let detail = if c.detail.is_empty() {
                String::new()
            } else {
                format!("  {DIM}{}{RESET}", c.detail)
            };
            println!(
                "  {col}{glyph}{RESET}  {name}{pad}{detail}",
                name = c.name,
                pad = " ".repeat(pad),
            );
        }
        println!();

        self.ok += n_ok;
        self.warn += n_warn;
        self.err += n_err;
    }

    fn has_errors(&self) -> bool {
        self.err > 0
    }

    fn print_summary(&self) {
        let total = self.ok + self.warn + self.err;
        match (self.err, self.warn) {
            (0, 0) => println!("{C_OK}{BOLD}all {total} checks passed{RESET}"),
            (0, w) => println!(
                "{total} checks: {C_OK}{}{RESET}  {C_WARN}{w}{RESET}",
                self.ok
            ),
            (e, w) => println!(
                "{total} checks: {C_OK}{}{RESET}  {C_WARN}{w}{RESET}  {C_ERR}{e}{RESET}",
                self.ok
            ),
        }
    }
}

fn tally(checks: &[Check]) -> (usize, usize, usize) {
    let (mut o, mut w, mut e) = (0, 0, 0);
    for c in checks {
        match c.status {
            Status::Ok => o += 1,
            Status::Warn => w += 1,
            Status::Err => e += 1,
        }
    }
    (o, w, e)
}

fn section_spinner(name: &str) -> ProgressBar {
    let pb = ProgressBar::new_spinner();
    pb.set_style(
        ProgressStyle::with_template("{spinner:.cyan}  {msg}")
            .unwrap()
            .tick_strings(&["", "", "", "", "", "", "", "", "", ""]),
    );
    pb.set_message(format!("Probing {name}"));
    pb.enable_steady_tick(Duration::from_millis(80));
    pb
}

/// Visible width of a string ignoring ANSI escapes. Good enough for
/// our short ASCII labels — no full Unicode width tables required.
fn visible_width(s: &str) -> usize {
    let mut w = 0;
    let mut in_esc = false;
    for c in s.chars() {
        if c == '\x1b' {
            in_esc = true;
            continue;
        }
        if in_esc {
            if c.is_ascii_alphabetic() {
                in_esc = false;
            }
            continue;
        }
        w += 1;
    }
    w
}

// ----- Rust toolchain --------------------------------------------------------

fn check_rust() -> Vec<Check> {
    let mut out = Vec::new();

    match run_capture("rustc", &["--version"]) {
        Ok(s) => {
            let line = s.lines().next().unwrap_or("").trim().to_string();
            if let Some(v) = parse_rustc_version(&line) {
                if v >= (1, 85) {
                    out.push(Check::ok("rustc", line));
                } else {
                    out.push(Check::err(
                        "rustc",
                        format!("{line} — Whisker requires 1.85+"),
                    ));
                }
            } else {
                out.push(Check::warn("rustc", line));
            }
        }
        Err(_) => out.push(Check::err("rustc", "not on PATH")),
    }

    match run_capture("cargo", &["--version"]) {
        Ok(s) => out.push(Check::ok(
            "cargo",
            s.lines().next().unwrap_or("").trim().to_string(),
        )),
        Err(_) => out.push(Check::err("cargo", "not on PATH")),
    }

    let installed = run_capture("rustup", &["target", "list", "--installed"]).unwrap_or_default();
    let installed: Vec<&str> = installed.lines().map(str::trim).collect();
    for triple in &[
        "aarch64-linux-android",
        "aarch64-apple-ios",
        "aarch64-apple-ios-sim",
        "x86_64-apple-ios",
    ] {
        if installed.iter().any(|t| t == triple) {
            out.push(Check::ok(format!("rustup target {triple}"), "installed"));
        } else {
            out.push(Check::warn(
                format!("rustup target {triple}"),
                format!("missing — `rustup target add {triple}`"),
            ));
        }
    }

    out
}

fn parse_rustc_version(s: &str) -> Option<(u32, u32)> {
    let rest = s.strip_prefix("rustc ")?;
    let v = rest.split_whitespace().next()?;
    let mut it = v.split('.');
    let major: u32 = it.next()?.parse().ok()?;
    let minor: u32 = it.next()?.parse().ok()?;
    Some((major, minor))
}

// ----- Android ---------------------------------------------------------------

fn check_android() -> Vec<Check> {
    let mut out = Vec::new();

    let android_home = std::env::var_os("ANDROID_HOME")
        .or_else(|| std::env::var_os("ANDROID_SDK_ROOT"))
        .map(PathBuf::from);
    let android_home = match android_home {
        Some(p) if p.is_dir() => {
            out.push(Check::ok("ANDROID_HOME", p.display().to_string()));
            p
        }
        Some(p) => {
            out.push(Check::err(
                "ANDROID_HOME",
                format!("{} does not exist", p.display()),
            ));
            return out;
        }
        None => {
            out.push(Check::err(
                "ANDROID_HOME",
                "not set (`export ANDROID_HOME=$HOME/Library/Android/sdk`)",
            ));
            return out;
        }
    };

    // NDK 21.1.6352462 — pinned because Lynx's gn/ninja toolchain
    // requires that exact version (build_lynx_aar bails otherwise).
    let ndk = android_home.join("ndk/21.1.6352462");
    if ndk.is_dir() {
        out.push(Check::ok("NDK 21.1.6352462", ndk.display().to_string()));
    } else {
        out.push(Check::err(
            "NDK 21.1.6352462",
            "missing — `sdkmanager 'ndk;21.1.6352462'`",
        ));
    }

    // JDK 11 — Lynx's gradle wrapper (6.7.1) refuses anything newer.
    match resolve_jdk11() {
        Some(p) => out.push(Check::ok("JDK 11", p.display().to_string())),
        None => out.push(Check::warn(
            "JDK 11",
            "not found (set WHISKER_JAVA11_HOME) — required for Lynx AAR build only",
        )),
    }

    // adb — required for `whisker run android` / install workflows.
    match which("adb").or_else(|| {
        let cand = android_home.join("platform-tools/adb");
        cand.is_file().then_some(cand)
    }) {
        Some(p) => out.push(Check::ok("adb", p.display().to_string())),
        None => out.push(Check::warn(
            "adb",
            "not on PATH (add $ANDROID_HOME/platform-tools)",
        )),
    }

    out
}

fn resolve_jdk11() -> Option<PathBuf> {
    if let Some(p) = std::env::var_os("WHISKER_JAVA11_HOME").map(PathBuf::from) {
        if p.is_dir() {
            return Some(p);
        }
    }
    let home = std::env::var_os("HOME").map(PathBuf::from)?;
    [
        home.join("work/java11/jdk-11.0.25+9/Contents/Home"),
        home.join("work/java11/jdk-11.0.25+9"),
        PathBuf::from("/Library/Java/JavaVirtualMachines/temurin-11.jdk/Contents/Home"),
    ]
    .into_iter()
    .find(|cand| cand.is_dir())
}

// ----- iOS -------------------------------------------------------------------

fn check_ios() -> Vec<Check> {
    let mut out = Vec::new();
    if !cfg!(target_os = "macos") {
        out.push(Check::warn(
            "host OS",
            "iOS builds require macOS — skipping",
        ));
        return out;
    }

    match run_capture("xcode-select", &["-p"]) {
        Ok(s) => out.push(Check::ok("Xcode", s.trim().to_string())),
        Err(_) => out.push(Check::err(
            "Xcode",
            "command-line tools not configured — `xcode-select --install`",
        )),
    }

    match run_capture("xcrun", &["simctl", "help"]) {
        Ok(_) => out.push(Check::ok("xcrun simctl", "available")),
        Err(_) => out.push(Check::err(
            "xcrun simctl",
            "not available — required for Simulator launches",
        )),
    }

    out
}

// ----- Tiny helpers ----------------------------------------------------------

fn run_capture(cmd: &str, args: &[&str]) -> Result<String> {
    let out = Command::new(cmd).args(args).output()?;
    if !out.status.success() {
        anyhow::bail!("{cmd} exited {}", out.status);
    }
    Ok(String::from_utf8_lossy(&out.stdout).to_string())
}

fn which(cmd: &str) -> Option<PathBuf> {
    let path = std::env::var_os("PATH")?;
    for dir in std::env::split_paths(&path) {
        let cand = dir.join(cmd);
        if cand.is_file() {
            return Some(cand);
        }
    }
    None
}

// =============================================================================
// Tests
// =============================================================================

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

    // ----- parse_rustc_version ------------------------------------------------

    #[test]
    fn parse_rustc_version_extracts_major_minor() {
        assert_eq!(
            parse_rustc_version("rustc 1.91.0 (f8297e351 2025-10-28)"),
            Some((1, 91)),
        );
    }

    #[test]
    fn parse_rustc_version_handles_no_metadata() {
        assert_eq!(parse_rustc_version("rustc 1.85.2"), Some((1, 85)));
    }

    #[test]
    fn parse_rustc_version_handles_pre_release_channel() {
        // Real-world nightly: "rustc 1.93.0-nightly (abc 2026-01-01)"
        assert_eq!(
            parse_rustc_version("rustc 1.93.0-nightly (abcdef 2026-01-01)"),
            Some((1, 93)),
        );
    }

    #[test]
    fn parse_rustc_version_rejects_garbage() {
        assert_eq!(parse_rustc_version(""), None);
        assert_eq!(parse_rustc_version("cargo 1.91.0"), None);
        assert_eq!(parse_rustc_version("rustc not-a-version"), None);
        assert_eq!(parse_rustc_version("rustc 1"), None);
    }

    // ----- visible_width ------------------------------------------------------

    #[test]
    fn visible_width_counts_plain_ascii() {
        assert_eq!(visible_width(""), 0);
        assert_eq!(visible_width("hello"), 5);
    }

    #[test]
    fn visible_width_ignores_ansi_color_escapes() {
        // "\x1b[32m✓\x1b[0m" should report 1 visible char (✓).
        assert_eq!(visible_width("\x1b[32m✓\x1b[0m"), 1);
        // Mixed: "  ✓  hello" -> 10 visible chars.
        assert_eq!(visible_width("  \x1b[32m✓\x1b[0m  hello"), 10);
    }

    #[test]
    fn visible_width_ignores_long_ansi_sequences() {
        // 38;5;n colour selector
        assert_eq!(visible_width("\x1b[38;5;208mhi\x1b[0m"), 2);
    }

    // ----- Check / Status constructors ----------------------------------------

    #[test]
    fn check_constructors_set_status() {
        assert!(matches!(Check::ok("n", "d").status, Status::Ok));
        assert!(matches!(Check::warn("n", "d").status, Status::Warn));
        assert!(matches!(Check::err("n", "d").status, Status::Err));
    }

    #[test]
    fn check_constructors_store_strings() {
        let c = Check::ok("rustc", "1.91.0");
        assert_eq!(c.name, "rustc");
        assert_eq!(c.detail, "1.91.0");
    }

    // ----- tally --------------------------------------------------------------

    #[test]
    fn tally_counts_each_status_bucket() {
        let checks = vec![
            Check::ok("a", ""),
            Check::ok("b", ""),
            Check::warn("c", ""),
            Check::err("d", ""),
            Check::err("e", ""),
            Check::err("f", ""),
        ];
        assert_eq!(tally(&checks), (2, 1, 3));
    }

    #[test]
    fn tally_of_empty_is_all_zero() {
        assert_eq!(tally(&[]), (0, 0, 0));
    }

    // ----- Report::has_errors -------------------------------------------------

    #[test]
    fn report_has_errors_only_when_err_nonzero() {
        let mut r = Report::default();
        assert!(!r.has_errors());
        r.warn = 5;
        assert!(!r.has_errors(), "warnings alone don't constitute errors");
        r.err = 1;
        assert!(r.has_errors());
    }
}