fission-command-run 0.6.1

Run, build, test, logs, devices, and doctor workflows for the fission command
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
use anyhow::{bail, Result};
use fission_command_core::Target;
use std::env;
use std::ffi::OsStr;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Status {
    Ok,
    Warn,
    Error,
}

#[derive(Debug)]
struct Check {
    area: &'static str,
    name: String,
    status: Status,
    detail: String,
    suggestion: Option<String>,
}

impl Check {
    fn ok(area: &'static str, name: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            area,
            name: name.into(),
            status: Status::Ok,
            detail: detail.into(),
            suggestion: None,
        }
    }

    fn warn(
        area: &'static str,
        name: impl Into<String>,
        detail: impl Into<String>,
        suggestion: impl Into<String>,
    ) -> Self {
        Self {
            area,
            name: name.into(),
            status: Status::Warn,
            detail: detail.into(),
            suggestion: Some(suggestion.into()),
        }
    }

    fn error(
        area: &'static str,
        name: impl Into<String>,
        detail: impl Into<String>,
        suggestion: impl Into<String>,
    ) -> Self {
        Self {
            area,
            name: name.into(),
            status: Status::Error,
            detail: detail.into(),
            suggestion: Some(suggestion.into()),
        }
    }
}

pub fn run_doctor(project_dir: &Path, targets: &[Target], strict: bool) -> Result<()> {
    let targets = normalized_targets(targets);
    let mut checks = Vec::new();

    checks.extend(check_project(project_dir, &targets));
    checks.extend(check_rust_targets(&targets));

    if targets.contains(&Target::Web) {
        checks.extend(check_web());
    }
    if targets.contains(&Target::Android) {
        checks.extend(check_android());
    }
    if targets.contains(&Target::Ios) {
        checks.extend(check_ios());
    }

    print_checks(project_dir, &targets, &checks);

    if strict && checks.iter().any(|check| check.status == Status::Error) {
        bail!("fission doctor found required toolchain errors");
    }

    Ok(())
}

fn normalized_targets(targets: &[Target]) -> Vec<Target> {
    if targets.is_empty() {
        return vec![Target::Web, Target::Ios, Target::Android];
    }

    targets.iter().copied().collect()
}

fn check_project(project_dir: &Path, targets: &[Target]) -> Vec<Check> {
    let mut checks = Vec::new();
    let fission_toml = project_dir.join("fission.toml");
    if fission_toml.exists() {
        checks.push(Check::ok(
            "project",
            "fission.toml",
            format!("found {}", fission_toml.display()),
        ));
    } else {
        checks.push(Check::warn(
            "project",
            "fission.toml",
            format!("{} does not exist", fission_toml.display()),
            "run doctor from a Fission app root, or pass --project-dir <path>",
        ));
    }

    for target in targets {
        let path = project_dir.join(target.scaffold_relative_path());
        if path.exists() {
            checks.push(Check::ok(
                "project",
                format!("{} scaffold", target.as_str()),
                format!("found {}", path.display()),
            ));
        } else {
            checks.push(Check::warn(
                "project",
                format!("{} scaffold", target.as_str()),
                format!("{} does not exist", path.display()),
                format!(
                    "run `fission add-target {} --project-dir {}`",
                    target.as_str(),
                    project_dir.display()
                ),
            ));
        }
    }

    checks
}

fn check_rust_targets(targets: &[Target]) -> Vec<Check> {
    let mut checks = Vec::new();
    let Some(rustup) = find_in_path("rustup") else {
        checks.push(Check::error(
            "rust",
            "rustup",
            "rustup is not on PATH",
            "install Rust from https://rustup.rs/ and restart your shell",
        ));
        return checks;
    };

    checks.push(Check::ok(
        "rust",
        "rustup",
        format!("found {}", rustup.display()),
    ));

    let installed = command_stdout(&rustup, ["target", "list", "--installed"])
        .unwrap_or_else(|_| String::new());
    for rust_target in required_rust_targets(targets) {
        if installed.lines().any(|line| line.trim() == rust_target) {
            checks.push(Check::ok(
                "rust",
                rust_target,
                "target is installed".to_string(),
            ));
        } else {
            checks.push(Check::error(
                "rust",
                rust_target,
                "target is not installed".to_string(),
                format!("run `rustup target add {}`", rust_target),
            ));
        }
    }

    checks
}

