microsandbox-cli 0.6.9

CLI binary for managing microsandbox environments.
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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//! `msb install` command — create an executable alias for `msb run`.

use std::fs;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};

use clap::Args;

use crate::sandbox_config;
use crate::ui;

use super::common::{
    SandboxConfigSources, SandboxOpts, apply_sandbox_opts_after_config, validate_mount_dir_spec,
    validate_mount_disk_spec, validate_mount_file_spec, validate_mount_named_spec,
    validate_volume_spec,
};

//--------------------------------------------------------------------------------------------------
// Constants
//--------------------------------------------------------------------------------------------------

/// Marker comment used to identify msb-generated alias scripts.
pub(super) const MARKER: &str = "# generated by msb install";

//--------------------------------------------------------------------------------------------------
// Types
//--------------------------------------------------------------------------------------------------

/// Install a sandbox as a system command in ~/.microsandbox/bin.
#[derive(Debug, Args)]
pub struct InstallArgs {
    /// Sparse root and scoped configuration inputs.
    #[command(flatten)]
    pub config: SandboxConfigSources,

    /// Image to install (e.g. python, ubuntu). May be omitted when an explicit config supplies it.
    #[arg(required_unless_present_any = [
        "list",
        "conf",
        "net_conf",
        "resource_conf",
        "runtime_conf",
        "fs_conf",
        "secret_conf",
        "script_conf"
    ])]
    pub image: Option<String>,

    /// Command name for the alias (defaults to image name).
    #[arg(short, long)]
    pub name: Option<String>,

    /// Number of virtual CPUs to allocate.
    #[arg(short = 'c', long)]
    pub cpus: Option<u8>,

    /// Amount of memory to allocate (e.g. 512M, 1G).
    #[arg(short, long)]
    pub memory: Option<String>,

    /// Mount a host path or named volume into the sandbox (`SOURCE:DEST[:OPTIONS]`).
    #[arg(short, long)]
    pub volume: Vec<String>,

    /// Explicitly mount a host directory into the sandbox (`SOURCE:DEST[:OPTIONS]`).
    #[arg(long = "mount-dir", value_name = "SOURCE:DEST[:OPTIONS]")]
    pub mount_dir: Vec<String>,

    /// Explicitly mount a host file into the sandbox (`SOURCE:DEST[:OPTIONS]`).
    #[arg(long = "mount-file", value_name = "SOURCE:DEST[:OPTIONS]")]
    pub mount_file: Vec<String>,

    /// Explicitly mount a disk image into the sandbox (`SOURCE:DEST[:OPTIONS]`).
    #[arg(long = "mount-disk", value_name = "SOURCE:DEST[:OPTIONS]")]
    pub mount_disk: Vec<String>,

    /// Explicitly mount a named volume into the sandbox (`NAME:DEST[:OPTIONS]`).
    #[arg(long = "mount-named", value_name = "NAME:DEST[:OPTIONS]")]
    pub mount_named: Vec<String>,

    /// Set the default working directory for commands.
    #[arg(short, long)]
    pub workdir: Option<String>,

    /// Shell to use for interactive sessions (default: /bin/sh).
    #[arg(long)]
    pub shell: Option<String>,

    /// Set an environment variable (KEY=value).
    #[arg(short, long)]
    pub env: Vec<String>,

    /// Overwrite an existing alias with the same name.
    #[arg(short, long)]
    pub force: bool,

    /// Don't pull the image before installing.
    #[arg(long)]
    pub no_pull: bool,

    /// Create a fresh sandbox on every invocation (no persistent state).
    #[arg(long)]
    pub tmp: bool,

    /// List all installed sandbox commands.
    #[arg(short, long)]
    pub list: bool,

    /// Default command to run in the sandbox (after --).
    #[arg(last = true)]
    pub command: Vec<String>,
}

//--------------------------------------------------------------------------------------------------
// Functions
//--------------------------------------------------------------------------------------------------

