oxdock-cli 0.6.0-alpha

CLI tooling for executing OxDock's Docker-inspired language on native platforms.
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
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
767
768
769
770
771
772
773
774
775
776
use anyhow::{Context, Result, bail};
use oxdock_fs::{GuardedPath, GuardedTempDir, PathResolver, discover_workspace_root};
#[cfg(test)]
use oxdock_process::CommandSnapshot;
use oxdock_process::{CommandBuilder, SharedInput};
use std::env;
use std::io::{self, IsTerminal, Read};
use std::sync::{Arc, Mutex};

use oxdock_core::{ExecIo, run_steps_with_context_result_with_io};
pub use oxdock_core::{run_steps, run_steps_with_context, run_steps_with_context_result};
pub use oxdock_parser::{Guard, Step, StepKind, parse_script};
pub use oxdock_process::shell_program;

pub fn run() -> Result<()> {
    let workspace_root = discover_workspace_root().context("guard workspace root")?;

    let mut args = std::env::args().skip(1);
    let opts = Options::parse(&mut args, &workspace_root)?;
    execute(opts, workspace_root)
}

#[derive(Debug, Clone)]
pub enum ScriptSource {
    Path(GuardedPath),
    Stdin,
}

#[derive(Debug, Clone)]
pub struct Options {
    pub script: ScriptSource,
    pub shell: bool,
}

impl Options {
    pub fn parse(
        args: &mut impl Iterator<Item = String>,
        workspace_root: &GuardedPath,
    ) -> Result<Self> {
        let mut script: Option<ScriptSource> = None;
        let mut shell = false;
        while let Some(arg) = args.next() {
            if arg.is_empty() {
                continue;
            }
            match arg.as_str() {
                "--script" => {
                    let p = args
                        .next()
                        .ok_or_else(|| anyhow::anyhow!("--script requires a path"))?;
                    if p == "-" {
                        script = Some(ScriptSource::Stdin);
                    } else {
                        script = Some(ScriptSource::Path(
                            workspace_root
                                .join(&p)
                                .with_context(|| format!("guard script path {p}"))?,
                        ));
                    }
                }
                "--shell" => {
                    shell = true;
                }
                other => bail!("unexpected flag: {}", other),
            }
        }

        let script = script.unwrap_or(ScriptSource::Stdin);

        Ok(Self { script, shell })
    }
}

pub fn execute(opts: Options, workspace_root: GuardedPath) -> Result<()> {
    execute_with_shell_runner(opts, workspace_root, run_shell, true)
}

pub struct ExecutionResult {
    pub tempdir: GuardedTempDir,
    pub final_cwd: GuardedPath,
}

pub fn execute_with_result(opts: Options, workspace_root: GuardedPath) -> Result<ExecutionResult> {
    if opts.shell {
        bail!("execute_with_result does not support --shell");
    }

    let tempdir = GuardedPath::tempdir().context("failed to create temp dir")?;
    let temp_root = tempdir.as_guarded_path().clone();

    let script = match &opts.script {
        ScriptSource::Path(path) => {
            let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
            resolver
                .read_to_string(path)
                .with_context(|| format!("failed to read script at {}", path.display()))?
        }
        ScriptSource::Stdin => {
            let mut buf = String::new();
            io::stdin()
                .lock()
                .read_to_string(&mut buf)
                .context("failed to read script from stdin")?;
            buf
        }
    };

    let mut final_cwd = temp_root.clone();
    if !script.trim().is_empty() {
        let steps = parse_script(&script)?;
        final_cwd = run_steps_with_context_result_with_io(
            &temp_root,
            &workspace_root,
            &steps,
            ExecIo::new(),
        )?;
    }

    Ok(ExecutionResult { tempdir, final_cwd })
}