fn required_rust_targets(targets: &[Target]) -> Vec<&'static str> {
    let mut required = Vec::new();
    if targets.contains(&Target::Web) {
        required.push("wasm32-unknown-unknown");
    }
    if targets.contains(&Target::Android) {
        required.push("aarch64-linux-android");
    }
    if targets.contains(&Target::Ios) {
        required.push("aarch64-apple-ios");
        required.push("aarch64-apple-ios-sim");
    }
    required
}

fn check_web() -> Vec<Check> {
    let mut checks = Vec::new();
    check_command(
        &mut checks,
        "web",
        "wasm-pack",
        "install with `cargo install wasm-pack`",
    );
    check_command(
        &mut checks,
        "web",
        "python3",
        "install Python 3 so generated web scripts can serve the app locally",
    );
    check_node_websocket(&mut checks);

    match detect_chrome() {
        Some(path) => checks.push(Check::ok(
            "web",
            "Chrome/Chromium",
            format!("found {}", path.display()),
        )),
        None => checks.push(Check::warn(
            "web",
            "Chrome/Chromium",
            "no Chrome-compatible browser was detected for headless CDP smoke tests",
            "install Chrome/Chromium, or set FISSION_CHROME=/path/to/chrome",
        )),
    }

    checks
}

fn check_node_websocket(checks: &mut Vec<Check>) {
    let Some(node) = find_in_path("node") else {
        checks.push(Check::error(
            "web",
            "Node.js",
            "node is not on PATH",
            "install Node 22+ so generated browser smoke tests can inspect Chrome CDP console/runtime errors",
        ));
        return;
    };

    let supports_websocket = Command::new(&node)
        .args([
            "-e",
            "process.exit(typeof WebSocket === 'function' ? 0 : 1)",
        ])
        .status()
        .map(|status| status.success())
        .unwrap_or(false);
    if supports_websocket {
        checks.push(Check::ok(
            "web",
            "Node.js WebSocket",
            format!("found {}", node.display()),
        ));
    } else {
        checks.push(Check::error(
            "web",
            "Node.js WebSocket",
            format!(
                "{} does not expose the built-in WebSocket client",
                node.display()
            ),
            "install Node 22+ for Chrome CDP smoke tests",
        ));
    }
}