/// Execute the `msb install` command.
pub async fn run(args: InstallArgs) -> anyhow::Result<()> {
    let bin_dir = resolve_bin_dir();

    if args.list {
        return list_aliases(&bin_dir);
    }

    let no_pull = args.no_pull;
    let resolved = sandbox_config::resolve(&args.config)?;
    let image = resolved.image(args.image.as_deref(), None)?;
    let registry_auth = resolved.registry_auth()?;
    let display_image = image.display();
    let alias_name = args
        .name
        .as_deref()
        .unwrap_or_else(|| derive_name(&display_image));

    validate_alias_name(alias_name)?;
    for volume in &args.volume {
        validate_volume_spec(volume)?;
    }
    for mount in &args.mount_dir {
        validate_mount_dir_spec(mount)?;
    }
    for mount in &args.mount_file {
        validate_mount_file_spec(mount)?;
    }
    for mount in &args.mount_disk {
        validate_mount_disk_spec(mount)?;
    }
    for mount in &args.mount_named {
        validate_mount_named_spec(mount)?;
    }

    // Validate the same merged builder the generated alias will create, before writing anything.
    let cli_opts = install_sandbox_opts(&args);
    let builder = resolved.apply(microsandbox::sandbox::Sandbox::builder("msb-install-check"))?;
    let builder = image.apply(builder)?;
    let builder = apply_sandbox_opts_after_config(builder, &cli_opts)?;
    builder.build().await?;

    // Resolve and quote all config paths before a forced install can replace an existing alias.
    let script = build_script(args.image.as_deref(), &display_image, alias_name, &args)?;
    let alias_path = alias_path(&bin_dir, alias_name);
    prepare_alias_path(&bin_dir, alias_name, args.force)?;

    // Pre-pull the image so the alias is ready to use immediately.
    if !no_pull && let Some(reference) = image.oci_reference() {
        super::image::pull_if_missing_with_auth(
            reference,
            false,
            super::pull::PullMaterialization::Layered,
            registry_auth,
        )
        .await?;
    }

    // Ensure bin dir exists.
    fs::create_dir_all(&bin_dir)?;

    // Write and make executable.
    fs::write(&alias_path, &script)?;
    #[cfg(unix)]
    fs::set_permissions(&alias_path, fs::Permissions::from_mode(0o755))?;

    ui::success("Installed", alias_name);

    // PATH hint.
    if !is_in_path(&bin_dir) {
        #[cfg(windows)]
        eprintln!("  Add to your user PATH:\n    {}", bin_dir.display());
        #[cfg(not(windows))]
        eprintln!(
            "  Add to your shell profile:\n    export PATH=\"{}:$PATH\"",
            bin_dir.display()
        );
    }

    Ok(())
}

/// Resolve the bin directory for installed aliases.
fn resolve_bin_dir() -> PathBuf {
    let backend = microsandbox::backend::default_backend();
    let home = match backend.as_local() {
        Some(local) => local.config().home(),
        None => microsandbox_utils::resolve_home(),
    };
    home.join("bin")
}

/// Validate that an alias name is safe to use as a filename in the bin directory.
fn validate_alias_name(name: &str) -> anyhow::Result<()> {
    if name.is_empty() {
        anyhow::bail!("alias name cannot be empty");
    }
    if name.contains('/') || name.contains('\\') || name.contains(':') || name.contains("..") {
        anyhow::bail!("alias name must not contain '/', '\\', ':', or '..'");
    }

    const RESERVED: &[&str] = &["msb", "agentd"];
    if RESERVED.contains(&name) {
        anyhow::bail!("alias name '{name}' would shadow a microsandbox binary");
    }

    Ok(())
}

/// Derive an alias name from an image reference.
///
/// Strips the digest, tag, and registry/namespace prefix:
/// - `ubuntu` → `ubuntu`
/// - `ghcr.io/foo/bar:latest` → `bar`
/// - `library/alpine` → `alpine`
/// - `ubuntu@sha256:abc` → `ubuntu`
fn derive_name(image: &str) -> &str {
    let without_digest = image.split('@').next().unwrap_or(image);
    let without_tag = without_digest.split(':').next().unwrap_or(without_digest);
    without_tag.rsplit('/').next().unwrap_or(without_tag)
}