fn execute_with_shell_runner<F>(
    opts: Options,
    workspace_root: GuardedPath,
    shell_runner: F,
    require_tty: bool,
) -> Result<()>
where
    F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
{
    #[cfg(windows)]
    maybe_reexec_shell_to_temp(&opts)?;

    let tempdir = GuardedPath::tempdir().context("failed to create temp dir")?;
    let temp_root = tempdir.as_guarded_path().clone();

    // Interpret a tiny Dockerfile-ish script
    let script = match &opts.script {
        ScriptSource::Path(path) => {
            // Read script path via PathResolver rooted at the workspace so
            // script files are validated to live under the workspace.
            let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
            resolver
                .read_to_string(path)
                .with_context(|| format!("failed to read script at {}", path.display()))?
        }
        ScriptSource::Stdin => {
            let stdin = io::stdin();
            if stdin.is_terminal() {
                // No piped script provided. If the caller requested `--shell`
                // allow running with an initially-empty script so we can either
                // drop into the interactive shell or open the editor later.
                // Otherwise, require a script on stdin.
                if opts.shell {
                    String::new()
                } else {
                    bail!(
                        "no stdin detected; pass --script <file> or pipe a script into stdin (use --script - if explicit)"
                    );
                }
            } else {
                let mut buf = String::new();
                stdin
                    .lock()
                    .read_to_string(&mut buf)
                    .context("failed to read script from stdin")?;
                buf
            }
        }
    };

    // Parse and run steps if we have a non-empty script. Empty scripts are
    // valid when `--shell` is requested and the caller didn't pipe a script.
    let mut final_cwd = temp_root.clone();
    if !script.trim().is_empty() {
        let steps = parse_script(&script)?;
        // Use the caller's workspace as the build context so WORKSPACE LOCAL can hop back and so COPY
        // can source from the original tree if needed. Capture the final working directory so shells
        // inherit whatever WORKDIR the script ended on.

        // If we are running a script from a file, we might have stdin available for the script itself.
        // If we read the script from stdin, then stdin is consumed.
        // But if opts.script is ScriptSource::Path, stdin is still available.

        let mut stdin_handle: Option<SharedInput> = None;
        if let ScriptSource::Path(_) = opts.script {
            let stdin = io::stdin();
            if !stdin.is_terminal() {
                // Wrap stdin in SharedInput (Arc<Mutex<dyn Read + Send>>)
                // Note: std::io::Stdin is a handle, but we need an owned Read + Send.
                // std::io::stdin() returns Stdin, which implements Read + Send.
                // However, we need to be careful about locking.
                // We can wrap the Stdin struct directly.
                stdin_handle = Some(Arc::new(Mutex::new(stdin)));
            }
        }

        let mut io_cfg = ExecIo::new();
        io_cfg.set_stdin(stdin_handle);
        final_cwd =
            run_steps_with_context_result_with_io(&temp_root, &workspace_root, &steps, io_cfg)?;
    }

    // If requested, drop into an interactive shell after running the script.
    if opts.shell {
        if require_tty && !has_controlling_tty() {
            bail!("--shell requires a tty (no controlling tty available)");
        }
        return shell_runner(&final_cwd, &workspace_root);
    }

    Ok(())
}

#[cfg(test)]
fn execute_for_test<F>(opts: Options, workspace_root: GuardedPath, shell_runner: F) -> Result<()>
where
    F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
{
    execute_with_shell_runner(opts, workspace_root, shell_runner, false)
}

fn has_controlling_tty() -> bool {
    // Prefer checking whether stdin or stderr is a terminal. This avoids
    // directly opening device files via `std::fs` while still detecting
    // whether an interactive tty is available in the common cases.
    #[cfg(unix)]
    {
        io::stdin().is_terminal() || io::stderr().is_terminal()
    }

    #[cfg(windows)]
    {
        io::stdin().is_terminal() || io::stderr().is_terminal()
    }

    #[cfg(not(any(unix, windows)))]
    {
        false
    }
}