fn check_android() -> Vec<Check> {
    let mut checks = Vec::new();
    let android_home = detect_android_home();
    if android_home.is_dir() {
        checks.push(Check::ok(
            "android",
            "ANDROID_HOME",
            format!("using {}", android_home.display()),
        ));
    } else {
        checks.push(Check::error(
            "android",
            "ANDROID_HOME",
            format!("{} does not exist", android_home.display()),
            "install Android Studio/SDK, or set ANDROID_HOME to your SDK path",
        ));
        return checks;
    }

    check_file(
        &mut checks,
        "android",
        "adb",
        android_home.join("platform-tools/adb"),
        "install Android platform-tools with sdkmanager",
    );
    check_file(
        &mut checks,
        "android",
        "emulator",
        android_home.join("emulator/emulator"),
        "install the Android emulator package with sdkmanager",
    );
    check_file(
        &mut checks,
        "android",
        "sdkmanager",
        android_home.join("cmdline-tools/latest/bin/sdkmanager"),
        "install Android SDK command-line tools",
    );
    check_file(
        &mut checks,
        "android",
        "avdmanager",
        android_home.join("cmdline-tools/latest/bin/avdmanager"),
        "install Android SDK command-line tools",
    );

    let platforms_dir = android_home.join("platforms");
    match latest_android_api(&platforms_dir) {
        Some(api) => checks.push(Check::ok(
            "android",
            "Android platform",
            format!("latest installed API level is {}", api),
        )),
        None => checks.push(Check::error(
            "android",
            "Android platform",
            format!("no platforms were found under {}", platforms_dir.display()),
            "install one with `sdkmanager \"platforms;android-35\"` or newer",
        )),
    }

    match latest_android_system_image_api(&android_home) {
        Some(api) => checks.push(Check::ok(
            "android",
            "Android emulator image",
            format!("latest installed google_apis arm64 image is API {}", api),
        )),
        None => checks.push(Check::warn(
            "android",
            "Android emulator image",
            format!(
                "no google_apis arm64 emulator image found under {}",
                android_home.join("system-images").display()
            ),
            "install one with `sdkmanager \"system-images;android-35;google_apis;arm64-v8a\"` or set ANDROID_SYSTEM_IMAGE",
        )),
    }

    let build_tools_dir = android_home.join("build-tools");
    match latest_child_dir(&build_tools_dir) {
        Some(path) => checks.push(Check::ok(
            "android",
            "build-tools",
            format!("using {}", path.display()),
        )),
        None => checks.push(Check::error(
            "android",
            "build-tools",
            format!(
                "no build-tools were found under {}",
                build_tools_dir.display()
            ),
            "install build-tools with `sdkmanager \"build-tools;35.0.0\"` or newer",
        )),
    }

    let ndk = detect_android_ndk(&android_home);
    if ndk.is_dir() {
        checks.push(Check::ok(
            "android",
            "Android NDK",
            format!("using {}", ndk.display()),
        ));
    } else {
        checks.push(Check::error(
            "android",
            "Android NDK",
            format!("{} does not exist", ndk.display()),
            "install the NDK with sdkmanager, or set ANDROID_NDK to an installed NDK path",
        ));
        return checks;
    }

    match detect_android_toolchain(&ndk) {
        Some(toolchain) => {
            checks.push(Check::ok(
                "android",
                "NDK LLVM toolchain",
                format!("using {}", toolchain.display()),
            ));
            let min_api = env::var("ANDROID_MIN_API_LEVEL").unwrap_or_else(|_| "24".to_string());
            let clang = toolchain.join(format!("aarch64-linux-android{}-clang", min_api));
            if clang.exists() {
                checks.push(Check::ok(
                    "android",
                    "aarch64 clang",
                    format!("found {}", clang.display()),
                ));
            } else {
                checks.push(Check::error(
                    "android",
                    "aarch64 clang",
                    format!("{} does not exist", clang.display()),
                    "set ANDROID_MIN_API_LEVEL to an API supported by the installed NDK",
                ));
            }
        }
        None => checks.push(Check::error(
            "android",
            "NDK LLVM toolchain",
            format!(
                "no prebuilt LLVM toolchain found under {}",
                ndk.join("toolchains/llvm/prebuilt").display()
            ),
            "set ANDROID_TOOLCHAIN to the NDK LLVM bin directory",
        )),
    }

    checks
}

fn check_ios() -> Vec<Check> {
    let mut checks = Vec::new();
    if !cfg!(target_os = "macos") {
        checks.push(Check::error(
            "ios",
            "macOS host",
            "iOS builds require macOS with Xcode",
            "run iOS packaging on macOS",
        ));
        return checks;
    }

    check_command(
        &mut checks,
        "ios",
        "xcrun",
        "install Xcode and run `xcode-select --install` if command-line tools are missing",
    );

    match command_stdout("xcrun", ["--sdk", "iphonesimulator", "--show-sdk-path"]) {
        Ok(path) if !path.trim().is_empty() => checks.push(Check::ok(
            "ios",
            "iPhoneSimulator SDK",
            path.trim().to_string(),
        )),
        _ => checks.push(Check::error(
            "ios",
            "iPhoneSimulator SDK",
            "xcrun could not resolve the iPhoneSimulator SDK",
            "install Xcode and open it once to finish component installation",
        )),
    }

    match command_stdout("xcrun", ["simctl", "list", "devices", "available", "-j"]) {
        Ok(output) if output.contains("iPhone") => checks.push(Check::ok(
            "ios",
            "iPhone simulator",
            "at least one available iPhone simulator is installed",
        )),
        Ok(_) => checks.push(Check::error(
            "ios",
            "iPhone simulator",
            "simctl did not report any available iPhone simulator",
            "install an iOS simulator runtime from Xcode Settings > Platforms",
        )),
        Err(_) => checks.push(Check::error(
            "ios",
            "simctl",
            "xcrun simctl is not available",
            "install Xcode and ensure xcrun is on PATH",
        )),
    }

    checks
}

