Skip to main content

oxdock_cli/
lib.rs

1use anyhow::{Context, Result, bail};
2use oxdock_fs::{
3    GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, discover_workspace_root,
4    env as oxdock_env, init_temp_gc,
5};
6#[cfg(windows)]
7use oxdock_process::CommandBuilder;
8use oxdock_process::{DefaultProcessManager, SharedInput};
9use std::env;
10use std::io::{self, IsTerminal, Read};
11use std::sync::{Arc, Mutex};
12
13pub use oxdock_core::{
14    Engine, EngineOutput, ExecState, FuncKind, FuncMeta, FuncParam, HostModule, HostRegistration,
15    NativeFn, OxDockFn, OxDockType, PureFn, StepCtx, TypeDescriptor, Value, parse_script,
16    parse_script_with_modules, run_steps, run_steps_with_context, run_steps_with_context_result,
17    run_steps_with_manager_with_modules,
18};
19use oxdock_core::{ExecIo, run_steps_with_lazy_snapshot_and_modules};
20pub use oxdock_parser::{Guard, Step, StepKind};
21pub use oxdock_process::shell_program;
22use std::collections::BTreeMap;
23
24mod endpoints;
25pub use endpoints::EndpointFlags;
26#[cfg(feature = "net")]
27pub use endpoints::build_registry;
28#[cfg(feature = "net")]
29use oxdock_net_plugin::EndpointRegistry;
30
31/// Host modules bundled into the CLI runner. With `net` this exposes STD
32/// plus the NET virtual-endpoint toolkit (`NET_LISTEN`, `NET_ACCEPT`,
33/// `NET_CLOSE`, `NET_CONNECT`, `NET_PORT`, `NET_ADDR`); with `--features
34/// ssh` it additionally registers the SSH server and client (`SSH_SERVE`,
35/// `SSH_ACCEPT`, `SSH_DEQUEUE`, `SSH_PUMP_CHANNEL`, `SSH_CLOSE`,
36/// `SSH_CONNECT`, `SSH_PUMP`) from oxdock-ssh-plugin. Without `net` only
37/// STD builtins remain.
38fn cli_host_modules() -> Vec<HostModule<DefaultProcessManager>> {
39    cli_host_modules_with(None)
40}
41
42/// Host modules resolving virtual endpoints through `registry`: the CLI
43/// builds it from `--listen`/`-p`/`--offline` before parsing so bind
44/// conflicts fail fast. `None` registers default module instances (enough
45/// for parse-time name resolution); without `net` no modules are pushed.
46/// The parameter type is feature-dependent because the registry type only
47/// exists with `net`; callers pass `Some` with `net` and `None` without.
48fn cli_host_modules_with(
49    #[cfg(feature = "net")] registry: Option<&Arc<EndpointRegistry>>,
50    #[cfg(not(feature = "net"))] registry: Option<&Arc<()>>,
51) -> Vec<HostModule<DefaultProcessManager>> {
52    #[cfg(feature = "net")]
53    let mut modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
54    #[cfg(not(feature = "net"))]
55    let modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
56    #[cfg(feature = "net")]
57    {
58        let net_module = match registry {
59            Some(registry) => oxdock_net_plugin::module_with_endpoints(Arc::clone(registry)),
60            None => oxdock_net_plugin::module(),
61        };
62        modules.push(net_module);
63        #[cfg(feature = "ssh")]
64        {
65            let ssh_module = match registry {
66                Some(registry) => oxdock_ssh_plugin::module_with_endpoints(Arc::clone(registry)),
67                None => oxdock_ssh_plugin::module(),
68            };
69            modules.push(ssh_module);
70        }
71    }
72    let _ = registry;
73    modules
74}
75
76/// Host types bundled into the CLI runner alongside [`cli_host_modules`].
77fn cli_host_types() -> Vec<&'static TypeDescriptor> {
78    #[cfg(feature = "net")]
79    let net: &[&'static TypeDescriptor] = &[oxdock_net_plugin::NetListenerTag::descriptor()];
80    #[cfg(not(feature = "net"))]
81    let net: &[&'static TypeDescriptor] = &[];
82    #[cfg(feature = "ssh")]
83    let ssh: &[&'static TypeDescriptor] = &[
84        oxdock_ssh_plugin::SshServerTag::descriptor(),
85        oxdock_ssh_plugin::SshSessionTag::descriptor(),
86    ];
87    #[cfg(not(feature = "ssh"))]
88    let ssh: &[&'static TypeDescriptor] = &[];
89    net.iter().chain(ssh.iter()).copied().collect()
90}
91
92/// Parse a CLI script against STD plus any bundled host modules. Without
93/// extra modules this is exactly `parse_script`, so base-build behavior
94/// never changes.
95fn parse_cli_script(script: &str) -> Result<Vec<Step>> {
96    let modules = cli_host_modules();
97    if modules.is_empty() {
98        parse_script(script)
99    } else {
100        let mut engine = Engine::new();
101        for module in modules {
102            engine.register_module(module);
103        }
104        parse_script_with_modules(script, engine.module_table())
105    }
106}
107
108pub fn run() -> Result<()> {
109    init_temp_gc();
110    let workspace_root = discover_workspace_root().context("guard workspace root")?;
111
112    let mut args = std::env::args().skip(1);
113    // `--help`/`-h` surfaces as the usage text in the parse error (parse must
114    // not exit the process itself: it is public library API). Print it and
115    // succeed so the binary exits 0.
116    let opts = match Options::parse(&mut args, &workspace_root) {
117        Ok(opts) => opts,
118        Err(err) if err.to_string() == usage() => {
119            print!("{err}");
120            return Ok(());
121        }
122        Err(err) => return Err(err),
123    };
124    execute(opts, workspace_root)
125}
126
127#[derive(Debug, Clone)]
128pub enum ScriptSource {
129    Path(GuardedPath),
130    Stdin,
131}
132
133#[derive(Debug, Clone)]
134pub struct Options {
135    pub script: ScriptSource,
136    pub shell: bool,
137    pub endpoints: EndpointFlags,
138}
139
140impl Options {
141    pub fn parse(
142        args: &mut impl Iterator<Item = String>,
143        workspace_root: &GuardedPath,
144    ) -> Result<Self> {
145        use lexopt::Arg::{Long, Short, Value};
146
147        let mut script: Option<ScriptSource> = None;
148        let mut shell = false;
149        let mut endpoints = EndpointFlags::default();
150        let mut set_script = |source: ScriptSource, origin: &str| -> Result<()> {
151            if script.is_some() {
152                bail!("script given multiple times ({origin})");
153            }
154            script = Some(source);
155            Ok(())
156        };
157        // Pass the stream unfiltered: an explicit empty value (for
158        // example `--script ""`) is a real token boundary, so stripping
159        // empties up front would shift every following value. Bare empty
160        // positionals are skipped in the `Value` arm instead.
161        let mut parser = lexopt::Parser::from_args(args.by_ref());
162        while let Some(arg) = parser.next()? {
163            match arg {
164                Long("script") => {
165                    let path = value_string(
166                        parser
167                            .value()
168                            .map_err(|_| anyhow::anyhow!("--script requires a path"))?,
169                    )?;
170                    if path.is_empty() {
171                        bail!("--script requires a path");
172                    }
173                    if path == "-" {
174                        set_script(ScriptSource::Stdin, "--script -")?;
175                    } else {
176                        set_script(
177                            ScriptSource::Path(
178                                workspace_root
179                                    .join(&path)
180                                    .with_context(|| format!("guard script path {path}"))?,
181                            ),
182                            "--script",
183                        )?;
184                    }
185                }
186                Long("shell") => {
187                    shell = true;
188                }
189                Long("listen") => {
190                    let raw = value_string(
191                        parser
192                            .value()
193                            .map_err(|_| anyhow::anyhow!("--listen requires an address"))?,
194                    )?;
195                    #[cfg(not(feature = "net"))]
196                    {
197                        // Evaluate the pure validator so it stays compiled
198                        // and covered in lean builds; the feature error below
199                        // still wins regardless of the value.
200                        let _ = endpoints::parse_listen_arg(&raw);
201                        bail!(
202                            "--listen/-p require the `net` feature (rebuild with --features net)"
203                        );
204                    }
205                    #[cfg(feature = "net")]
206                    endpoints.listens.push(endpoints::parse_listen_arg(&raw)?);
207                }
208                Short('p') => {
209                    let raw = value_string(
210                        parser
211                            .value()
212                            .map_err(|_| anyhow::anyhow!("-p requires outer:inner"))?,
213                    )?;
214                    #[cfg(not(feature = "net"))]
215                    {
216                        // Same as `--listen` above: keep the pure outer
217                        // validation live in lean builds; the feature error
218                        // below still wins.
219                        let _ = endpoints::parse_publish_arg(&raw);
220                        bail!(
221                            "--listen/-p require the `net` feature (rebuild with --features net)"
222                        );
223                    }
224                    #[cfg(feature = "net")]
225                    endpoints
226                        .publishes
227                        .push(endpoints::parse_publish_arg(&raw)?);
228                }
229                Long("offline") => {
230                    endpoints.offline = true;
231                }
232                Long("help") | Short('h') => {
233                    bail!("{}", usage());
234                }
235                Value(value) => {
236                    let text = value_string(value)?;
237                    if text.is_empty() {
238                        continue;
239                    }
240                    if text == "-" {
241                        set_script(ScriptSource::Stdin, "positional `-`")?;
242                    } else {
243                        set_script(
244                            ScriptSource::Path(
245                                workspace_root
246                                    .join(&text)
247                                    .with_context(|| format!("guard script path {text}"))?,
248                            ),
249                            "positional argument",
250                        )?;
251                    }
252                }
253                Long(other) => bail!("unexpected flag: --{other}"),
254                Short(other) => bail!("unexpected flag: -{other}"),
255            }
256        }
257
258        let script = script.unwrap_or(ScriptSource::Stdin);
259
260        Ok(Self {
261            script,
262            shell,
263            endpoints,
264        })
265    }
266}
267
268/// Option/positional text out of a lexopt value. Inputs arrive as
269/// `String`, so non-UTF8 is unreachable in practice; fail loudly anyway.
270fn value_string(value: std::ffi::OsString) -> Result<String> {
271    value
272        .into_string()
273        .map_err(|_| anyhow::anyhow!("argument must be UTF-8"))
274}
275
276/// Human-readable CLI usage, printed for `--help`/`-h`.
277pub fn usage() -> String {
278    let version = env!("CARGO_PKG_VERSION");
279    let description = env!("CARGO_PKG_DESCRIPTION");
280    #[cfg(feature = "net")]
281    {
282        indoc::formatdoc! {"
283            oxdock {version} — {description}
284            Usage: oxdock [OPTIONS] [SCRIPT]
285              SCRIPT             script file path (same as `--script <file>`); `-` reads stdin
286              --script <file|->  script file under the workspace root, or `-` for stdin
287              --shell            run the script, then drop into an interactive shell (requires a TTY)
288              --listen <addr>    expose a logical service port ([host:]port, repeatable)
289              -p <[host:]outer:inner>  map outer port to an inner service port or name (repeatable; outer 0 is ephemeral)
290              --offline          open no sockets (conflicts with --listen/-p)
291              --help, -h         print this help and exit
292            With no script given, reads the script from stdin (must be piped unless `--shell`).
293            Scripts declare logical endpoints (a port like 2251); the flags above map them to interfaces.
294        "}
295    }
296    #[cfg(not(feature = "net"))]
297    {
298        indoc::formatdoc! {"
299            oxdock {version} — {description}
300            Usage: oxdock [OPTIONS] [SCRIPT]
301              SCRIPT             script file path (same as `--script <file>`); `-` reads stdin
302              --script <file|->  script file under the workspace root, or `-` for stdin
303              --shell            run the script, then drop into an interactive shell (requires a TTY)
304              --offline          open no sockets (endpoint flags require the `net` feature)
305              --help, -h         print this help and exit
306            With no script given, reads the script from stdin (must be piped unless `--shell`).
307            Endpoint flags (--listen/-p) require the `net` feature (rebuild with --features net).
308        "}
309    }
310}
311
312pub fn execute(opts: Options, workspace_root: GuardedPath) -> Result<()> {
313    init_temp_gc();
314    execute_with_shell_runner(opts, workspace_root, run_shell, true)
315}
316
317/// Output of a script execution (issue #131).
318///
319/// The snapshot directory is created lazily: [`ExecutionResult::snapshot`]
320/// stays unmaterialized when the script never touches snapshot-rooted state
321/// (e.g. `WORKSPACE LOCAL`-only or empty scripts), in which case
322/// [`ExecutionResult::has_snapshot`] is false and `final_cwd` points under
323/// the workspace root.
324pub struct ExecutionResult {
325    /// Shared ownership of the snapshot backing dir. The physical directory
326    /// lives exactly as long as the last surviving clone (normally this
327    /// struct, since execution-internal clones are dropped before return).
328    pub snapshot: Arc<LazyGuardedTempDir>,
329    /// Actual final cwd: inside the snapshot when materialized, otherwise
330    /// under the workspace/local root.
331    pub final_cwd: GuardedPath,
332    /// Top-level script variable bindings captured at completion, keyed by
333    /// variable name. Empty when the script is empty. Populated exclusively
334    /// by [`execute_with_result`]; `--shell` runs never produce one.
335    pub bindings: BTreeMap<String, Value>,
336}
337
338impl ExecutionResult {
339    /// Whether the run materialized the snapshot tempdir.
340    pub fn has_snapshot(&self) -> bool {
341        self.snapshot.is_materialized()
342    }
343
344    /// Borrow the snapshot root iff materialized.
345    pub fn snapshot_path(&self) -> Option<&GuardedPath> {
346        self.snapshot.get()
347    }
348}
349
350pub fn execute_with_result(opts: Options, workspace_root: GuardedPath) -> Result<ExecutionResult> {
351    if opts.shell {
352        bail!("execute_with_result does not support --shell");
353    }
354
355    // Read + parse BEFORE any tempdir exists so LOCAL-only scripts never
356    // create a snapshot directory they never use (issue #131).
357    let script = read_script(&opts.script, &workspace_root)?;
358
359    let mut final_cwd = workspace_root.clone();
360    let snapshot = Arc::new(LazyGuardedTempDir::new());
361    if !script.trim().is_empty() {
362        // Bind endpoint sockets before parsing: conflicts fail fast,
363        // never parse-then-fail-on-bind.
364        #[cfg(feature = "net")]
365        let registry = build_registry(&opts.endpoints)?;
366        #[cfg(not(feature = "net"))]
367        check_no_net_endpoints(&opts.endpoints)?;
368        let steps = parse_cli_script(&script)?;
369        #[cfg(feature = "net")]
370        let output = run_steps_with_lazy_snapshot_and_modules(
371            &workspace_root,
372            &steps,
373            ExecIo::new(),
374            cli_host_modules_with(Some(&registry)),
375            cli_host_types(),
376        )?;
377        #[cfg(not(feature = "net"))]
378        let output = run_steps_with_lazy_snapshot_and_modules(
379            &workspace_root,
380            &steps,
381            ExecIo::new(),
382            cli_host_modules_with(None),
383            cli_host_types(),
384        )?;
385        final_cwd = output.final_cwd;
386        return Ok(ExecutionResult {
387            snapshot: output.snapshot,
388            final_cwd,
389            bindings: output.bindings,
390        });
391    }
392
393    Ok(ExecutionResult {
394        snapshot,
395        final_cwd,
396        bindings: BTreeMap::new(),
397    })
398}
399
400/// Report ephemeral outer resolutions (`-p 0:<inner>`) to stderr so the
401/// runner learns the real ports. Fixed mappings need no report: the flags
402/// already name them.
403#[cfg(feature = "net")]
404fn report_ephemeral_publishes(flags: &EndpointFlags, registry: &Arc<EndpointRegistry>) {
405    use oxdock_net_plugin::{EndpointKey, Protocol, parse_endpoint_ref};
406    for (outer, inner) in &flags.publishes {
407        if outer.port() != 0 {
408            continue;
409        }
410        let Ok((protocol, endpoint)) = parse_endpoint_ref(inner, "-p") else {
411            continue;
412        };
413        let key = EndpointKey {
414            protocol: protocol.unwrap_or(Protocol::Tcp),
415            endpoint,
416        };
417        match registry.resolve_endpoint(&key) {
418            Ok(addr) => eprintln!("oxdock: published {addr} -> {inner}"),
419            Err(_) => eprintln!("oxdock: published <unbound> -> {inner}"),
420        }
421    }
422}
423
424/// Without `net`, endpoint sockets cannot exist: `--listen`/`-p` are
425/// rejected (parse time already bails; this covers programmatic `Options`),
426/// while `--offline` or no flags proceed socketless.
427#[cfg(not(feature = "net"))]
428fn check_no_net_endpoints(flags: &EndpointFlags) -> Result<()> {
429    if !flags.listens.is_empty() || !flags.publishes.is_empty() {
430        bail!("--listen/-p require the `net` feature (rebuild with --features net)");
431    }
432    Ok(())
433}
434
435/// Read the script source without creating any execution state.
436fn read_script(source: &ScriptSource, workspace_root: &GuardedPath) -> Result<String> {
437    match source {
438        ScriptSource::Path(path) => {
439            let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
440            resolver
441                .read_to_string(path)
442                .with_context(|| format!("failed to read script at {}", path.display()))
443        }
444        ScriptSource::Stdin => {
445            let mut buf = String::new();
446            io::stdin()
447                .lock()
448                .read_to_string(&mut buf)
449                .context("failed to read script from stdin")?;
450            Ok(buf)
451        }
452    }
453}
454
455fn execute_with_shell_runner<F>(
456    opts: Options,
457    workspace_root: GuardedPath,
458    shell_runner: F,
459    require_tty: bool,
460) -> Result<()>
461where
462    F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
463{
464    #[cfg(windows)]
465    maybe_reexec_shell_to_temp(&opts)?;
466
467    // Interpret a tiny Dockerfile-ish script. No tempdir exists yet: the
468    // snapshot materializes lazily on first snapshot-targeted step, so an
469    // empty non-shell run creates nothing at all (issue #131).
470    let script = match &opts.script {
471        ScriptSource::Path(path) => {
472            // Read script path via PathResolver rooted at the workspace so
473            // script files are validated to live under the workspace.
474            let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
475            resolver
476                .read_to_string(path)
477                .with_context(|| format!("failed to read script at {}", path.display()))?
478        }
479        ScriptSource::Stdin => {
480            let stdin = io::stdin();
481            if stdin.is_terminal() {
482                // No piped script provided. If the caller requested `--shell`
483                // allow running with an initially-empty script so we can either
484                // drop into the interactive shell or open the editor later.
485                // Otherwise, require a script on stdin.
486                if opts.shell {
487                    String::new()
488                } else {
489                    bail!(
490                        "no stdin detected; pass --script <file> or pipe a script into stdin (use --script - if explicit)"
491                    );
492                }
493            } else {
494                let mut buf = String::new();
495                stdin
496                    .lock()
497                    .read_to_string(&mut buf)
498                    .context("failed to read script from stdin")?;
499                buf
500            }
501        }
502    };
503
504    // Parse and run steps if we have a non-empty script. Empty scripts are
505    // valid when `--shell` is requested and the caller didn't pipe a script.
506    // Use the caller's workspace as the build context so WORKSPACE LOCAL can
507    // hop back and so COPY can source from the original tree if needed.
508    // Capture the final working directory so shells inherit whatever WORKDIR
509    // the script ended on.
510    let mut final_cwd = workspace_root.clone();
511    let mut snapshot = Arc::new(LazyGuardedTempDir::new());
512    let mut fs: Option<Box<dyn WorkspaceFs>> = None;
513    if !script.trim().is_empty() {
514        // Bind endpoint sockets before parsing: conflicts fail fast,
515        // never parse-then-fail-on-bind.
516        #[cfg(feature = "net")]
517        let registry = build_registry(&opts.endpoints)?;
518        #[cfg(not(feature = "net"))]
519        check_no_net_endpoints(&opts.endpoints)?;
520        #[cfg(feature = "net")]
521        report_ephemeral_publishes(&opts.endpoints, &registry);
522        let steps = parse_cli_script(&script)?;
523        // If we are running a script from a file, we might have stdin available for the script itself.
524        // If we read the script from stdin, then stdin is consumed.
525        // But if opts.script is ScriptSource::Path, stdin is still available.
526
527        let mut stdin_handle: Option<SharedInput> = None;
528        if let ScriptSource::Path(_) = opts.script {
529            let stdin = io::stdin();
530            if !stdin.is_terminal() {
531                // Wrap stdin in SharedInput (Arc<Mutex<dyn Read + Send>>)
532                // Note: std::io::Stdin is a handle, but we need an owned Read + Send.
533                // std::io::stdin() returns Stdin, which implements Read + Send.
534                // However, we need to be careful about locking.
535                // We can wrap the Stdin struct directly.
536                stdin_handle = Some(Arc::new(Mutex::new(stdin)));
537            }
538        }
539
540        let mut io_cfg = ExecIo::new();
541        io_cfg.set_stdin(stdin_handle);
542        #[cfg(feature = "net")]
543        let output = run_steps_with_lazy_snapshot_and_modules(
544            &workspace_root,
545            &steps,
546            io_cfg,
547            cli_host_modules_with(Some(&registry)),
548            cli_host_types(),
549        )?;
550        #[cfg(not(feature = "net"))]
551        let output = run_steps_with_lazy_snapshot_and_modules(
552            &workspace_root,
553            &steps,
554            io_cfg,
555            cli_host_modules_with(None),
556            cli_host_types(),
557        )?;
558        final_cwd = output.final_cwd;
559        snapshot = output.snapshot;
560        fs = Some(output.fs);
561    }
562
563    // If requested, drop into an interactive shell after running the script.
564    if opts.shell {
565        if require_tty && !has_controlling_tty() {
566            bail!("--shell requires a tty (no controlling tty available)");
567        }
568        // The shell needs a concrete directory: materialize here at shell
569        // entry (not at startup) when the script left the snapshot pending,
570        // then converge the cwd onto the shared concrete root. An empty
571        // script starts the shell in a fresh snapshot directory.
572        match fs.as_ref() {
573            Some(fs) => {
574                if fs.is_snapshot_pending() {
575                    snapshot
576                        .materialize()
577                        .context("failed to create shell temp dir")?;
578                }
579                final_cwd = fs.concretize_cwd(&final_cwd);
580            }
581            None => {
582                snapshot
583                    .materialize()
584                    .context("failed to create shell temp dir")?;
585                final_cwd = snapshot
586                    .get()
587                    .cloned()
588                    .expect("shell snapshot materialized above");
589            }
590        }
591        return shell_runner(&final_cwd, &workspace_root);
592    }
593
594    Ok(())
595}
596
597#[cfg(test)]
598fn execute_for_test<F>(opts: Options, workspace_root: GuardedPath, shell_runner: F) -> Result<()>
599where
600    F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
601{
602    execute_with_shell_runner(opts, workspace_root, shell_runner, false)
603}
604
605fn has_controlling_tty() -> bool {
606    // Prefer checking whether stdin or stderr is a terminal. This avoids
607    // directly opening device files via `std::fs` while still detecting
608    // whether an interactive tty is available in the common cases.
609    #[cfg(unix)]
610    {
611        io::stdin().is_terminal() || io::stderr().is_terminal()
612    }
613
614    #[cfg(windows)]
615    {
616        io::stdin().is_terminal() || io::stderr().is_terminal()
617    }
618
619    #[cfg(not(any(unix, windows)))]
620    {
621        false
622    }
623}
624
625#[cfg(windows)]
626fn maybe_reexec_shell_to_temp(opts: &Options) -> Result<()> {
627    // Only used for interactive shells. Copy the binary to a temp path and run it there so the
628    // original target exe is free for rebuilding while the shell stays open.
629    if !opts.shell {
630        return Ok(());
631    }
632    if std::env::var(oxdock_env::SHELL_REEXEC).ok().as_deref() == Some("1") {
633        return Ok(());
634    }
635
636    let self_path = std::env::current_exe().context("determine current executable")?;
637    let base_temp =
638        GuardedPath::new_root(std::env::temp_dir().as_path()).context("guard system temp dir")?;
639    let ts = std::time::SystemTime::now()
640        .duration_since(std::time::UNIX_EPOCH)
641        .unwrap_or_default()
642        .as_millis();
643    let temp_file = base_temp
644        .join(&format!("oxdock-shell-{ts}-{}.exe", std::process::id()))
645        .context("construct temp shell path")?;
646
647    // Copy the current executable into the temporary location via a
648    // resolver whose root is the temp directory. The source may live
649    // outside the temp dir, so use `copy_file_from_external`.
650    let temp_root_guard = temp_file
651        .parent()
652        .ok_or_else(|| anyhow::anyhow!("temp path unexpectedly missing parent"))?;
653    let resolver_temp = PathResolver::new(temp_root_guard.as_path(), temp_root_guard.as_path())?;
654    let dest = temp_file;
655    #[allow(clippy::disallowed_types)]
656    let source = oxdock_fs::UnguardedPath::external(self_path);
657    resolver_temp
658        .copy_file_from_unguarded(&source, &dest)
659        .with_context(|| format!("failed to copy shell runner to {}", dest.display()))?;
660
661    let mut cmd = CommandBuilder::new(dest.as_path());
662    cmd.args(std::env::args_os().skip(1));
663    cmd.env(oxdock_env::SHELL_REEXEC, "1");
664    cmd.spawn()
665        .with_context(|| format!("failed to spawn shell from {}", dest.display()))?;
666
667    // Exit immediately so the original binary can be rebuilt while the shell child stays running.
668    std::process::exit(0);
669}
670
671pub fn run_script(workspace_root: &GuardedPath, steps: &[Step]) -> Result<()> {
672    run_steps_with_context(workspace_root, workspace_root, steps)
673}
674
675fn shell_banner(cwd: &GuardedPath, workspace_root: &GuardedPath) -> String {
676    #[cfg(windows)]
677    let cwd_disp = oxdock_fs::command_path(cwd).as_ref().display().to_string();
678    #[cfg(windows)]
679    let workspace_disp = oxdock_fs::command_path(workspace_root)
680        .as_ref()
681        .display()
682        .to_string();
683
684    #[cfg(not(windows))]
685    let cwd_disp = cwd.display().to_string();
686    #[cfg(not(windows))]
687    let workspace_disp = workspace_root.display().to_string();
688
689    let pkg = env::var(oxdock_env::CARGO_PKG_NAME)
690        .unwrap_or_else(|_| oxdock_env::FALLBACK_APP_NAME.to_string());
691    indoc::formatdoc! {"
692        {pkg} shell workspace
693          cwd: {cwd_disp}
694          source: workspace root at {workspace_disp}
695          lifetime: temporary directory created for this shell session; it disappears when you exit
696          creation: temp workspace starts empty unless your script copies files into it
697
698          WARNING: This shell still runs on your host filesystem and is **not** isolated!
699    "}
700}
701
702fn run_shell(cwd: &GuardedPath, workspace_root: &GuardedPath) -> Result<()> {
703    oxdock_process::spawn_interactive_shell(cwd, workspace_root, &shell_banner(cwd, workspace_root))
704}
705
706// `command_path` now lives in `oxdock-fs` to centralize Path usage.
707
708#[cfg(test)]
709mod tests {
710    use super::*;
711    use indoc::indoc;
712    use oxdock_fs::PathResolver;
713    use std::cell::{Cell, RefCell};
714
715    #[cfg_attr(
716        miri,
717        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
718    )]
719    #[test]
720    fn shell_runner_receives_final_workdir() -> Result<()> {
721        let workspace = GuardedPath::tempdir()?;
722        let workspace_root = workspace.as_guarded_path().clone();
723        let script_path = workspace_root.join("script.ox")?;
724        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
725        let script = indoc! {"
726            WRITE temp.txt 123
727            WORKDIR sub
728        "};
729        resolver.write_file(&script_path, script.as_bytes())?;
730
731        let opts = Options {
732            script: ScriptSource::Path(script_path),
733            shell: true,
734            endpoints: EndpointFlags::default(),
735        };
736
737        let observed = Cell::new(false);
738        execute_for_test(opts, workspace_root.clone(), |cwd, _| {
739            assert!(
740                cwd.as_path().ends_with("sub"),
741                "final cwd should end in WORKDIR target, got {}",
742                cwd.display()
743            );
744
745            let temp_root = GuardedPath::new_root(cwd.root())
746                .context("construct guard for temp workspace root")?;
747            let sub_dir = temp_root.join("sub")?;
748            assert_eq!(
749                cwd.as_path(),
750                sub_dir.as_path(),
751                "shell runner cwd should match guarded sub dir"
752            );
753            let temp_file = temp_root.join("temp.txt")?;
754            let temp_resolver = PathResolver::new(temp_root.as_path(), temp_root.as_path())?;
755            let contents = temp_resolver.read_to_string(&temp_file)?;
756            assert!(
757                contents.contains("123"),
758                "expected WRITE command to materialize temp file"
759            );
760            observed.set(true);
761            Ok(())
762        })?;
763
764        assert!(
765            observed.into_inner(),
766            "shell runner closure should have been invoked"
767        );
768        Ok(())
769    }
770
771    #[cfg_attr(
772        miri,
773        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
774    )]
775    #[test]
776    fn options_parse_requires_script_path_value() {
777        let workspace = GuardedPath::tempdir().expect("tempdir");
778        let mut args = vec!["--script".to_string()].into_iter();
779        let err = Options::parse(&mut args, workspace.as_guarded_path())
780            .expect_err("expected missing path error");
781        assert!(err.to_string().contains("--script requires a path"));
782    }
783
784    #[cfg_attr(
785        miri,
786        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
787    )]
788    #[test]
789    fn options_parse_script_path_and_shell() {
790        let workspace = GuardedPath::tempdir().expect("tempdir");
791        let workspace_root = workspace.as_guarded_path().clone();
792        let script_path = workspace_root.join("script.txt").expect("script path");
793        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
794            .expect("resolver");
795        resolver
796            .write_file(&script_path, b"WRITE out.txt hi")
797            .expect("write script");
798        let mut args = vec![
799            "--script".to_string(),
800            "script.txt".to_string(),
801            "--shell".to_string(),
802        ]
803        .into_iter();
804        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
805        assert!(opts.shell);
806        match opts.script {
807            ScriptSource::Path(path) => assert_eq!(path, script_path),
808            ScriptSource::Stdin => panic!("expected path script"),
809        }
810    }
811
812    #[cfg_attr(
813        miri,
814        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
815    )]
816    #[test]
817    fn options_parse_positional_script_path() {
818        let workspace = GuardedPath::tempdir().expect("tempdir");
819        let workspace_root = workspace.as_guarded_path().clone();
820        let mut args = vec!["script.txt".to_string()].into_iter();
821        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
822        assert!(!opts.shell);
823        match opts.script {
824            ScriptSource::Path(path) => assert_eq!(
825                path,
826                workspace_root.join("script.txt").expect("script path")
827            ),
828            ScriptSource::Stdin => panic!("expected path script"),
829        }
830    }
831
832    #[cfg_attr(
833        miri,
834        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
835    )]
836    #[test]
837    fn options_parse_positional_dash_reads_stdin() {
838        let workspace = GuardedPath::tempdir().expect("tempdir");
839        let mut args = vec!["-".to_string()].into_iter();
840        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
841        assert!(matches!(opts.script, ScriptSource::Stdin));
842    }
843
844    #[cfg_attr(
845        miri,
846        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
847    )]
848    #[test]
849    fn options_parse_rejects_duplicate_script_sources() {
850        let workspace = GuardedPath::tempdir().expect("tempdir");
851        let workspace_root = workspace.as_guarded_path().clone();
852        let mut args = vec![
853            "a.ox".to_string(),
854            "--script".to_string(),
855            "b.ox".to_string(),
856        ]
857        .into_iter();
858        let err = Options::parse(&mut args, &workspace_root)
859            .expect_err("expected duplicate script error");
860        assert!(err.to_string().contains("multiple times"), "{err:?}");
861
862        let mut args = vec!["a.ox".to_string(), "b.ox".to_string()].into_iter();
863        let err = Options::parse(&mut args, &workspace_root)
864            .expect_err("expected duplicate script error");
865        assert!(err.to_string().contains("multiple times"), "{err:?}");
866    }
867
868    #[cfg_attr(
869        miri,
870        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
871    )]
872    #[test]
873    fn options_parse_rejects_unknown_flags() {
874        let workspace = GuardedPath::tempdir().expect("tempdir");
875        let mut args = vec!["--frobnicate".to_string()].into_iter();
876        let err = Options::parse(&mut args, workspace.as_guarded_path())
877            .expect_err("expected unknown flag error");
878        assert!(err.to_string().contains("unexpected flag"), "{err:?}");
879    }
880
881    #[test]
882    fn usage_describes_positional_script_and_help() {
883        let text = usage();
884        assert!(text.contains("Usage: oxdock"), "{text}");
885        assert!(text.contains("SCRIPT"), "{text}");
886        assert!(text.contains("--script"), "{text}");
887        assert!(text.contains("--help"), "{text}");
888        assert!(text.contains("--offline"), "{text}");
889        #[cfg(feature = "net")]
890        {
891            assert!(text.contains("--listen"), "{text}");
892            assert!(text.contains("-p <[host:]outer:inner>"), "{text}");
893        }
894        #[cfg(not(feature = "net"))]
895        {
896            assert!(!text.contains("--listen <addr>"), "{text}");
897            assert!(!text.contains("-p <[host:]outer:inner>"), "{text}");
898            assert!(text.contains("require the `net` feature"), "{text}");
899        }
900        // Tagline is single-sourced from the package manifest, not hardcoded.
901        assert!(text.contains(env!("CARGO_PKG_DESCRIPTION")), "{text}");
902    }
903
904    #[cfg(feature = "net")]
905    #[cfg_attr(
906        miri,
907        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
908    )]
909    #[test]
910    fn options_parse_endpoint_flags() {
911        // Pure flag parsing: no sockets open, but tempdir keeps the
912        // ignore uniform with the neighboring parse tests.
913        let workspace = GuardedPath::tempdir().expect("tempdir");
914        let mut args = vec![
915            "--listen".to_string(),
916            "0.0.0.0:2251".to_string(),
917            "-p".to_string(),
918            "2222:demo-proxy".to_string(),
919            "-p".to_string(),
920            "0:2252".to_string(),
921            "-".to_string(),
922        ]
923        .into_iter();
924        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
925        assert_eq!(opts.endpoints.listens.len(), 1);
926        assert_eq!(opts.endpoints.publishes.len(), 2);
927        assert!(!opts.endpoints.offline);
928        assert!(matches!(opts.script, ScriptSource::Stdin));
929    }
930
931    #[cfg_attr(
932        miri,
933        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
934    )]
935    #[test]
936    fn options_parse_offline_flag() {
937        let workspace = GuardedPath::tempdir().expect("tempdir");
938        let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
939        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
940        assert!(opts.endpoints.offline);
941    }
942
943    #[cfg(feature = "net")]
944    #[cfg_attr(
945        miri,
946        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
947    )]
948    #[test]
949    fn options_parse_rejects_bad_endpoint_flags() {
950        let workspace = GuardedPath::tempdir().expect("tempdir");
951        for args in [
952            vec!["--listen"],
953            vec!["--listen", "0.0.0.0:0"],
954            vec!["-p"],
955            vec!["-p", "2222"],
956            vec!["-p", "2222:0"],
957        ] {
958            let mut args = args.into_iter().map(str::to_string);
959            Options::parse(&mut args, workspace.as_guarded_path())
960                .expect_err("bad endpoint flag must fail");
961        }
962    }
963
964    #[cfg_attr(
965        miri,
966        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
967    )]
968    #[test]
969    fn options_parse_empty_values_hold_token_boundaries() {
970        // Regression: explicit empty values must not shift the stream.
971        // `--script ""` bails instead of consuming the next token, and a
972        // bare empty positional is skipped like before.
973        let workspace = GuardedPath::tempdir().expect("tempdir");
974        let mut args = vec![
975            "--script".to_string(),
976            "".to_string(),
977            "--shell".to_string(),
978        ]
979        .into_iter();
980        let err = Options::parse(&mut args, workspace.as_guarded_path())
981            .expect_err("empty script path must fail");
982        assert!(
983            err.to_string().contains("--script requires a path"),
984            "{err:?}"
985        );
986        let mut args = vec!["".to_string(), "-".to_string()].into_iter();
987        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
988        assert!(matches!(opts.script, ScriptSource::Stdin));
989    }
990
991    #[cfg(feature = "net")]
992    #[cfg_attr(
993        miri,
994        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
995    )]
996    #[test]
997    fn options_parse_accepts_equals_and_attached_forms() {
998        // lexopt-native spellings: `--flag=value`, attached short values,
999        // and `--` separating positionals.
1000        let workspace = GuardedPath::tempdir().expect("tempdir");
1001        let workspace_root = workspace.as_guarded_path().clone();
1002        let mut args = vec![
1003            "--listen=0.0.0.0:2251".to_string(),
1004            "-p2222:demo-proxy".to_string(),
1005            "--".to_string(),
1006            "script.ox".to_string(),
1007        ]
1008        .into_iter();
1009        let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1010        assert_eq!(opts.endpoints.listens.len(), 1);
1011        assert_eq!(opts.endpoints.publishes.len(), 1);
1012        match opts.script {
1013            ScriptSource::Path(path) => {
1014                assert_eq!(path, workspace_root.join("script.ox").expect("script path"))
1015            }
1016            ScriptSource::Stdin => panic!("expected path script after --"),
1017        }
1018    }
1019
1020    #[cfg_attr(
1021        miri,
1022        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1023    )]
1024    #[test]
1025    fn options_parse_help_returns_usage_error_without_exiting() {
1026        // Regression: parse is public library API and must return instead of
1027        // terminating the process; `run()` turns this error into a clean exit 0.
1028        let workspace = GuardedPath::tempdir().expect("tempdir");
1029        for flag in ["--help", "-h"] {
1030            let mut args = vec![flag.to_string()].into_iter();
1031            let err = Options::parse(&mut args, workspace.as_guarded_path())
1032                .expect_err("help flag must not parse as options");
1033            assert_eq!(err.to_string(), usage());
1034        }
1035    }
1036
1037    #[cfg_attr(
1038        miri,
1039        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1040    )]
1041    #[test]
1042    fn execute_with_result_runs_script() {
1043        let workspace = GuardedPath::tempdir().expect("tempdir");
1044        let workspace_root = workspace.as_guarded_path().clone();
1045        let script_path = workspace_root.join("script.txt").expect("script path");
1046        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1047            .expect("resolver");
1048        resolver
1049            .write_file(&script_path, b"WRITE out.txt hi")
1050            .expect("write script");
1051        let opts = Options {
1052            script: ScriptSource::Path(script_path),
1053            shell: false,
1054            endpoints: EndpointFlags::default(),
1055        };
1056        let result = execute_with_result(opts, workspace_root).expect("execute");
1057        let snapshot = result
1058            .snapshot_path()
1059            .expect("default WRITE materializes the snapshot");
1060        assert_eq!(snapshot, &result.final_cwd);
1061        let temp_resolver = PathResolver::new(snapshot.root(), snapshot.root()).expect("resolver");
1062        let out = snapshot.join("out.txt").expect("out path");
1063        let contents = temp_resolver.read_to_string(&out).expect("read out");
1064        assert_eq!(contents.trim(), "hi");
1065    }
1066
1067    #[cfg_attr(
1068        miri,
1069        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1070    )]
1071    #[test]
1072    fn execute_with_result_local_only_creates_no_snapshot() {
1073        let workspace = GuardedPath::tempdir().expect("tempdir");
1074        let workspace_root = workspace.as_guarded_path().clone();
1075        let script_path = workspace_root.join("script.txt").expect("script path");
1076        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1077            .expect("resolver");
1078        resolver
1079            .write_file(&script_path, b"WORKSPACE LOCAL\nWRITE out.txt hi")
1080            .expect("write script");
1081        let opts = Options {
1082            script: ScriptSource::Path(script_path),
1083            shell: false,
1084            endpoints: EndpointFlags::default(),
1085        };
1086        let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1087        assert!(
1088            !result.has_snapshot(),
1089            "WORKSPACE LOCAL-only script must not create a snapshot tempdir"
1090        );
1091        assert!(result.snapshot_path().is_none());
1092        // The write landed in the live workspace tree instead.
1093        let out = workspace_root.join("out.txt").expect("out path");
1094        let contents = resolver.read_to_string(&out).expect("read out");
1095        assert_eq!(contents.trim(), "hi");
1096        // The reported cwd stays under the workspace root.
1097        assert_eq!(result.final_cwd.root(), workspace_root.as_path());
1098    }
1099
1100    #[cfg_attr(
1101        miri,
1102        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1103    )]
1104    #[test]
1105    fn execute_with_result_empty_script_creates_no_snapshot() {
1106        let workspace = GuardedPath::tempdir().expect("tempdir");
1107        let workspace_root = workspace.as_guarded_path().clone();
1108        let script_path = workspace_root.join("empty.txt").expect("script path");
1109        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1110            .expect("resolver");
1111        resolver
1112            .write_file(&script_path, b"")
1113            .expect("write script");
1114        let opts = Options {
1115            script: ScriptSource::Path(script_path),
1116            shell: false,
1117            endpoints: EndpointFlags::default(),
1118        };
1119        let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1120        assert!(
1121            !result.has_snapshot(),
1122            "empty script must not create a snapshot tempdir"
1123        );
1124        assert_eq!(result.final_cwd, workspace_root);
1125    }
1126
1127    #[cfg_attr(
1128        miri,
1129        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1130    )]
1131    #[test]
1132    fn execute_for_test_invokes_shell_runner() -> Result<()> {
1133        let workspace = GuardedPath::tempdir()?;
1134        let workspace_root = workspace.as_guarded_path().clone();
1135        let script_path = workspace_root.join("empty.txt")?;
1136        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1137        resolver.write_file(&script_path, b"")?;
1138        let opts = Options {
1139            script: ScriptSource::Path(script_path),
1140            shell: true,
1141            endpoints: EndpointFlags::default(),
1142        };
1143        let called = RefCell::new(None::<(String, String)>);
1144        execute_for_test(opts, workspace_root.clone(), |cwd, workspace| {
1145            called.replace(Some((cwd.display(), workspace.display())));
1146            // Shell entry converges onto a concrete, existing directory even
1147            // when the script never touched the snapshot (issue #131).
1148            assert!(
1149                cwd.exists(),
1150                "shell cwd must exist on disk, got {}",
1151                cwd.display()
1152            );
1153            Ok(())
1154        })?;
1155        let seen = called.borrow().clone().expect("shell runner called");
1156        assert_eq!(seen.1, workspace_root.display());
1157        Ok(())
1158    }
1159
1160    /// The `ssh` feature wires the SSH host module into the real CLI
1161    /// runner: serve an ephemeral server and close it through
1162    /// `execute_with_result`, no client needed.
1163    #[cfg(feature = "ssh")]
1164    #[cfg_attr(
1165        miri,
1166        ignore = "loopback TCP plus threads plus a Tokio runtime; also GuardedPath::tempdir"
1167    )]
1168    #[test]
1169    fn ssh_feature_serves_and_closes() -> Result<()> {
1170        let workspace = GuardedPath::tempdir()?;
1171        let workspace_root = workspace.as_guarded_path().clone();
1172        let script_path = workspace_root.join("ssh-serve.ox")?;
1173        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1174        let script = indoc! {"
1175            IMPORT [STD, SSH]
1176            LET $m: MAP = SSH_SERVE(\"23301\", {username: \"test\", password: \"test123\"})
1177            SSH_CLOSE($m.server)
1178        "};
1179        resolver.write_file(&script_path, script.as_bytes())?;
1180        let opts = Options {
1181            script: ScriptSource::Path(script_path),
1182            shell: false,
1183            endpoints: EndpointFlags::default(),
1184        };
1185        execute_with_result(opts, workspace_root)?;
1186        Ok(())
1187    }
1188
1189    /// The NET module ships with the `net` feature: bind an ephemeral
1190    /// loopback port and close it through `execute_with_result`, no
1191    /// client needed.
1192    #[cfg(feature = "net")]
1193    #[cfg_attr(
1194        miri,
1195        ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
1196    )]
1197    #[test]
1198    fn net_module_listens_and_closes() -> Result<()> {
1199        let workspace = GuardedPath::tempdir()?;
1200        let workspace_root = workspace.as_guarded_path().clone();
1201        let script_path = workspace_root.join("net-listen.ox")?;
1202        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1203        let script = indoc! {"
1204            IMPORT [STD, NET]
1205            LET $l: MAP = NET_LISTEN(\"23501\", {})
1206            NET_CLOSE($l.listener)
1207        "};
1208        resolver.write_file(&script_path, script.as_bytes())?;
1209        let opts = Options {
1210            script: ScriptSource::Path(script_path),
1211            shell: false,
1212            endpoints: EndpointFlags::default(),
1213        };
1214        execute_with_result(opts, workspace_root)?;
1215        Ok(())
1216    }
1217
1218    /// A `-p`-mapped outer port is observable in-script: route an
1219    /// ephemeral `-p 0:<name>` resolution through `NET_PORT`/`NET_ADDR`
1220    /// into files an inner `RUN` could equally consume via `ENV`.
1221    #[cfg(feature = "net")]
1222    #[cfg_attr(
1223        miri,
1224        ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
1225    )]
1226    #[test]
1227    fn net_port_addr_observe_publish_mapping() -> Result<()> {
1228        let workspace = GuardedPath::tempdir()?;
1229        let workspace_root = workspace.as_guarded_path().clone();
1230        let script_path = workspace_root.join("net-port.ox")?;
1231        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1232        let script = indoc! {"
1233            IMPORT [STD, NET]
1234            LET $port: INT = NET_PORT(\"routed-svc\")
1235            WRITE port.txt \"{{ $port }}\"
1236            LET $addr: STRING = NET_ADDR(\"routed-svc\")
1237            WRITE addr.txt \"{{ $addr }}\"
1238        "};
1239        resolver.write_file(&script_path, script.as_bytes())?;
1240        let opts = Options {
1241            script: ScriptSource::Path(script_path),
1242            shell: false,
1243            endpoints: EndpointFlags {
1244                publishes: vec![(
1245                    std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
1246                    "routed-svc".to_string(),
1247                )],
1248                ..EndpointFlags::default()
1249            },
1250        };
1251        let result = execute_with_result(opts, workspace_root)?;
1252        let snapshot = result
1253            .snapshot_path()
1254            .expect("WRITE materializes the snapshot");
1255        let snapshot_resolver = PathResolver::new(snapshot.root(), snapshot.root())?;
1256        let port_path = snapshot.join("port.txt")?;
1257        let port_text = snapshot_resolver.read_to_string(&port_path)?;
1258        let port: u16 = port_text
1259            .trim()
1260            .parse()
1261            .map_err(|_| anyhow::anyhow!("expected a resolved port, got {port_text:?}"))?;
1262        assert_ne!(port, 0, "ephemeral outer port must resolve");
1263        let addr_path = snapshot.join("addr.txt")?;
1264        let addr_text = snapshot_resolver.read_to_string(&addr_path)?;
1265        assert!(
1266            addr_text.trim().ends_with(&format!(":{port}")),
1267            "dial string must carry the resolved port, got {addr_text:?}"
1268        );
1269        Ok(())
1270    }
1271
1272    /// Without the `ssh` feature the same script must fail to parse:
1273    /// SSH names stay unknown instead of silently changing meaning.
1274    #[cfg(not(feature = "ssh"))]
1275    #[cfg_attr(
1276        miri,
1277        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1278    )]
1279    #[test]
1280    fn ssh_scripts_rejected_without_feature() -> Result<()> {
1281        let workspace = GuardedPath::tempdir()?;
1282        let workspace_root = workspace.as_guarded_path().clone();
1283        let script_path = workspace_root.join("ssh-serve.ox")?;
1284        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1285        let script = indoc! {"
1286            IMPORT [STD, SSH]
1287            LET $m: MAP = SSH_SERVE(\"23301\", {username: \"test\", password: \"test123\"})
1288            SSH_CLOSE($m.server)
1289        "};
1290        resolver.write_file(&script_path, script.as_bytes())?;
1291        let opts = Options {
1292            script: ScriptSource::Path(script_path),
1293            shell: false,
1294            endpoints: EndpointFlags::default(),
1295        };
1296        let err = match execute_with_result(opts, workspace_root) {
1297            Ok(_) => panic!("SSH names must be unknown without the feature"),
1298            Err(err) => err,
1299        };
1300        assert!(err.to_string().contains("SSH"), "{err}");
1301        Ok(())
1302    }
1303
1304    /// Without the `net` feature `--listen`/`-p` are rejected with the
1305    /// feature message, while `--offline` stays accepted as trivially
1306    /// satisfied.
1307    #[cfg(not(feature = "net"))]
1308    #[cfg_attr(
1309        miri,
1310        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1311    )]
1312    #[test]
1313    fn net_flags_rejected_without_feature() {
1314        let workspace = GuardedPath::tempdir().expect("tempdir");
1315        for args in [
1316            vec!["--listen", "0.0.0.0:2251", "-"],
1317            vec!["-p", "2222:2251", "-"],
1318            vec!["--listen=0.0.0.0:2251", "-"],
1319        ] {
1320            let mut args = args.into_iter().map(str::to_string);
1321            let err = Options::parse(&mut args, workspace.as_guarded_path())
1322                .expect_err("endpoint flag must fail without net");
1323            assert!(
1324                err.to_string().contains("require the `net` feature"),
1325                "{err:?}"
1326            );
1327        }
1328        let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
1329        let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1330        assert!(opts.endpoints.offline);
1331    }
1332
1333    /// Without the `net` feature the same script must fail to parse:
1334    /// NET names stay unknown instead of silently changing meaning.
1335    #[cfg(not(feature = "net"))]
1336    #[cfg_attr(
1337        miri,
1338        ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1339    )]
1340    #[test]
1341    fn net_scripts_rejected_without_feature() -> Result<()> {
1342        let workspace = GuardedPath::tempdir()?;
1343        let workspace_root = workspace.as_guarded_path().clone();
1344        let script_path = workspace_root.join("net-listen.ox")?;
1345        let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1346        let script = indoc! {"
1347            IMPORT [STD, NET]
1348            LET $l: MAP = NET_LISTEN(\"23501\", {})
1349            NET_CLOSE($l.listener)
1350        "};
1351        resolver.write_file(&script_path, script.as_bytes())?;
1352        let opts = Options {
1353            script: ScriptSource::Path(script_path),
1354            shell: false,
1355            endpoints: EndpointFlags::default(),
1356        };
1357        let err = match execute_with_result(opts, workspace_root) {
1358            Ok(_) => panic!("NET names must be unknown without the feature"),
1359            Err(err) => err,
1360        };
1361        assert!(err.to_string().contains("NET"), "{err}");
1362        Ok(())
1363    }
1364}
1365
1366#[cfg(all(test, windows))]
1367mod windows_shell_tests {
1368    use super::*;
1369
1370    #[test]
1371    fn command_path_strips_verbatim_prefix() -> Result<()> {
1372        let temp = GuardedPath::tempdir()?;
1373        let converted = oxdock_fs::command_path(temp.as_guarded_path());
1374        let as_str = converted.as_ref().display().to_string();
1375        assert!(
1376            !as_str.starts_with(r"\\?\"),
1377            "expected non-verbatim path, got {as_str}"
1378        );
1379        Ok(())
1380    }
1381}