#[cfg(windows)]
fn maybe_reexec_shell_to_temp(opts: &Options) -> Result<()> {
    // Only used for interactive shells. Copy the binary to a temp path and run it there so the
    // original target exe is free for rebuilding while the shell stays open.
    if !opts.shell {
        return Ok(());
    }
    if std::env::var("OXDOCK_SHELL_REEXEC").ok().as_deref() == Some("1") {
        return Ok(());
    }

    let self_path = std::env::current_exe().context("determine current executable")?;
    let base_temp =
        GuardedPath::new_root(std::env::temp_dir().as_path()).context("guard system temp dir")?;
    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis();
    let temp_file = base_temp
        .join(&format!("oxdock-shell-{ts}-{}.exe", std::process::id()))
        .context("construct temp shell path")?;

    // Copy the current executable into the temporary location via a
    // resolver whose root is the temp directory. The source may live
    // outside the temp dir, so use `copy_file_from_external`.
    let temp_root_guard = temp_file
        .parent()
        .ok_or_else(|| anyhow::anyhow!("temp path unexpectedly missing parent"))?;
    let resolver_temp = PathResolver::new(temp_root_guard.as_path(), temp_root_guard.as_path())?;
    let dest = temp_file;
    #[allow(clippy::disallowed_types)]
    let source = oxdock_fs::UnguardedPath::new(self_path);
    resolver_temp
        .copy_file_from_unguarded(&source, &dest)
        .with_context(|| format!("failed to copy shell runner to {}", dest.display()))?;

    let mut cmd = CommandBuilder::new(dest.as_path());
    cmd.args(std::env::args_os().skip(1));
    cmd.env("OXDOCK_SHELL_REEXEC", "1");
    cmd.spawn()
        .with_context(|| format!("failed to spawn shell from {}", dest.display()))?;

    // Exit immediately so the original binary can be rebuilt while the shell child stays running.
    std::process::exit(0);
}

pub fn run_script(workspace_root: &GuardedPath, steps: &[Step]) -> Result<()> {
    run_steps_with_context(workspace_root, workspace_root, steps)
}

fn shell_banner(cwd: &GuardedPath, workspace_root: &GuardedPath) -> String {
    #[cfg(windows)]
    let cwd_disp = oxdock_fs::command_path(cwd).as_ref().display().to_string();
    #[cfg(windows)]
    let workspace_disp = oxdock_fs::command_path(workspace_root)
        .as_ref()
        .display()
        .to_string();

    #[cfg(not(windows))]
    let cwd_disp = cwd.display().to_string();
    #[cfg(not(windows))]
    let workspace_disp = workspace_root.display().to_string();

    let pkg = env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "oxdock".to_string());
    indoc::formatdoc! {"
        {pkg} shell workspace
          cwd: {cwd_disp}
          source: workspace root at {workspace_disp}
          lifetime: temporary directory created for this shell session; it disappears when you exit
          creation: temp workspace starts empty unless your script copies files into it

          WARNING: This shell still runs on your host filesystem and is **not** isolated!
    "}
}

#[cfg(windows)]
fn escape_for_cmd(s: &str) -> String {
    // Escape characters that would otherwise be interpreted by cmd when echoed.
    s.replace('^', "^^")
        .replace('&', "^&")
        .replace('|', "^|")
        .replace('>', "^>")
        .replace('<', "^<")
}

#[cfg(windows)]
fn windows_banner_command(banner: &str, cwd: &GuardedPath) -> String {
    let mut parts: Vec<String> = banner
        .lines()
        .map(|line| format!("echo {}", escape_for_cmd(line)))
        .collect();
    let cwd_path = oxdock_fs::command_path(cwd);
    parts.push(format!(
        "cd /d {}",
        escape_for_cmd(&cwd_path.as_ref().display().to_string())
    ));
    parts.join(" && ")
}