/// Shell-quote a string, using single quotes only when necessary.
#[cfg(not(windows))]
fn shell_quote(s: &str) -> String {
    if s.is_empty() {
        return "''".to_string();
    }
    if s.chars()
        .all(|c| c.is_alphanumeric() || matches!(c, '-' | '_' | '.' | '/' | ':' | '=' | '+'))
    {
        s.to_string()
    } else {
        format!("'{}'", s.replace('\'', "'\\''"))
    }
}

/// Quote an argument for the generated Windows command shim.
#[cfg(windows)]
fn cmd_quote(s: &str) -> String {
    if s.is_empty() {
        return "\"\"".to_string();
    }

    // Batch files expand `%...%` before invoking the command. Doubling
    // percent signs preserves literal env values and command arguments.
    let escaped = s.replace('%', "%%").replace('"', "\"\"");
    format!("\"{escaped}\"")
}

/// Strip control characters for safe embedding in shell comments.
fn sanitize_comment(s: &str) -> String {
    s.chars().filter(|c| !c.is_control()).collect()
}

/// Build the shell script content for an alias.
fn build_script(
    image: Option<&str>,
    display_image: &str,
    alias_name: &str,
    args: &InstallArgs,
) -> anyhow::Result<String> {
    #[cfg(windows)]
    {
        build_cmd_script(image, display_image, alias_name, args)
    }
    #[cfg(not(windows))]
    {
        if args.tmp {
            build_tmp_script(image, display_image, args)
        } else {
            build_persisted_script(image, display_image, alias_name, args)
        }
    }
}

/// Build an ephemeral (--tmp) alias script.
///
/// Each invocation creates a fresh sandbox that is removed on exit.
#[cfg(not(windows))]
fn build_tmp_script(
    image: Option<&str>,
    display_image: &str,
    args: &InstallArgs,
) -> anyhow::Result<String> {
    let mut parts = vec!["exec".to_string(), "msb".to_string(), "run".to_string()];
    if let Some(image) = image {
        parts.push(shell_quote(image));
    }
    append_config_options(&mut parts, &args.config, shell_quote)?;
    append_resource_options(&mut parts, args, shell_quote);

    if !args.command.is_empty() {
        parts.push("--".into());
        for c in &args.command {
            parts.push(shell_quote(c));
        }
    }

    let mut script = format!("#!/bin/sh\n{MARKER}\n");
    script.push_str(&format!("# image: {}\n", sanitize_comment(display_image)));
    script.push_str("# mode: tmp\n");
    if !args.command.is_empty() {
        script.push_str(&format!(
            "# command: {}\n",
            sanitize_comment(&args.command.join(" "))
        ));
    }
    script.push_str(&parts.join(" "));
    script.push('\n');
    Ok(script)
}

/// Build a persisted alias script.
///
/// Uses `msb run -n` which creates on first use and reuses on subsequent
/// invocations. State (installed packages, files, etc.) persists across calls.
#[cfg(not(windows))]
fn build_persisted_script(
    image: Option<&str>,
    display_image: &str,
    sandbox_name: &str,
    args: &InstallArgs,
) -> anyhow::Result<String> {
    let mut parts = vec![
        "exec".to_string(),
        "msb".to_string(),
        "run".to_string(),
        "-n".to_string(),
        shell_quote(sandbox_name),
    ];
    if let Some(image) = image {
        parts.push(shell_quote(image));
    }
    append_config_options(&mut parts, &args.config, shell_quote)?;
    append_resource_options(&mut parts, args, shell_quote);

    if !args.command.is_empty() {
        parts.push("--".into());
        for c in &args.command {
            parts.push(shell_quote(c));
        }
    }

    let mut script = format!("#!/bin/sh\n{MARKER}\n");
    script.push_str(&format!("# image: {}\n", sanitize_comment(display_image)));
    script.push_str("# mode: persisted\n");
    if !args.command.is_empty() {
        script.push_str(&format!(
            "# command: {}\n",
            sanitize_comment(&args.command.join(" "))
        ));
    }
    script.push_str(&parts.join(" "));
    script.push('\n');
    Ok(script)
}