fn check_command(checks: &mut Vec<Check>, area: &'static str, name: &str, suggestion: &str) {
    match find_in_path(name) {
        Some(path) => checks.push(Check::ok(area, name, format!("found {}", path.display()))),
        None => checks.push(Check::error(
            area,
            name,
            format!("{} is not on PATH", name),
            suggestion,
        )),
    }
}

fn check_file(
    checks: &mut Vec<Check>,
    area: &'static str,
    name: &str,
    path: PathBuf,
    suggestion: &str,
) {
    if path.exists() {
        checks.push(Check::ok(area, name, format!("found {}", path.display())));
    } else {
        checks.push(Check::error(
            area,
            name,
            format!("{} does not exist", path.display()),
            suggestion,
        ));
    }
}

fn print_checks(project_dir: &Path, targets: &[Target], checks: &[Check]) {
    println!("Fission doctor");
    println!("Project: {}", project_dir.display());
    println!(
        "Targets: {}",
        targets
            .iter()
            .map(|target| target.as_str())
            .collect::<Vec<_>>()
            .join(", ")
    );
    println!();

    for check in checks {
        let marker = match check.status {
            Status::Ok => "[ok]",
            Status::Warn => "[warn]",
            Status::Error => "[error]",
        };
        println!(
            "{} {} - {}: {}",
            marker, check.area, check.name, check.detail
        );
        if let Some(suggestion) = &check.suggestion {
            println!("       suggestion: {}", suggestion);
        }
    }

    let ok = checks
        .iter()
        .filter(|check| check.status == Status::Ok)
        .count();
    let warn = checks
        .iter()
        .filter(|check| check.status == Status::Warn)
        .count();
    let error = checks
        .iter()
        .filter(|check| check.status == Status::Error)
        .count();
    println!();
    println!("Summary: {} ok, {} warnings, {} errors", ok, warn, error);
}

fn command_stdout<I, S>(program: impl AsRef<OsStr>, args: I) -> Result<String>
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    let output = Command::new(program).args(args).output()?;
    if !output.status.success() {
        bail!("command exited with {}", output.status);
    }
    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

fn find_in_path(name: &str) -> Option<PathBuf> {
    let explicit = Path::new(name);
    if explicit.components().count() > 1 && explicit.exists() {
        return Some(explicit.to_path_buf());
    }

    let path = env::var_os("PATH")?;
    for dir in env::split_paths(&path) {
        let candidate = dir.join(name);
        if candidate.exists() {
            return Some(candidate);
        }
        #[cfg(windows)]
        {
            let candidate = dir.join(format!("{}.exe", name));
            if candidate.exists() {
                return Some(candidate);
            }
        }
    }
    None
}

fn detect_chrome() -> Option<PathBuf> {
    for var in ["FISSION_CHROME", "CHROME", "CHROME_BIN"] {
        if let Ok(value) = env::var(var) {
            let path = PathBuf::from(value);
            if path.exists() {
                return Some(path);
            }
        }
    }

    for name in ["google-chrome", "chromium", "chromium-browser", "chrome"] {
        if let Some(path) = find_in_path(name) {
            return Some(path);
        }
    }

    for path in [
        "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
        "/Applications/Chromium.app/Contents/MacOS/Chromium",
        "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
    ] {
        let path = PathBuf::from(path);
        if path.exists() {
            return Some(path);
        }
    }

    None
}