// TODO: Migrate to oxdock-process crate so that Miri flags don't need to be handled here.
fn run_shell(cwd: &GuardedPath, workspace_root: &GuardedPath) -> Result<()> {
    let banner = shell_banner(cwd, workspace_root);

    #[cfg(unix)]
    {
        let mut cmd = CommandBuilder::new(shell_program());
        cmd.current_dir(cwd.as_path());

        // Print a single banner inside the subshell, then exec the user's shell to stay interactive.
        let script = format!("printf '%s\\n' \"{}\"; exec {}", banner, shell_program());
        cmd.arg("-c").arg(script);

        // Reattach stdin to the controlling TTY so a piped-in script can still open an interactive shell.
        // Use `PathResolver::open_external_file` to centralize raw `File::open` usage.
        #[cfg(not(miri))]
        {
            #[allow(clippy::disallowed_types)]
            let tty_path = oxdock_fs::UnguardedPath::new("/dev/tty");
            if let Ok(resolver) =
                PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
                && let Ok(tty) = resolver.open_file_unguarded(&tty_path)
            {
                cmd.stdin_file(tty);
            }
        }

        if try_shell_command_hook(&mut cmd)? {
            return Ok(());
        }

        let status = cmd.status()?;
        if !status.success() {
            bail!("shell exited with status {}", status);
        }
        Ok(())
    }

    #[cfg(windows)]
    {
        // Launch via `start` so Windows opens a real interactive console window. Normalize the path
        // and also set the parent process working directory to the temp workspace; this avoids
        // start's `/D` parsing quirks on paths with spaces or verbatim prefixes.
        let cwd_path = oxdock_fs::command_path(cwd);
        let banner_cmd = windows_banner_command(&banner, cwd);
        let mut cmd = CommandBuilder::new("cmd");
        cmd.current_dir(cwd_path.as_ref())
            .arg("/C")
            .arg("start")
            .arg("oxdock shell")
            .arg("cmd")
            .arg("/K")
            .arg(banner_cmd);

        if try_shell_command_hook(&mut cmd)? {
            return Ok(());
        }

        // Fire-and-forget so the parent console regains control immediately; the child window is
        // fully interactive. If the launch fails, surface the error right away.
        cmd.spawn()
            .context("failed to start interactive shell window")?;
        Ok(())
    }

    #[cfg(not(any(unix, windows)))]
    {
        let _ = cwd;
        bail!("interactive shell unsupported on this platform");
    }
}
#[cfg(test)]
type ShellCmdHook = dyn FnMut(&CommandSnapshot) -> Result<()> + Send;

#[cfg(test)]
thread_local! {
    static SHELL_CMD_HOOK: std::cell::RefCell<Option<Box<ShellCmdHook>>> = std::cell::RefCell::new(None);
}

#[cfg(test)]
fn set_shell_command_hook<F>(hook: F)
where
    F: FnMut(&CommandSnapshot) -> Result<()> + Send + 'static,
{
    SHELL_CMD_HOOK.with(|slot| {
        *slot.borrow_mut() = Some(Box::new(hook));
    });
}

#[cfg(test)]
fn clear_shell_command_hook() {
    SHELL_CMD_HOOK.with(|slot| {
        *slot.borrow_mut() = None;
    });
}

#[cfg(test)]
fn try_shell_command_hook(cmd: &mut CommandBuilder) -> Result<bool> {
    SHELL_CMD_HOOK.with(|slot| {
        if let Some(hook) = slot.borrow_mut().as_mut() {
            let snap = cmd.snapshot();
            hook(&snap)?;
            return Ok(true);
        }
        Ok(false)
    })
}

#[cfg(not(test))]
fn try_shell_command_hook(_cmd: &mut CommandBuilder) -> Result<bool> {
    Ok(false)
}

// `command_path` now lives in `oxdock-fs` to centralize Path usage.

#[cfg(test)]
mod tests {
    use super::*;
    use indoc::indoc;
    use oxdock_fs::PathResolver;
    use std::cell::{Cell, RefCell};