/// Build a Windows `.cmd` alias shim.
#[cfg(windows)]
fn build_cmd_script(
    image: Option<&str>,
    display_image: &str,
    alias_name: &str,
    args: &InstallArgs,
) -> anyhow::Result<String> {
    let mut parts = vec!["\"%~dp0msb.exe\"".to_string(), "run".to_string()];
    if !args.tmp {
        parts.push("-n".to_string());
        parts.push(cmd_quote(alias_name));
    }
    if let Some(image) = image {
        parts.push(cmd_quote(image));
    }
    append_config_options(&mut parts, &args.config, cmd_quote)?;
    append_resource_options(&mut parts, args, cmd_quote);

    if !args.command.is_empty() {
        parts.push("--".into());
        for c in &args.command {
            parts.push(cmd_quote(c));
        }
    }

    let mut script = "@echo off\r\n".to_string();
    script.push_str(&format!("rem {MARKER}\r\n"));
    script.push_str(&format!(
        "rem # image: {}\r\n",
        sanitize_comment(display_image)
    ));
    script.push_str(if args.tmp {
        "rem # mode: tmp\r\n"
    } else {
        "rem # mode: persisted\r\n"
    });
    if !args.command.is_empty() {
        script.push_str(&format!(
            "rem # command: {}\r\n",
            sanitize_comment(&args.command.join(" "))
        ));
    }
    script.push_str(&parts.join(" "));
    script.push_str("\r\nexit /b %ERRORLEVEL%\r\n");
    Ok(script)
}

/// Convert install's intentionally smaller CLI surface into the shared option model for validation.
fn install_sandbox_opts(args: &InstallArgs) -> SandboxOpts {
    SandboxOpts {
        cpus: args.cpus,
        memory: args.memory.clone(),
        volume: args.volume.clone(),
        mount_dir: args.mount_dir.clone(),
        mount_file: args.mount_file.clone(),
        mount_disk: args.mount_disk.clone(),
        mount_named: args.mount_named.clone(),
        workdir: args.workdir.clone(),
        shell: args.shell.clone(),
        env: args.env.clone(),
        ..SandboxOpts::default()
    }
}

/// Record explicit config inputs as absolute paths so an installed alias is cwd-independent.
fn append_config_options(
    parts: &mut Vec<String>,
    sources: &SandboxConfigSources,
    quote: fn(&str) -> String,
) -> anyhow::Result<()> {
    for source in sources.iter() {
        let absolute = fs::canonicalize(&source.path).map_err(|err| {
            anyhow::anyhow!(
                "failed to resolve config path {}: {err}",
                source.path.display()
            )
        })?;
        parts.push(source.kind.flag());
        parts.push(quote(&absolute.to_string_lossy()));
    }
    Ok(())
}

/// Append resource/environment options to a command parts list.
fn append_resource_options(parts: &mut Vec<String>, args: &InstallArgs, quote: fn(&str) -> String) {
    if let Some(cpus) = args.cpus {
        parts.push("-c".into());
        parts.push(cpus.to_string());
    }
    if let Some(ref mem) = args.memory {
        parts.push("-m".into());
        parts.push(quote(mem));
    }
    for vol in &args.volume {
        parts.push("-v".into());
        parts.push(quote(vol));
    }
    for mount in &args.mount_dir {
        parts.push("--mount-dir".into());
        parts.push(quote(mount));
    }
    for mount in &args.mount_file {
        parts.push("--mount-file".into());
        parts.push(quote(mount));
    }
    for mount in &args.mount_disk {
        parts.push("--mount-disk".into());
        parts.push(quote(mount));
    }
    for mount in &args.mount_named {
        parts.push("--mount-named".into());
        parts.push(quote(mount));
    }
    if let Some(ref workdir) = args.workdir {
        parts.push("-w".into());
        parts.push(quote(workdir));
    }
    if let Some(ref shell) = args.shell {
        parts.push("--shell".into());
        parts.push(quote(shell));
    }
    for env_str in &args.env {
        parts.push("-e".into());
        parts.push(quote(env_str));
    }
}