fn detect_android_home() -> PathBuf {
    if let Ok(value) = env::var("ANDROID_HOME").or_else(|_| env::var("ANDROID_SDK_ROOT")) {
        return PathBuf::from(value);
    }
    default_android_home()
}

fn default_android_home() -> PathBuf {
    let home = env::var_os("HOME")
        .or_else(|| env::var_os("USERPROFILE"))
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("."));

    if cfg!(target_os = "macos") {
        home.join("Library/Android/sdk")
    } else if cfg!(target_os = "windows") {
        env::var_os("LOCALAPPDATA")
            .map(PathBuf::from)
            .unwrap_or(home)
            .join("Android/Sdk")
    } else {
        home.join("Android/Sdk")
    }
}

fn detect_android_ndk(android_home: &Path) -> PathBuf {
    if let Ok(value) = env::var("ANDROID_NDK").or_else(|_| env::var("ANDROID_NDK_HOME")) {
        return PathBuf::from(value);
    }
    latest_child_dir(&android_home.join("ndk")).unwrap_or_else(|| android_home.join("ndk"))
}

fn detect_android_toolchain(ndk: &Path) -> Option<PathBuf> {
    if let Ok(value) = env::var("ANDROID_TOOLCHAIN") {
        let path = PathBuf::from(value);
        if path.exists() {
            return Some(path);
        }
    }

    let prebuilt = ndk.join("toolchains/llvm/prebuilt");
    for host in android_host_candidates() {
        let path = prebuilt.join(host).join("bin");
        if path.exists() {
            return Some(path);
        }
    }

    latest_child_dir(&prebuilt).map(|path| path.join("bin"))
}

fn android_host_candidates() -> Vec<&'static str> {
    if cfg!(target_os = "macos") {
        vec!["darwin-aarch64", "darwin-x86_64"]
    } else if cfg!(target_os = "windows") {
        vec!["windows-x86_64"]
    } else {
        vec!["linux-x86_64"]
    }
}

fn latest_android_api(platforms_dir: &Path) -> Option<u32> {
    let mut apis = Vec::new();
    for entry in fs::read_dir(platforms_dir).ok()? {
        let entry = entry.ok()?;
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if let Some(value) = name.strip_prefix("android-") {
            if let Ok(api) = value.parse::<u32>() {
                apis.push(api);
            }
        }
    }
    apis.into_iter().max()
}

fn latest_android_system_image_api(android_home: &Path) -> Option<u32> {
    let root = android_home.join("system-images");
    let mut apis = Vec::new();
    for entry in fs::read_dir(&root).ok()? {
        let entry = entry.ok()?;
        let name = entry.file_name();
        let name = name.to_string_lossy();
        let Some(value) = name.strip_prefix("android-") else {
            continue;
        };
        let Ok(api) = value.parse::<u32>() else {
            continue;
        };
        if entry.path().join("google_apis/arm64-v8a").is_dir() {
            apis.push(api);
        }
    }
    apis.into_iter().max()
}

fn latest_child_dir(path: &Path) -> Option<PathBuf> {
    let mut dirs = fs::read_dir(path)
        .ok()?
        .filter_map(|entry| entry.ok().map(|entry| entry.path()))
        .filter(|path| path.is_dir())
        .collect::<Vec<_>>();
    dirs.sort_by(|left, right| {
        version_key(left)
            .cmp(&version_key(right))
            .then_with(|| left.cmp(right))
    });
    dirs.pop()
}

fn version_key(path: &Path) -> Vec<u32> {
    path.file_name()
        .and_then(|name| name.to_str())
        .unwrap_or_default()
        .split(|ch: char| !ch.is_ascii_digit())
        .filter(|part| !part.is_empty())
        .filter_map(|part| part.parse::<u32>().ok())
        .collect()
}