    #[cfg_attr(
        miri,
        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
    )]
    #[test]
    fn shell_runner_receives_final_workdir() -> Result<()> {
        let workspace = GuardedPath::tempdir()?;
        let workspace_root = workspace.as_guarded_path().clone();
        let script_path = workspace_root.join("script.ox")?;
        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
        let script = indoc! {"
            WRITE temp.txt 123
            WORKDIR sub
        "};
        resolver.write_file(&script_path, script.as_bytes())?;

        let opts = Options {
            script: ScriptSource::Path(script_path),
            shell: true,
        };

        let observed = Cell::new(false);
        execute_for_test(opts, workspace_root.clone(), |cwd, _| {
            assert!(
                cwd.as_path().ends_with("sub"),
                "final cwd should end in WORKDIR target, got {}",
                cwd.display()
            );

            let temp_root = GuardedPath::new_root(cwd.root())
                .context("construct guard for temp workspace root")?;
            let sub_dir = temp_root.join("sub")?;
            assert_eq!(
                cwd.as_path(),
                sub_dir.as_path(),
                "shell runner cwd should match guarded sub dir"
            );
            let temp_file = temp_root.join("temp.txt")?;
            let temp_resolver = PathResolver::new(temp_root.as_path(), temp_root.as_path())?;
            let contents = temp_resolver.read_to_string(&temp_file)?;
            assert!(
                contents.contains("123"),
                "expected WRITE command to materialize temp file"
            );
            observed.set(true);
            Ok(())
        })?;

        assert!(
            observed.into_inner(),
            "shell runner closure should have been invoked"
        );
        Ok(())
    }

    #[cfg(any(unix, windows))]
    #[test]
    fn run_shell_builds_command_for_platform() -> Result<()> {
        let workspace = GuardedPath::tempdir()?;
        let workspace_root = workspace.as_guarded_path().clone();
        let cwd = workspace_root.join("subdir")?;
        #[cfg(not(miri))]
        {
            let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
            resolver.create_dir_all(&cwd)?;
        }

        let captured = std::sync::Arc::new(Mutex::new(None::<CommandSnapshot>));
        let guard = captured.clone();
        set_shell_command_hook(move |cmd| {
            *guard.lock().unwrap() = Some(cmd.clone());
            Ok(())
        });
        run_shell(&cwd, &workspace_root)?;
        clear_shell_command_hook();

        let snap = captured
            .lock()
            .unwrap()
            .clone()
            .expect("hook should capture snapshot");
        let cwd_path = snap.cwd.expect("cwd should be set");
        assert!(
            cwd_path.ends_with("subdir"),
            "expected cwd to include subdir, got {}",
            cwd_path.display()
        );

        #[cfg(unix)]
        {
            let program = snap.program.to_string_lossy();
            assert_eq!(program, shell_program(), "expected shell program name");
            let args: Vec<_> = snap
                .args
                .iter()
                .map(|s| s.to_string_lossy().to_string())
                .collect();
            assert_eq!(
                args.len(),
                2,
                "expected two args (-c script), got {:?}",
                args
            );
            assert_eq!(args[0], "-c");
            assert!(
                args[1].contains("exec"),
                "expected script to exec the shell, got {:?}",
                args[1]
            );
        }

        #[cfg(windows)]
        {
            let program = snap.program.to_string_lossy().to_string();
            assert_eq!(program, "cmd", "expected cmd.exe launcher");
            let args: Vec<_> = snap
                .args
                .iter()
                .map(|s| s.to_string_lossy().to_string())
                .collect();
            let banner_cmd = windows_banner_command(&shell_banner(&cwd, &workspace_root), &cwd);
            let expected = vec![
                "/C".to_string(),
                "start".to_string(),
                "oxdock shell".to_string(),
                "cmd".to_string(),
                "/K".to_string(),
                banner_cmd,
            ];
            assert_eq!(args, expected, "expected exact windows shell argv");
        }

        Ok(())
    }

    #[cfg_attr(
        miri,
        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
    )]
    #[test]
    fn options_parse_requires_script_path_value() {
        let workspace = GuardedPath::tempdir().expect("tempdir");
        let mut args = vec!["--script".to_string()].into_iter();
        let err = Options::parse(&mut args, workspace.as_guarded_path())
            .expect_err("expected missing path error");
        assert!(err.to_string().contains("--script requires a path"));
    }

    #[cfg_attr(
        miri,
        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
    )]
    #[test]
    fn options_parse_script_path_and_shell() {
        let workspace = GuardedPath::tempdir().expect("tempdir");
        let workspace_root = workspace.as_guarded_path().clone();
        let script_path = workspace_root.join("script.txt").expect("script path");
        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
            .expect("resolver");
        resolver
            .write_file(&script_path, b"WRITE out.txt hi")
            .expect("write script");
        let mut args = vec![
            "--script".to_string(),
            "script.txt".to_string(),
            "--shell".to_string(),
        ]
        .into_iter();
        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
        assert!(opts.shell);
        match opts.script {
            ScriptSource::Path(path) => assert_eq!(path, script_path),
            ScriptSource::Stdin => panic!("expected path script"),
        }
    }

    #[cfg_attr(
        miri,
        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
    )]
    #[test]
    fn execute_with_result_runs_script() {
        let workspace = GuardedPath::tempdir().expect("tempdir");
        let workspace_root = workspace.as_guarded_path().clone();
        let script_path = workspace_root.join("script.txt").expect("script path");
        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
            .expect("resolver");
        resolver
            .write_file(&script_path, b"WRITE out.txt hi")
            .expect("write script");
        let opts = Options {
            script: ScriptSource::Path(script_path),
            shell: false,
        };
        let ExecutionResult { tempdir, final_cwd } =
            execute_with_result(opts, workspace_root).expect("execute");
        assert_eq!(tempdir.as_guarded_path(), &final_cwd);
        let temp_resolver = PathResolver::new(
            tempdir.as_guarded_path().root(),
            tempdir.as_guarded_path().root(),
        )
        .expect("resolver");
        let out = tempdir.as_guarded_path().join("out.txt").expect("out path");
        let contents = temp_resolver.read_to_string(&out).expect("read out");
        assert_eq!(contents.trim(), "hi");
    }

    #[cfg_attr(
        miri,
        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
    )]
    #[test]
    fn execute_for_test_invokes_shell_runner() -> Result<()> {
        let workspace = GuardedPath::tempdir()?;
        let workspace_root = workspace.as_guarded_path().clone();
        let script_path = workspace_root.join("empty.txt")?;
        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
        resolver.write_file(&script_path, b"")?;
        let opts = Options {
            script: ScriptSource::Path(script_path),
            shell: true,
        };
        let called = RefCell::new(None::<(String, String)>);
        execute_for_test(opts, workspace_root.clone(), |cwd, workspace| {
            called.replace(Some((cwd.display(), workspace.display())));
            Ok(())
        })?;
        let seen = called.borrow().clone().expect("shell runner called");
        assert_eq!(seen.1, workspace_root.display());
        Ok(())
    }
}