/// List all msb-installed aliases in the bin directory.
fn list_aliases(bin_dir: &Path) -> anyhow::Result<()> {
    let mut table = ui::Table::new(&["NAME", "IMAGE", "MODE", "COMMAND"]);

    if bin_dir.is_dir() {
        let mut entries: Vec<_> = fs::read_dir(bin_dir)?.filter_map(|e| e.ok()).collect();
        entries.sort_by_key(|e| e.file_name());

        for entry in entries {
            let path = entry.path();
            if !path.is_file() {
                continue;
            }

            let content = match fs::read_to_string(&path) {
                Ok(c) => c,
                Err(_) => continue,
            };
            if !is_generated_alias(&content) {
                continue;
            }

            let name = display_alias_name(&entry.file_name().to_string_lossy());
            let image = alias_comment_value(&content, "image: ")
                .unwrap_or("-")
                .to_string();
            let mode = alias_comment_value(&content, "mode: ")
                .unwrap_or("-")
                .to_string();
            let command = alias_comment_value(&content, "command: ")
                .unwrap_or("")
                .to_string();

            table.add_row(vec![name, image, mode, command]);
        }
    }

    table.print();

    Ok(())
}

/// Check whether a directory is already in the PATH.
fn is_in_path(dir: &Path) -> bool {
    std::env::var_os("PATH")
        .map(|path| std::env::split_paths(&path).any(|p| p == dir))
        .unwrap_or(false)
}

/// Return the primary alias path for the current platform.
pub(super) fn alias_path(bin_dir: &Path, alias_name: &str) -> PathBuf {
    #[cfg(windows)]
    {
        bin_dir.join(format!("{alias_name}.cmd"))
    }
    #[cfg(not(windows))]
    {
        bin_dir.join(alias_name)
    }
}

/// Return every filename that may represent a single alias.
pub(super) fn alias_candidates(bin_dir: &Path, alias_name: &str) -> Vec<PathBuf> {
    #[cfg(windows)]
    {
        vec![
            bin_dir.join(format!("{alias_name}.cmd")),
            bin_dir.join(format!("{alias_name}.ps1")),
            bin_dir.join(alias_name),
        ]
    }
    #[cfg(not(windows))]
    {
        vec![bin_dir.join(alias_name)]
    }
}

/// Remove or reject existing files for an alias before writing the new shim.
fn prepare_alias_path(bin_dir: &Path, alias_name: &str, force: bool) -> anyhow::Result<()> {
    for path in alias_candidates(bin_dir, alias_name) {
        if !path.exists() {
            continue;
        }
        if !force {
            anyhow::bail!("alias '{alias_name}' already exists (use --force to overwrite)");
        }

        let content = fs::read_to_string(&path)?;
        if !is_generated_alias(&content) {
            anyhow::bail!("refusing to overwrite non-msb alias {}", path.display());
        }
        fs::remove_file(path)?;
    }
    Ok(())
}

/// Return true if a script/shim was generated by `msb install`.
pub(super) fn is_generated_alias(content: &str) -> bool {
    content.lines().nth(1).is_some_and(is_marker_line)
}

/// Extract a generated alias metadata value.
fn alias_comment_value<'a>(content: &'a str, key: &str) -> Option<&'a str> {
    content.lines().find_map(|line| {
        let comment = line
            .strip_prefix("# ")
            .or_else(|| line.strip_prefix("rem # "))
            .or_else(|| line.strip_prefix("REM # "))?;
        comment.strip_prefix(key)
    })
}

/// Return true if a line is the platform marker line.
fn is_marker_line(line: &str) -> bool {
    line == MARKER
        || line
            .strip_prefix("rem ")
            .or_else(|| line.strip_prefix("REM "))
            .is_some_and(|line| line == MARKER)
}

/// Convert the alias filename shown by the filesystem into the user-facing name.
fn display_alias_name(file_name: &str) -> String {
    #[cfg(windows)]
    {
        file_name
            .strip_suffix(".cmd")
            .or_else(|| file_name.strip_suffix(".ps1"))
            .unwrap_or(file_name)
            .to_string()
    }
    #[cfg(not(windows))]
    {
        file_name.to_string()
    }
}

//--------------------------------------------------------------------------------------------------
// Tests
//--------------------------------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use clap::Parser;
    use clap::error::ErrorKind;

    use super::*;
    use crate::commands::common::SandboxConfigKind;

    #[derive(Debug, Parser)]
    struct TestCli {
        #[command(flatten)]
        args: InstallArgs,
    }

    #[cfg(windows)]
    fn args(tmp: bool) -> InstallArgs {
        InstallArgs {
            config: SandboxConfigSources::default(),
            image: Some("alpine".to_string()),
            name: Some("hello".to_string()),
            cpus: None,
            memory: None,
            volume: Vec::new(),
            mount_dir: Vec::new(),
            mount_file: Vec::new(),
            mount_disk: Vec::new(),
            mount_named: Vec::new(),
            workdir: None,
            shell: None,
            env: Vec::new(),
            force: false,
            no_pull: true,
            tmp,
            list: false,
            command: vec!["echo".to_string(), "alias-ok".to_string()],
        }
    }

    #[test]
    fn detects_posix_generated_alias_marker() {
        let script = "#!/bin/sh\n# generated by msb install\n# image: alpine\n";
        assert!(is_generated_alias(script));
    }

    #[test]
    fn detects_windows_generated_alias_marker() {
        let script = "@echo off\r\nrem # generated by msb install\r\nrem # image: alpine\r\n";
        assert!(is_generated_alias(script));
    }

    #[test]
    fn explicit_config_can_supply_the_installed_image() {
        let parsed = TestCli::parse_from(["msb", "--conf", "agent.yaml"]);

        assert!(parsed.args.image.is_none());
        assert_eq!(
            parsed
                .args
                .config
                .iter()
                .map(|source| (source.kind, source.path.clone()))
                .collect::<Vec<_>>(),
            [(SandboxConfigKind::Root, PathBuf::from("agent.yaml"))]
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn installed_alias_preserves_repeated_config_source_order() {
        let dir = tempfile::tempdir().unwrap();
        let first = dir.path().join("first.yaml");
        let base = dir.path().join("base.yaml");
        let second = dir.path().join("second.yaml");
        fs::write(&first, "memory: 1G\n").unwrap();
        fs::write(&base, "image: alpine\n").unwrap();
        fs::write(&second, "memory: 2G\n").unwrap();
        let sources = SandboxConfigSources::default()
            .source(SandboxConfigKind::Resources, first)
            .source(SandboxConfigKind::Root, base)
            .source(SandboxConfigKind::Resources, second);
        let mut parts = Vec::new();

        append_config_options(&mut parts, &sources, shell_quote).unwrap();

        assert_eq!(
            parts
                .iter()
                .step_by(2)
                .map(String::as_str)
                .collect::<Vec<_>>(),
            ["--resource-conf", "--conf", "--resource-conf"]
        );
    }

    #[test]
    fn install_still_requires_an_image_source() {
        let error = TestCli::try_parse_from(["msb"]).unwrap_err();

        assert_eq!(error.kind(), ErrorKind::MissingRequiredArgument);
    }

    #[test]
    #[cfg(windows)]
    fn windows_alias_path_uses_cmd_extension() {
        let path = alias_path(Path::new(r"C:\Users\Stephen\.microsandbox\bin"), "hello");
        assert_eq!(
            path,
            PathBuf::from(r"C:\Users\Stephen\.microsandbox\bin\hello.cmd")
        );
    }

    #[test]
    #[cfg(windows)]
    fn windows_build_script_invokes_adjacent_msb_exe() {
        let args = args(true);
        let script = build_script(Some("alpine"), "alpine", "hello", &args).unwrap();
        assert!(is_generated_alias(&script));
        assert!(script.contains(r#""%~dp0msb.exe" run "alpine" -- "echo" "alias-ok""#));
        assert!(script.contains("rem # mode: tmp"));
    }
}