#[cfg(all(test, windows))]
mod windows_shell_tests {
    use super::*;
    use oxdock_fs::PathResolver;

    #[test]
    fn command_path_strips_verbatim_prefix() -> Result<()> {
        let temp = GuardedPath::tempdir()?;
        let converted = oxdock_fs::command_path(temp.as_guarded_path());
        let as_str = converted.as_ref().display().to_string();
        assert!(
            !as_str.starts_with(r"\\?\"),
            "expected non-verbatim path, got {as_str}"
        );
        Ok(())
    }

    #[test]
    fn windows_banner_command_emits_all_lines() {
        let banner = "line1\nline2\nline3";
        let workspace = GuardedPath::tempdir().expect("tempdir");
        let cwd = workspace.as_guarded_path().clone();
        let cmd = windows_banner_command(banner, &cwd);
        assert!(cmd.contains("line1"));
        assert!(cmd.contains("line2"));
        assert!(cmd.contains("line3"));
        assert!(cmd.contains("cd /d "));
    }

    #[test]
    fn run_shell_builds_windows_command() -> Result<()> {
        let workspace = GuardedPath::tempdir_with(|builder| {
            builder.prefix("oxdock shell win ");
        })?;
        let workspace_root = workspace.as_guarded_path().clone();
        let cwd = workspace_root.join("subdir")?;
        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
        resolver.create_dir_all(&cwd)?;

        let captured = std::sync::Arc::new(Mutex::new(None::<CommandSnapshot>));
        let guard = captured.clone();
        set_shell_command_hook(move |cmd| {
            *guard.lock().unwrap() = Some(cmd.clone());
            Ok(())
        });
        run_shell(&cwd, &workspace_root)?;
        clear_shell_command_hook();

        let snap = captured
            .lock()
            .unwrap()
            .clone()
            .expect("hook should capture snapshot");
        let program = snap.program.to_string_lossy().to_string();
        assert_eq!(program, "cmd", "expected cmd.exe launcher");
        let args: Vec<_> = snap
            .args
            .iter()
            .map(|s| s.to_string_lossy().to_string())
            .collect();
        let banner_cmd = windows_banner_command(&shell_banner(&cwd, &workspace_root), &cwd);
        let expected = vec![
            "/C".to_string(),
            "start".to_string(),
            "oxdock shell".to_string(),
            "cmd".to_string(),
            "/K".to_string(),
            banner_cmd,
        ];
        assert_eq!(args, expected, "expected exact windows shell argv");
        let cwd_path = snap.cwd.expect("cwd should be set");
        assert!(
            cwd_path.ends_with("subdir"),
            "expected cwd to include subdir, got {}",
            cwd_path.display()
        );
        Ok(())
    }
}