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
13use oxdock_core::ExecIo;
14pub use oxdock_core::{
15 Engine, EngineOutput, ExecState, ExitRequest, FuncKind, FuncMeta, FuncParam, HostModule,
16 HostRegistration, NativeFn, OxDockFn, OxDockType, PureFn, PushManifestSink, StepCtx,
17 TypeDescriptor, Value, dry_run_closure, exit_code_of, parse_script, parse_script_with_modules,
18 run_steps, run_steps_with_context, run_steps_with_context_result,
19 run_steps_with_lazy_snapshot_and_modules_and_entry, run_steps_with_manager_with_modules,
20 run_steps_with_manager_with_modules_and_entry, run_steps_without_snapshot,
21};
22pub use oxdock_parser::{Guard, Step, StepKind};
23pub use oxdock_process::shell_program;
24use std::collections::BTreeMap;
25
26mod endpoints;
27pub use endpoints::EndpointFlags;
28#[cfg(feature = "mcp")]
29mod mcp;
30
31use oxdock_macros::oxdock_embed;
36oxdock_embed! {
37 name: UsageAssets,
38 script: {
39 INHERIT_ENV [CARGO_PKG_VERSION, CARGO_PKG_DESCRIPTION]
40 FUNC EMIT_BODY($is_net: BOOL): VOID {
41 LET $net_flags: STRING = """
42 --offline open no sockets (endpoint flags require the `net` feature)
43 """
44
45 LET $tail: STRING = """
46 Endpoint flags (--listen/-p) require the `net` feature (rebuild with --features net).
47 """
48
49 IF $is_net {
50 $net_flags = """
51 --listen <addr> expose a logical service port ([host:]port, repeatable)
52 -p <[host:]outer:inner> map outer port to an inner service port or name (repeatable; outer 0 is ephemeral; bare outer binds loopback, prefix 0.0.0.0: for all interfaces)
53 --offline open no sockets (conflicts with --listen/-p)
54 --remote TARGET=CMD bind a REMOTE target to a stdio transport command (repeatable)
55 """
56 $tail = "Scripts declare logical endpoints (a port like 2251); the flags above map them to interfaces."
57 }
58
59 ECHO """
60 oxdock {{ env:CARGO_PKG_VERSION }} — {{ env:CARGO_PKG_DESCRIPTION }}
61
62 Usage: oxdock [OPTIONS] [SCRIPT]
63 SCRIPT script file path (same as `--script <file>`); `-` reads stdin
64 --script <file|-> script file (relative resolves under the OxDock workspace root), or `-` for stdin
65 --shell run the script, then drop into an interactive shell (requires a TTY)
66 --dry-run print the transitive import closure (file:line CMD) instead of running
67 --mcp serve EXPORTed FUNCs as MCP tools over stdio (requires the `mcp` feature)
68 {{ $net_flags }}
69 --help, -h print this help and exit
70 --version, -V print the version and exit
71
72 With no script given, reads the script from stdin (must be piped unless `--shell`).
73 {{ $tail }}
74 """
75 }
76
77 LET $p: PIPE
78 WITH_IO [stdout=$p] {
79 EMIT_BODY(true)
80 }
81 WITH_IO [stdin=$p] WRITE dist/usage-net.txt
82 WITH_IO [stdout=$p] {
83 EMIT_BODY(false)
84 }
85 WITH_IO [stdin=$p] WRITE dist/usage-lean.txt
86 },
87 out_dir: "usage-prebuilt",
88}
89#[cfg(feature = "net")]
90pub use endpoints::build_registry;
91#[cfg(feature = "net")]
92use oxdock_net_plugin::EndpointRegistry;
93#[cfg(feature = "net")]
94mod serve;
95
96fn cli_host_modules() -> Vec<HostModule<DefaultProcessManager>> {
105 cli_host_modules_with(None)
106}
107
108#[cfg(feature = "net")]
112fn cli_host_modules_for_serve() -> Vec<HostModule<DefaultProcessManager>> {
113 cli_host_modules_with(None)
114}
115
116#[cfg(feature = "net")]
119fn remote_session_module_hash(entries: &[(String, Vec<String>)]) -> String {
120 oxdock_net_plugin::module_hash(entries)
121}
122
123fn cli_host_modules_with(
130 #[cfg(feature = "net")] registry: Option<&Arc<EndpointRegistry>>,
131 #[cfg(not(feature = "net"))] registry: Option<&Arc<()>>,
132) -> Vec<HostModule<DefaultProcessManager>> {
133 #[cfg(any(feature = "net", feature = "markdown"))]
134 let mut modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
135 #[cfg(not(any(feature = "net", feature = "markdown")))]
136 let modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
137 #[cfg(feature = "net")]
138 {
139 let net_module = match registry {
140 Some(registry) => oxdock_net_plugin::module_with_endpoints(Arc::clone(registry)),
141 None => oxdock_net_plugin::module(),
142 };
143 modules.push(net_module);
144 #[cfg(feature = "ssh")]
145 {
146 let ssh_module = match registry {
147 Some(registry) => oxdock_ssh_plugin::module_with_endpoints(Arc::clone(registry)),
148 None => oxdock_ssh_plugin::module(),
149 };
150 modules.push(ssh_module);
151 }
152 }
153 #[cfg(feature = "markdown")]
154 modules.push(oxdock_markdown_plugin::module());
155 let _ = registry;
156 modules
157}
158
159fn cli_host_types() -> Vec<&'static TypeDescriptor> {
161 #[cfg(feature = "net")]
162 let net: &[&'static TypeDescriptor] = &[oxdock_net_plugin::NetListenerTag::descriptor()];
163 #[cfg(not(feature = "net"))]
164 let net: &[&'static TypeDescriptor] = &[];
165 #[cfg(feature = "ssh")]
166 let ssh: &[&'static TypeDescriptor] = &[
167 oxdock_ssh_plugin::SshServerTag::descriptor(),
168 oxdock_ssh_plugin::SshSessionTag::descriptor(),
169 ];
170 #[cfg(not(feature = "ssh"))]
171 let ssh: &[&'static TypeDescriptor] = &[];
172 net.iter().chain(ssh.iter()).copied().collect()
173}
174
175fn parse_cli_script(script: &str) -> Result<Vec<Step>> {
179 parse_script_with_modules(script, cli_module_table())
180}
181
182fn cli_module_table() -> oxdock_parser::ModuleTable {
185 let modules = cli_host_modules();
186 if modules.is_empty() {
187 return oxdock_core::std_module_table();
188 }
189 let mut engine = Engine::new();
190 for module in modules {
191 engine.register_module(module);
192 }
193 engine.module_table()
194}
195
196fn entry_file_of(script: &ScriptSource) -> Option<GuardedPath> {
199 match script {
200 ScriptSource::Path(path) => Some(path.clone()),
201 ScriptSource::Stdin => None,
202 }
203}
204
205fn print_dry_run(
211 steps: &[Step],
212 script: &ScriptSource,
213 workspace_root: &GuardedPath,
214) -> Result<()> {
215 let table = cli_module_table();
216 let entry_file = entry_file_of(script);
217 {
221 let resolver = PathResolver::new_lazy(workspace_root.clone())?;
222 let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
223 oxdock_core::validate_steps_with_fs_modules_and_entry(
224 fs,
225 steps,
226 cli_host_modules_with(None),
227 cli_host_types(),
228 entry_file.clone(),
229 )?;
230 }
231 let (label, base) = match script {
232 ScriptSource::Path(path) => (
233 path.display(),
234 path.parent().unwrap_or_else(|| workspace_root.clone()),
235 ),
236 ScriptSource::Stdin => ("<stdin>".to_string(), workspace_root.clone()),
237 };
238 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
239 let listing = dry_run_closure(steps, &label, &base, &resolver, &table)?;
240 for item in listing {
241 println!("{}:{} {}", item.file, item.step.line, item.step.kind);
242 }
243 Ok(())
244}
245
246pub fn run() -> Result<()> {
247 init_temp_gc();
248 let workspace_root = discover_workspace_root().context("guard workspace root")?;
249
250 let mut args = std::env::args().skip(1);
251 let opts = match Options::parse(&mut args, &workspace_root) {
255 Ok(opts) => opts,
256 Err(err) if err.to_string() == version() => {
257 println!("{err}");
258 return Ok(());
259 }
260 Err(err) if err.to_string() == usage() => {
261 print!("{err}");
262 return Ok(());
263 }
264 Err(err) => return Err(err),
265 };
266 #[cfg(feature = "net")]
269 if opts.remote_serve {
270 if opts.shell || !opts.remotes.is_empty() || !matches!(opts.script, ScriptSource::Stdin) {
271 bail!("--remote-serve runs alone (no --script, --shell, or --remote)");
272 }
273 return serve::serve();
274 }
275 #[cfg(not(feature = "net"))]
276 if opts.remote_serve {
277 bail!("--remote-serve requires the `net` feature (rebuild with --features net)");
278 }
279 if opts.mcp {
282 #[cfg(feature = "mcp")]
283 {
284 if opts.shell || opts.remote_serve || !opts.remotes.is_empty() {
285 bail!("--mcp runs alone (no --shell, --remote-serve, or --remote)");
286 }
287 if !opts.endpoints.listens.is_empty() || !opts.endpoints.publishes.is_empty() {
288 bail!("--mcp runs alone (no --listen/-p)");
289 }
290 if opts.dry_run {
291 bail!("--mcp runs alone (no --dry-run)");
292 }
293 return mcp::serve_mcp(opts, workspace_root);
294 }
295 #[cfg(not(feature = "mcp"))]
296 {
297 bail!("--mcp requires the `mcp` feature (rebuild with --features mcp)");
298 }
299 }
300 execute(opts, workspace_root)
301}
302
303pub fn process_exit_code(err: &anyhow::Error) -> i32 {
307 exit_code_of(err)
308 .map(|code| code.clamp(0, 255) as i32)
309 .unwrap_or(1)
310}
311
312#[derive(Debug, Clone)]
313pub enum ScriptSource {
314 Path(GuardedPath),
315 Stdin,
316}
317
318fn reject_url_script(text: &str) -> Result<()> {
322 if text.contains("://") {
323 bail!("not a local path: {text:?} (pass a workspace path or `-` for stdin)");
324 }
325 Ok(())
326}
327
328#[derive(Debug, Clone)]
329pub struct Options {
330 pub script: ScriptSource,
331 pub shell: bool,
332 pub dry_run: bool,
335 pub endpoints: EndpointFlags,
336 pub remote_serve: bool,
337 pub mcp: bool,
340 pub remotes: Vec<(String, String)>,
343}
344
345impl Options {
346 pub fn parse(
347 args: &mut impl Iterator<Item = String>,
348 workspace_root: &GuardedPath,
349 ) -> Result<Self> {
350 use lexopt::Arg::{Long, Short, Value};
351
352 let mut script: Option<ScriptSource> = None;
353 let mut shell = false;
354 let mut dry_run = false;
355 let mut endpoints = EndpointFlags::default();
356 let mut remote_serve = false;
357 let mut mcp = false;
358 #[cfg_attr(not(feature = "net"), allow(unused_mut))]
360 let mut remotes: Vec<(String, String)> = Vec::new();
361 let mut set_script = |source: ScriptSource, origin: &str| -> Result<()> {
362 if script.is_some() {
363 bail!("script given multiple times ({origin})");
364 }
365 script = Some(source);
366 Ok(())
367 };
368 let mut parser = lexopt::Parser::from_args(args.by_ref());
373 while let Some(arg) = parser.next()? {
374 match arg {
375 Long("script") => {
376 let path = value_string(
377 parser
378 .value()
379 .map_err(|_| anyhow::anyhow!("--script requires a path"))?,
380 )?;
381 if path.is_empty() {
382 bail!("--script requires a path");
383 }
384 if path == "-" {
385 set_script(ScriptSource::Stdin, "--script -")?;
386 } else {
387 reject_url_script(&path)?;
388 set_script(
389 ScriptSource::Path(
390 workspace_root
391 .join_script(&path)
392 .with_context(|| format!("guard script path {path}"))?,
393 ),
394 "--script",
395 )?;
396 }
397 }
398 Long("shell") => {
399 shell = true;
400 }
401 Long("dry-run") => {
402 dry_run = true;
403 }
404 Long("listen") => {
405 let raw = value_string(
406 parser
407 .value()
408 .map_err(|_| anyhow::anyhow!("--listen requires an address"))?,
409 )?;
410 #[cfg(not(feature = "net"))]
411 {
412 let _ = endpoints::parse_listen_arg(&raw);
416 bail!(
417 "--listen/-p require the `net` feature (rebuild with --features net)"
418 );
419 }
420 #[cfg(feature = "net")]
421 endpoints.listens.push(endpoints::parse_listen_arg(&raw)?);
422 }
423 Short('p') => {
424 let raw = value_string(
425 parser
426 .value()
427 .map_err(|_| anyhow::anyhow!("-p requires outer:inner"))?,
428 )?;
429 #[cfg(not(feature = "net"))]
430 {
431 let _ = endpoints::parse_publish_arg(&raw);
435 bail!(
436 "--listen/-p require the `net` feature (rebuild with --features net)"
437 );
438 }
439 #[cfg(feature = "net")]
440 endpoints
441 .publishes
442 .push(endpoints::parse_publish_arg(&raw)?);
443 }
444 Long("offline") => {
445 endpoints.offline = true;
446 }
447 Long("remote-serve") => {
448 remote_serve = true;
449 }
450 Long("mcp") => {
451 mcp = true;
452 }
453 Long("remote") => {
454 let raw = value_string(parser.value().map_err(|_| {
455 anyhow::anyhow!("--remote requires <target>=\"<command>\"")
456 })?)?;
457 #[cfg(not(feature = "net"))]
458 {
459 let _ = oxdock_net_plugin_stub_parse_remote(&raw);
462 bail!("--remote requires the `net` feature (rebuild with --features net)");
463 }
464 #[cfg(feature = "net")]
465 remotes.push(oxdock_net_plugin::parse_remote_arg(&raw)?);
466 }
467 Long("help") | Short('h') => {
468 bail!("{}", usage());
469 }
470 Long("version") | Short('V') => {
471 bail!("{}", version());
472 }
473 Value(value) => {
474 let text = value_string(value)?;
475 if text.is_empty() {
476 continue;
477 }
478 if text == "-" {
479 set_script(ScriptSource::Stdin, "positional `-`")?;
480 } else {
481 reject_url_script(&text)?;
482 set_script(
483 ScriptSource::Path(
484 workspace_root
485 .join_script(&text)
486 .with_context(|| format!("guard script path {text}"))?,
487 ),
488 "positional argument",
489 )?;
490 }
491 }
492 Long(other) => bail!("unexpected flag: --{other}"),
493 Short(other) => bail!("unexpected flag: -{other}"),
494 }
495 }
496
497 let script = script.unwrap_or(ScriptSource::Stdin);
498
499 Ok(Self {
500 script,
501 shell,
502 dry_run,
503 endpoints,
504 remote_serve,
505 mcp,
506 remotes,
507 })
508 }
509}
510
511fn value_string(value: std::ffi::OsString) -> Result<String> {
514 value
515 .into_string()
516 .map_err(|_| anyhow::anyhow!("argument must be UTF-8"))
517}
518
519pub fn version() -> String {
521 format!("oxdock {}", env!("CARGO_PKG_VERSION"))
522}
523
524pub fn usage() -> String {
530 #[cfg(feature = "net")]
531 let asset = "dist/usage-net.txt";
532 #[cfg(not(feature = "net"))]
533 let asset = "dist/usage-lean.txt";
534 let file = UsageAssets::get(asset).expect("usage must be embedded");
535 str::from_utf8(file.data.as_ref())
536 .expect("usage is UTF-8")
537 .to_string()
538}
539
540pub fn execute(opts: Options, workspace_root: GuardedPath) -> Result<()> {
541 init_temp_gc();
542 execute_with_shell_runner(opts, workspace_root, run_shell, true)
543}
544
545pub struct ExecutionResult {
553 pub snapshot: Arc<LazyGuardedTempDir>,
557 pub final_cwd: GuardedPath,
560 pub bindings: BTreeMap<String, Value>,
564}
565
566impl ExecutionResult {
567 pub fn has_snapshot(&self) -> bool {
569 self.snapshot.is_materialized()
570 }
571
572 pub fn snapshot_path(&self) -> Option<&GuardedPath> {
574 self.snapshot.get()
575 }
576}
577
578pub fn execute_with_result(opts: Options, workspace_root: GuardedPath) -> Result<ExecutionResult> {
579 if opts.shell {
580 bail!("execute_with_result does not support --shell");
581 }
582
583 let script = read_script(&opts.script)?;
586
587 let mut final_cwd = workspace_root.clone();
588 let snapshot = Arc::new(LazyGuardedTempDir::new());
589 if !script.trim().is_empty() {
590 let steps = parse_cli_script(&script)?;
591 if opts.dry_run {
594 print_dry_run(&steps, &opts.script, &workspace_root)?;
595 return Ok(ExecutionResult {
596 snapshot,
597 final_cwd,
598 bindings: BTreeMap::new(),
599 });
600 }
601 #[cfg(feature = "net")]
604 let registry = build_registry(&opts.endpoints)?;
605 #[cfg(not(feature = "net"))]
606 check_no_net_endpoints(&opts.endpoints)?;
607 #[cfg(not(feature = "net"))]
608 check_no_net_remotes(&opts.remotes)?;
609 #[cfg(feature = "net")]
613 let inventory = {
614 let pairs = opts.remotes.clone();
615 let inventory = oxdock_net_plugin::RemoteInventory::build(pairs)?;
616 inventory.log_resolutions();
617 inventory.validate_script(&steps)?;
618 inventory
619 };
620 let entry_file = entry_file_of(&opts.script);
621 #[cfg(feature = "net")]
622 let output = {
623 let mut io_cfg = ExecIo::new();
624 register_remote_runners(&mut io_cfg, &inventory);
625 run_steps_with_lazy_snapshot_and_modules_and_entry(
626 &workspace_root,
627 &steps,
628 io_cfg,
629 cli_host_modules_with(Some(®istry)),
630 cli_host_types(),
631 entry_file,
632 )?
633 };
634 #[cfg(not(feature = "net"))]
635 let output = run_steps_with_lazy_snapshot_and_modules_and_entry(
636 &workspace_root,
637 &steps,
638 ExecIo::new(),
639 cli_host_modules_with(None),
640 cli_host_types(),
641 entry_file,
642 )?;
643 final_cwd = output.final_cwd;
644 return Ok(ExecutionResult {
645 snapshot: output.snapshot,
646 final_cwd,
647 bindings: output.bindings,
648 });
649 }
650
651 Ok(ExecutionResult {
652 snapshot,
653 final_cwd,
654 bindings: BTreeMap::new(),
655 })
656}
657
658#[cfg(feature = "net")]
663fn register_remote_runners(io: &mut ExecIo, inventory: &oxdock_net_plugin::RemoteInventory) {
664 use std::sync::Arc;
665 let entries = surface_entries();
666 let module_hash = oxdock_net_plugin::module_hash(&entries);
667 let modules: Vec<String> = entries.iter().map(|(name, _)| name.clone()).collect();
668 for target in inventory.targets() {
669 let Some(argv) = inventory.argv(&target) else {
670 continue;
671 };
672 let config = oxdock_net_plugin::SessionConfig {
673 argv: argv.to_vec(),
674 oxdock_version: env!("CARGO_PKG_VERSION").to_string(),
675 modules: modules.clone(),
676 module_hash: module_hash.clone(),
677 };
678 io.set_remote_runner_for_target(
679 target,
680 Arc::new(oxdock_net_plugin::StdioSession::new(config)),
681 );
682 }
683}
684
685#[cfg(feature = "net")]
688fn surface_entries() -> Vec<(String, Vec<String>)> {
689 let mut engine = Engine::new();
690 for module in cli_host_modules() {
691 engine.register_module(module);
692 }
693 let table = engine.module_table();
694 let mut entries: Vec<(String, Vec<String>)> = table
695 .modules
696 .into_iter()
697 .map(|(name, module_funcs)| {
698 let mut func_names: Vec<String> = module_funcs
699 .map(|surface| surface.func_names.into_iter().collect())
700 .unwrap_or_default();
701 func_names.sort();
702 (name, func_names)
703 })
704 .collect();
705 entries.sort();
706 entries
707}
708#[cfg(feature = "net")]
709fn report_ephemeral_publishes(flags: &EndpointFlags, registry: &Arc<EndpointRegistry>) {
710 use oxdock_net_plugin::{EndpointKey, Protocol, parse_endpoint_ref};
711 for (outer, inner) in &flags.publishes {
712 if outer.port() != 0 {
713 continue;
714 }
715 let Ok((protocol, endpoint)) = parse_endpoint_ref(inner, "-p") else {
716 continue;
717 };
718 let key = EndpointKey {
719 protocol: protocol.unwrap_or(Protocol::Tcp),
720 endpoint,
721 };
722 match registry.resolve_endpoint(&key) {
723 Ok(addr) => eprintln!("oxdock: published {addr} -> {inner}"),
724 Err(_) => eprintln!("oxdock: published <unbound> -> {inner}"),
725 }
726 }
727}
728
729#[cfg(not(feature = "net"))]
732fn oxdock_net_plugin_stub_parse_remote(raw: &str) -> Result<(String, String)> {
733 match raw.split_once('=') {
736 Some((target, command)) if !target.trim().is_empty() && !command.trim().is_empty() => {
737 Ok((target.trim().to_string(), command.to_string()))
738 }
739 _ => bail!("invalid --remote {raw:?}: expected <target>=\"<command>\""),
740 }
741}
742
743#[cfg(not(feature = "net"))]
745fn check_no_net_remotes(remotes: &[(String, String)]) -> Result<()> {
746 if !remotes.is_empty() {
747 bail!("--remote requires the `net` feature (rebuild with --features net)");
748 }
749 Ok(())
750}
751
752#[cfg(not(feature = "net"))]
756fn check_no_net_endpoints(flags: &EndpointFlags) -> Result<()> {
757 if !flags.listens.is_empty() || !flags.publishes.is_empty() {
758 bail!("--listen/-p require the `net` feature (rebuild with --features net)");
759 }
760 Ok(())
761}
762
763fn read_script(source: &ScriptSource) -> Result<String> {
767 match source {
768 ScriptSource::Path(path) => {
769 let resolver = PathResolver::new(path.root(), path.root())?;
770 resolver
771 .read_to_string(path)
772 .with_context(|| format!("failed to read script at {}", path.display()))
773 }
774 ScriptSource::Stdin => {
775 let mut buf = String::new();
776 io::stdin()
777 .lock()
778 .read_to_string(&mut buf)
779 .context("failed to read script from stdin")?;
780 Ok(buf)
781 }
782 }
783}
784
785fn execute_with_shell_runner<F>(
786 opts: Options,
787 workspace_root: GuardedPath,
788 shell_runner: F,
789 require_tty: bool,
790) -> Result<()>
791where
792 F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
793{
794 #[cfg(windows)]
795 maybe_reexec_shell_to_temp(&opts)?;
796
797 let script = match &opts.script {
801 ScriptSource::Path(_) => read_script(&opts.script)?,
802 ScriptSource::Stdin => {
803 let stdin = io::stdin();
804 if stdin.is_terminal() {
805 if opts.shell {
810 String::new()
811 } else {
812 bail!(
813 "no stdin detected; pass --script <file> or pipe a script into stdin (use --script - if explicit)"
814 );
815 }
816 } else {
817 let mut buf = String::new();
818 stdin
819 .lock()
820 .read_to_string(&mut buf)
821 .context("failed to read script from stdin")?;
822 buf
823 }
824 }
825 };
826
827 let mut final_cwd = workspace_root.clone();
834 let mut snapshot = Arc::new(LazyGuardedTempDir::new());
835 let mut fs: Option<Box<dyn WorkspaceFs>> = None;
836 if !script.trim().is_empty() {
837 let steps = parse_cli_script(&script)?;
838 if opts.dry_run {
841 print_dry_run(&steps, &opts.script, &workspace_root)?;
842 return Ok(());
843 }
844 #[cfg(feature = "net")]
847 let registry = build_registry(&opts.endpoints)?;
848 #[cfg(not(feature = "net"))]
849 check_no_net_endpoints(&opts.endpoints)?;
850 #[cfg(not(feature = "net"))]
851 check_no_net_remotes(&opts.remotes)?;
852 #[cfg(feature = "net")]
853 report_ephemeral_publishes(&opts.endpoints, ®istry);
854 #[cfg(feature = "net")]
858 let inventory = {
859 let inventory = oxdock_net_plugin::RemoteInventory::build(opts.remotes.clone())?;
860 inventory.log_resolutions();
861 inventory.validate_script(&steps)?;
862 inventory
863 };
864 let mut stdin_handle: Option<SharedInput> = None;
869 if let ScriptSource::Path(_) = opts.script {
870 let stdin = io::stdin();
871 if !stdin.is_terminal() {
872 stdin_handle = Some(Arc::new(Mutex::new(stdin)));
878 }
879 }
880
881 let mut io_cfg = ExecIo::new();
882 io_cfg.set_stdin(stdin_handle);
883 #[cfg(feature = "net")]
884 register_remote_runners(&mut io_cfg, &inventory);
885 let entry_file = entry_file_of(&opts.script);
886 #[cfg(feature = "net")]
887 let output = run_steps_with_lazy_snapshot_and_modules_and_entry(
888 &workspace_root,
889 &steps,
890 io_cfg,
891 cli_host_modules_with(Some(®istry)),
892 cli_host_types(),
893 entry_file,
894 )?;
895 #[cfg(not(feature = "net"))]
896 let output = run_steps_with_lazy_snapshot_and_modules_and_entry(
897 &workspace_root,
898 &steps,
899 io_cfg,
900 cli_host_modules_with(None),
901 cli_host_types(),
902 entry_file,
903 )?;
904 final_cwd = output.final_cwd;
905 snapshot = output.snapshot;
906 fs = Some(output.fs);
907 }
908
909 if opts.shell {
911 if require_tty && !has_controlling_tty() {
912 bail!("--shell requires a tty (no controlling tty available)");
913 }
914 match fs.as_ref() {
919 Some(fs) => {
920 if fs.is_snapshot_pending() {
921 snapshot
922 .materialize()
923 .context("failed to create shell temp dir")?;
924 }
925 final_cwd = fs.concretize_cwd(&final_cwd);
926 }
927 None => {
928 snapshot
929 .materialize()
930 .context("failed to create shell temp dir")?;
931 final_cwd = snapshot
932 .get()
933 .cloned()
934 .expect("shell snapshot materialized above");
935 }
936 }
937 return shell_runner(&final_cwd, &workspace_root);
938 }
939
940 Ok(())
941}
942
943#[cfg(test)]
944fn execute_for_test<F>(opts: Options, workspace_root: GuardedPath, shell_runner: F) -> Result<()>
945where
946 F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
947{
948 execute_with_shell_runner(opts, workspace_root, shell_runner, false)
949}
950
951fn has_controlling_tty() -> bool {
952 #[cfg(unix)]
956 {
957 io::stdin().is_terminal() || io::stderr().is_terminal()
958 }
959
960 #[cfg(windows)]
961 {
962 io::stdin().is_terminal() || io::stderr().is_terminal()
963 }
964
965 #[cfg(not(any(unix, windows)))]
966 {
967 false
968 }
969}
970
971#[cfg(windows)]
972fn maybe_reexec_shell_to_temp(opts: &Options) -> Result<()> {
973 if !opts.shell {
976 return Ok(());
977 }
978 if std::env::var(oxdock_env::oxdock::SHELL_REEXEC)
979 .ok()
980 .as_deref()
981 == Some("1")
982 {
983 return Ok(());
984 }
985
986 let self_path = std::env::current_exe().context("determine current executable")?;
987 let base_temp =
988 GuardedPath::new_root(std::env::temp_dir().as_path()).context("guard system temp dir")?;
989 let ts = std::time::SystemTime::now()
990 .duration_since(std::time::UNIX_EPOCH)
991 .unwrap_or_default()
992 .as_millis();
993 let temp_file = base_temp
994 .join(&format!("oxdock-shell-{ts}-{}.exe", std::process::id()))
995 .context("construct temp shell path")?;
996
997 let temp_root_guard = temp_file
1001 .parent()
1002 .ok_or_else(|| anyhow::anyhow!("temp path unexpectedly missing parent"))?;
1003 let resolver_temp = PathResolver::new(temp_root_guard.as_path(), temp_root_guard.as_path())?;
1004 let dest = temp_file;
1005 #[allow(clippy::disallowed_types)]
1006 let source = oxdock_fs::UnguardedPath::external(self_path);
1007 resolver_temp
1008 .copy_file_from_unguarded(&source, &dest)
1009 .with_context(|| format!("failed to copy shell runner to {}", dest.display()))?;
1010
1011 let mut cmd = CommandBuilder::new(dest.as_path());
1012 cmd.args(std::env::args_os().skip(1));
1013 cmd.env(oxdock_env::oxdock::SHELL_REEXEC, "1");
1014 cmd.spawn()
1015 .with_context(|| format!("failed to spawn shell from {}", dest.display()))?;
1016
1017 std::process::exit(0);
1019}
1020
1021pub fn run_script(workspace_root: &GuardedPath, steps: &[Step]) -> Result<()> {
1022 run_steps_with_context(workspace_root, workspace_root, steps)
1023}
1024
1025fn shell_banner(cwd: &GuardedPath, workspace_root: &GuardedPath) -> String {
1026 #[cfg(windows)]
1027 let cwd_disp = oxdock_fs::command_path(cwd).as_ref().display().to_string();
1028 #[cfg(windows)]
1029 let workspace_disp = oxdock_fs::command_path(workspace_root)
1030 .as_ref()
1031 .display()
1032 .to_string();
1033
1034 #[cfg(not(windows))]
1035 let cwd_disp = cwd.display().to_string();
1036 #[cfg(not(windows))]
1037 let workspace_disp = workspace_root.display().to_string();
1038
1039 let pkg = env::var(oxdock_env::cargo::PKG_NAME)
1040 .unwrap_or_else(|_| oxdock_env::oxdock::FALLBACK_APP_NAME.to_string());
1041 indoc::formatdoc! {"
1042 {pkg} shell workspace
1043 cwd: {cwd_disp}
1044 source: workspace root at {workspace_disp}
1045 lifetime: temporary directory created for this shell session; it disappears when you exit
1046 creation: temp workspace starts empty unless your script copies files into it
1047
1048 WARNING: This shell still runs on your host filesystem and is **not** isolated!
1049 "}
1050}
1051
1052fn run_shell(cwd: &GuardedPath, workspace_root: &GuardedPath) -> Result<()> {
1053 oxdock_process::spawn_interactive_shell(cwd, workspace_root, &shell_banner(cwd, workspace_root))
1054}
1055
1056#[cfg(test)]
1059mod tests {
1060 use super::*;
1061 use indoc::indoc;
1062 use oxdock_fs::PathResolver;
1063 use std::cell::{Cell, RefCell};
1064
1065 #[cfg_attr(
1066 miri,
1067 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1068 )]
1069 #[test]
1070 fn shell_runner_receives_final_workdir() -> Result<()> {
1071 let workspace = GuardedPath::tempdir()?;
1072 let workspace_root = workspace.as_guarded_path().clone();
1073 let script_path = workspace_root.join("script.ox")?;
1074 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1075 let script = indoc! {"
1076 WRITE temp.txt 123
1077 WORKDIR sub
1078 "};
1079 resolver.write_file(&script_path, script.as_bytes())?;
1080
1081 let opts = Options {
1082 script: ScriptSource::Path(script_path),
1083 shell: true,
1084 dry_run: false,
1085 endpoints: EndpointFlags::default(),
1086 remote_serve: false,
1087 mcp: false,
1088 remotes: Vec::new(),
1089 };
1090
1091 let observed = Cell::new(false);
1092 execute_for_test(opts, workspace_root.clone(), |cwd, _| {
1093 assert!(
1094 cwd.as_path().ends_with("sub"),
1095 "final cwd should end in WORKDIR target, got {}",
1096 cwd.display()
1097 );
1098
1099 let temp_root = GuardedPath::new_root(cwd.root())
1100 .context("construct guard for temp workspace root")?;
1101 let sub_dir = temp_root.join("sub")?;
1102 assert_eq!(
1103 cwd.as_path(),
1104 sub_dir.as_path(),
1105 "shell runner cwd should match guarded sub dir"
1106 );
1107 let temp_file = temp_root.join("temp.txt")?;
1108 let temp_resolver = PathResolver::new(temp_root.as_path(), temp_root.as_path())?;
1109 let contents = temp_resolver.read_to_string(&temp_file)?;
1110 assert!(
1111 contents.contains("123"),
1112 "expected WRITE command to materialize temp file"
1113 );
1114 observed.set(true);
1115 Ok(())
1116 })?;
1117
1118 assert!(
1119 observed.into_inner(),
1120 "shell runner closure should have been invoked"
1121 );
1122 Ok(())
1123 }
1124
1125 #[cfg_attr(
1126 miri,
1127 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1128 )]
1129 #[test]
1130 fn options_parse_requires_script_path_value() {
1131 let workspace = GuardedPath::tempdir().expect("tempdir");
1132 let mut args = vec!["--script".to_string()].into_iter();
1133 let err = Options::parse(&mut args, workspace.as_guarded_path())
1134 .expect_err("expected missing path error");
1135 assert!(err.to_string().contains("--script requires a path"));
1136 }
1137
1138 #[cfg_attr(
1139 miri,
1140 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1141 )]
1142 #[test]
1143 fn options_parse_script_path_and_shell() {
1144 let workspace = GuardedPath::tempdir().expect("tempdir");
1145 let workspace_root = workspace.as_guarded_path().clone();
1146 let script_path = workspace_root.join("script.txt").expect("script path");
1147 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1148 .expect("resolver");
1149 resolver
1150 .write_file(&script_path, b"WRITE out.txt hi")
1151 .expect("write script");
1152 let mut args = vec![
1153 "--script".to_string(),
1154 "script.txt".to_string(),
1155 "--shell".to_string(),
1156 ]
1157 .into_iter();
1158 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1159 assert!(opts.shell);
1160 match opts.script {
1161 ScriptSource::Path(path) => assert_eq!(path, script_path),
1162 ScriptSource::Stdin => panic!("expected path script"),
1163 }
1164 }
1165
1166 #[cfg_attr(
1167 miri,
1168 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1169 )]
1170 #[test]
1171 fn options_parse_mcp_flag() {
1172 let workspace = GuardedPath::tempdir().expect("tempdir");
1173 let workspace_root = workspace.as_guarded_path().clone();
1174 let mut args = vec!["--mcp".to_string(), "tools.oxdock".to_string()].into_iter();
1175 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1176 assert!(opts.mcp);
1177 match opts.script {
1178 ScriptSource::Path(path) => assert_eq!(
1179 path,
1180 workspace_root.join("tools.oxdock").expect("script path")
1181 ),
1182 ScriptSource::Stdin => panic!("expected path script"),
1183 }
1184 }
1185
1186 #[cfg_attr(
1187 miri,
1188 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1189 )]
1190 #[test]
1191 fn options_parse_mcp_defaults_off() {
1192 let workspace = GuardedPath::tempdir().expect("tempdir");
1193 let workspace_root = workspace.as_guarded_path().clone();
1194 let mut args = vec!["script.txt".to_string()].into_iter();
1195 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1196 assert!(!opts.mcp);
1197 }
1198
1199 #[cfg_attr(
1200 miri,
1201 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1202 )]
1203 #[test]
1204 fn options_parse_positional_script_path() {
1205 let workspace = GuardedPath::tempdir().expect("tempdir");
1206 let workspace_root = workspace.as_guarded_path().clone();
1207 let mut args = vec!["script.txt".to_string()].into_iter();
1208 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1209 assert!(!opts.shell);
1210 match opts.script {
1211 ScriptSource::Path(path) => assert_eq!(
1212 path,
1213 workspace_root.join("script.txt").expect("script path")
1214 ),
1215 ScriptSource::Stdin => panic!("expected path script"),
1216 }
1217 }
1218
1219 #[cfg_attr(
1220 miri,
1221 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1222 )]
1223 #[test]
1224 fn options_parse_positional_dash_reads_stdin() {
1225 let workspace = GuardedPath::tempdir().expect("tempdir");
1226 let mut args = vec!["-".to_string()].into_iter();
1227 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1228 assert!(matches!(opts.script, ScriptSource::Stdin));
1229 }
1230
1231 #[cfg_attr(
1232 miri,
1233 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1234 )]
1235 #[test]
1236 fn options_parse_rejects_duplicate_script_sources() {
1237 let workspace = GuardedPath::tempdir().expect("tempdir");
1238 let workspace_root = workspace.as_guarded_path().clone();
1239 let mut args = vec![
1240 "a.ox".to_string(),
1241 "--script".to_string(),
1242 "b.ox".to_string(),
1243 ]
1244 .into_iter();
1245 let err = Options::parse(&mut args, &workspace_root)
1246 .expect_err("expected duplicate script error");
1247 assert!(err.to_string().contains("multiple times"), "{err:?}");
1248
1249 let mut args = vec!["a.ox".to_string(), "b.ox".to_string()].into_iter();
1250 let err = Options::parse(&mut args, &workspace_root)
1251 .expect_err("expected duplicate script error");
1252 assert!(err.to_string().contains("multiple times"), "{err:?}");
1253 }
1254
1255 #[cfg_attr(
1256 miri,
1257 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1258 )]
1259 #[test]
1260 fn options_parse_absolute_script_outside_execution_workspace_loads() {
1261 let workspace = GuardedPath::tempdir().expect("tempdir");
1264 let outside = GuardedPath::tempdir().expect("outside");
1265 let target = outside
1266 .as_guarded_path()
1267 .as_path()
1268 .join("step.ox")
1269 .to_string_lossy()
1270 .into_owned();
1271 let mut args = vec!["--script".to_string(), target.clone()].into_iter();
1272 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1273 match opts.script {
1274 ScriptSource::Path(path) => {
1275 assert_eq!(path.as_path().to_string_lossy(), target);
1276 assert_eq!(path.root(), outside.as_guarded_path().as_path());
1277 }
1278 ScriptSource::Stdin => panic!("absolute script must not parse as stdin"),
1279 }
1280 }
1281
1282 #[cfg_attr(
1283 miri,
1284 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1285 )]
1286 #[test]
1287 fn options_parse_relative_escape_stays_rejected() {
1288 let workspace = GuardedPath::tempdir().expect("tempdir");
1289 let mut args = vec!["--script".to_string(), "../escape.ox".to_string()].into_iter();
1290 let err =
1291 Options::parse(&mut args, workspace.as_guarded_path()).expect_err("escape must fail");
1292 assert!(err.to_string().contains("guard script path"), "{err:?}");
1293 }
1294
1295 #[cfg_attr(
1296 miri,
1297 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1298 )]
1299 #[test]
1300 fn options_parse_rejects_unknown_flags() {
1301 let workspace = GuardedPath::tempdir().expect("tempdir");
1302 let mut args = vec!["--frobnicate".to_string()].into_iter();
1303 let err = Options::parse(&mut args, workspace.as_guarded_path())
1304 .expect_err("expected unknown flag error");
1305 assert!(err.to_string().contains("unexpected flag"), "{err:?}");
1306 }
1307
1308 #[test]
1309 fn usage_describes_positional_script_and_help() {
1310 let text = usage();
1311 assert!(text.contains("Usage: oxdock"), "{text}");
1312 assert!(text.contains("SCRIPT"), "{text}");
1313 assert!(text.contains("--script"), "{text}");
1314 assert!(text.contains("--help"), "{text}");
1315 assert!(text.contains("--offline"), "{text}");
1316 #[cfg(feature = "net")]
1317 {
1318 assert!(text.contains("--listen"), "{text}");
1319 assert!(text.contains("-p <[host:]outer:inner>"), "{text}");
1320 }
1321 #[cfg(not(feature = "net"))]
1322 {
1323 assert!(!text.contains("--listen <addr>"), "{text}");
1324 assert!(!text.contains("-p <[host:]outer:inner>"), "{text}");
1325 assert!(text.contains("require the `net` feature"), "{text}");
1326 }
1327 assert!(text.contains(env!("CARGO_PKG_DESCRIPTION")), "{text}");
1329 }
1330
1331 #[cfg(feature = "net")]
1332 #[cfg_attr(
1333 miri,
1334 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1335 )]
1336 #[test]
1337 fn options_parse_endpoint_flags() {
1338 let workspace = GuardedPath::tempdir().expect("tempdir");
1341 let mut args = vec![
1342 "--listen".to_string(),
1343 "0.0.0.0:2251".to_string(),
1344 "-p".to_string(),
1345 "2222:demo-proxy".to_string(),
1346 "-p".to_string(),
1347 "0:2252".to_string(),
1348 "-".to_string(),
1349 ]
1350 .into_iter();
1351 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1352 assert_eq!(opts.endpoints.listens.len(), 1);
1353 assert_eq!(opts.endpoints.publishes.len(), 2);
1354 assert!(!opts.endpoints.offline);
1355 assert!(matches!(opts.script, ScriptSource::Stdin));
1356 }
1357
1358 #[cfg_attr(
1359 miri,
1360 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1361 )]
1362 #[test]
1363 fn options_parse_offline_flag() {
1364 let workspace = GuardedPath::tempdir().expect("tempdir");
1365 let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
1366 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1367 assert!(opts.endpoints.offline);
1368 }
1369
1370 #[cfg(feature = "net")]
1371 #[cfg_attr(
1372 miri,
1373 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1374 )]
1375 #[test]
1376 fn options_parse_rejects_bad_endpoint_flags() {
1377 let workspace = GuardedPath::tempdir().expect("tempdir");
1378 for args in [
1379 vec!["--listen"],
1380 vec!["--listen", "0.0.0.0:0"],
1381 vec!["-p"],
1382 vec!["-p", "2222"],
1383 vec!["-p", "2222:0"],
1384 ] {
1385 let mut args = args.into_iter().map(str::to_string);
1386 Options::parse(&mut args, workspace.as_guarded_path())
1387 .expect_err("bad endpoint flag must fail");
1388 }
1389 }
1390
1391 #[cfg_attr(
1392 miri,
1393 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1394 )]
1395 #[test]
1396 fn options_parse_empty_values_hold_token_boundaries() {
1397 let workspace = GuardedPath::tempdir().expect("tempdir");
1401 let mut args = vec![
1402 "--script".to_string(),
1403 "".to_string(),
1404 "--shell".to_string(),
1405 ]
1406 .into_iter();
1407 let err = Options::parse(&mut args, workspace.as_guarded_path())
1408 .expect_err("empty script path must fail");
1409 assert!(
1410 err.to_string().contains("--script requires a path"),
1411 "{err:?}"
1412 );
1413 let mut args = vec!["".to_string(), "-".to_string()].into_iter();
1414 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1415 assert!(matches!(opts.script, ScriptSource::Stdin));
1416 }
1417
1418 #[cfg(feature = "net")]
1419 #[cfg_attr(
1420 miri,
1421 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1422 )]
1423 #[test]
1424 fn options_parse_accepts_equals_and_attached_forms() {
1425 let workspace = GuardedPath::tempdir().expect("tempdir");
1428 let workspace_root = workspace.as_guarded_path().clone();
1429 let mut args = vec![
1430 "--listen=0.0.0.0:2251".to_string(),
1431 "-p2222:demo-proxy".to_string(),
1432 "--".to_string(),
1433 "script.ox".to_string(),
1434 ]
1435 .into_iter();
1436 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1437 assert_eq!(opts.endpoints.listens.len(), 1);
1438 assert_eq!(opts.endpoints.publishes.len(), 1);
1439 match opts.script {
1440 ScriptSource::Path(path) => {
1441 assert_eq!(path, workspace_root.join("script.ox").expect("script path"))
1442 }
1443 ScriptSource::Stdin => panic!("expected path script after --"),
1444 }
1445 }
1446
1447 #[cfg_attr(
1448 miri,
1449 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1450 )]
1451 #[test]
1452 fn options_parse_version_returns_version_without_exiting() {
1453 let workspace = GuardedPath::tempdir().expect("tempdir");
1457 for flag in ["--version", "-V"] {
1458 let mut args = vec![flag.to_string()].into_iter();
1459 let err = Options::parse(&mut args, workspace.as_guarded_path())
1460 .expect_err("version flag must not parse as options");
1461 assert_eq!(err.to_string(), version());
1462 }
1463 }
1464
1465 #[cfg_attr(
1466 miri,
1467 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1468 )]
1469 #[test]
1470 fn options_parse_help_returns_usage_error_without_exiting() {
1471 let workspace = GuardedPath::tempdir().expect("tempdir");
1474 for flag in ["--help", "-h"] {
1475 let mut args = vec![flag.to_string()].into_iter();
1476 let err = Options::parse(&mut args, workspace.as_guarded_path())
1477 .expect_err("help flag must not parse as options");
1478 assert_eq!(err.to_string(), usage());
1479 }
1480 }
1481
1482 #[cfg_attr(
1483 miri,
1484 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1485 )]
1486 #[test]
1487 fn options_parse_rejects_remote_script_with_input_intact() {
1488 let workspace = GuardedPath::tempdir().expect("tempdir");
1489 for args in [
1490 vec!["https://example.com/process.oxfile".to_string()],
1491 vec![
1492 "--script".to_string(),
1493 "https://example.com/process.oxfile".to_string(),
1494 ],
1495 ] {
1496 let err = Options::parse(&mut args.into_iter(), workspace.as_guarded_path())
1497 .expect_err("remote script must not parse as a path");
1498 let rendered = format!("{err:#}");
1499 assert!(
1500 rendered.contains("not a local path")
1501 && rendered.contains("https://example.com/process.oxfile"),
1502 "rejection names the intact input: {rendered}"
1503 );
1504 assert!(
1505 !rendered.contains("https:/example.com"),
1506 "scheme must never come out mangled: {rendered}"
1507 );
1508 }
1509 }
1510
1511 #[test]
1512 fn execute_with_result_runs_script() {
1513 let workspace = GuardedPath::tempdir().expect("tempdir");
1514 let workspace_root = workspace.as_guarded_path().clone();
1515 let script_path = workspace_root.join("script.txt").expect("script path");
1516 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1517 .expect("resolver");
1518 resolver
1519 .write_file(&script_path, b"WRITE out.txt hi")
1520 .expect("write script");
1521 let opts = Options {
1522 script: ScriptSource::Path(script_path),
1523 shell: false,
1524 dry_run: false,
1525 endpoints: EndpointFlags::default(),
1526 remote_serve: false,
1527 mcp: false,
1528 remotes: Vec::new(),
1529 };
1530 let result = execute_with_result(opts, workspace_root).expect("execute");
1531 let snapshot = result
1532 .snapshot_path()
1533 .expect("default WRITE materializes the snapshot");
1534 assert_eq!(snapshot, &result.final_cwd);
1535 let temp_resolver = PathResolver::new(snapshot.root(), snapshot.root()).expect("resolver");
1536 let out = snapshot.join("out.txt").expect("out path");
1537 let contents = temp_resolver.read_to_string(&out).expect("read out");
1538 assert_eq!(contents.trim(), "hi");
1539 }
1540
1541 #[cfg_attr(
1542 miri,
1543 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1544 )]
1545 #[test]
1546 fn execute_with_result_local_only_creates_no_snapshot() {
1547 let workspace = GuardedPath::tempdir().expect("tempdir");
1548 let workspace_root = workspace.as_guarded_path().clone();
1549 let script_path = workspace_root.join("script.txt").expect("script path");
1550 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1551 .expect("resolver");
1552 resolver
1553 .write_file(&script_path, b"WORKSPACE LOCAL\nWRITE out.txt hi")
1554 .expect("write script");
1555 let opts = Options {
1556 script: ScriptSource::Path(script_path),
1557 shell: false,
1558 dry_run: false,
1559 endpoints: EndpointFlags::default(),
1560 remote_serve: false,
1561 mcp: false,
1562 remotes: Vec::new(),
1563 };
1564 let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1565 assert!(
1566 !result.has_snapshot(),
1567 "WORKSPACE LOCAL-only script must not create a snapshot tempdir"
1568 );
1569 assert!(result.snapshot_path().is_none());
1570 let out = workspace_root.join("out.txt").expect("out path");
1572 let contents = resolver.read_to_string(&out).expect("read out");
1573 assert_eq!(contents.trim(), "hi");
1574 assert_eq!(result.final_cwd.root(), workspace_root.as_path());
1576 }
1577
1578 #[cfg_attr(
1579 miri,
1580 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1581 )]
1582 #[test]
1583 fn execute_with_result_empty_script_creates_no_snapshot() {
1584 let workspace = GuardedPath::tempdir().expect("tempdir");
1585 let workspace_root = workspace.as_guarded_path().clone();
1586 let script_path = workspace_root.join("empty.txt").expect("script path");
1587 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1588 .expect("resolver");
1589 resolver
1590 .write_file(&script_path, b"")
1591 .expect("write script");
1592 let opts = Options {
1593 script: ScriptSource::Path(script_path),
1594 shell: false,
1595 dry_run: false,
1596 endpoints: EndpointFlags::default(),
1597 remote_serve: false,
1598 mcp: false,
1599 remotes: Vec::new(),
1600 };
1601 let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1602 assert!(
1603 !result.has_snapshot(),
1604 "empty script must not create a snapshot tempdir"
1605 );
1606 assert_eq!(result.final_cwd, workspace_root);
1607 }
1608
1609 #[cfg_attr(
1610 miri,
1611 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1612 )]
1613 #[test]
1614 fn execute_for_test_invokes_shell_runner() -> Result<()> {
1615 let workspace = GuardedPath::tempdir()?;
1616 let workspace_root = workspace.as_guarded_path().clone();
1617 let script_path = workspace_root.join("empty.txt")?;
1618 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1619 resolver.write_file(&script_path, b"")?;
1620 let opts = Options {
1621 script: ScriptSource::Path(script_path),
1622 shell: true,
1623 dry_run: false,
1624 endpoints: EndpointFlags::default(),
1625 remote_serve: false,
1626 mcp: false,
1627 remotes: Vec::new(),
1628 };
1629 let called = RefCell::new(None::<(String, String)>);
1630 execute_for_test(opts, workspace_root.clone(), |cwd, workspace| {
1631 called.replace(Some((cwd.display(), workspace.display())));
1632 assert!(
1635 cwd.exists(),
1636 "shell cwd must exist on disk, got {}",
1637 cwd.display()
1638 );
1639 Ok(())
1640 })?;
1641 let seen = called.borrow().clone().expect("shell runner called");
1642 assert_eq!(seen.1, workspace_root.display());
1643 Ok(())
1644 }
1645
1646 #[cfg(feature = "ssh")]
1650 #[cfg_attr(
1651 miri,
1652 ignore = "loopback TCP plus threads plus a Tokio runtime; also GuardedPath::tempdir"
1653 )]
1654 #[test]
1655 fn ssh_feature_serves_and_closes() -> Result<()> {
1656 let workspace = GuardedPath::tempdir()?;
1657 let workspace_root = workspace.as_guarded_path().clone();
1658 let script_path = workspace_root.join("ssh-serve.ox")?;
1659 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1660 let script = indoc! {"
1661 IMPORT [STD, SSH]
1662 LET $m: SSH_SERVE_INFO = SSH_SERVE(\"cli-ssh-svc\", {username: \"test\", password: \"test123\"})
1663 SSH_CLOSE($m.server)
1664 "};
1665 resolver.write_file(&script_path, script.as_bytes())?;
1666 let opts = Options {
1667 script: ScriptSource::Path(script_path),
1668 shell: false,
1669 dry_run: false,
1670 endpoints: EndpointFlags {
1671 publishes: vec![(
1672 std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
1673 "cli-ssh-svc".to_string(),
1674 )],
1675 ..EndpointFlags::default()
1676 },
1677 remote_serve: false,
1678 mcp: false,
1679 remotes: Vec::new(),
1680 };
1681 execute_with_result(opts, workspace_root)?;
1682 Ok(())
1683 }
1684
1685 #[cfg(feature = "net")]
1689 #[cfg_attr(
1690 miri,
1691 ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
1692 )]
1693 #[test]
1694 fn net_module_listens_and_closes() -> Result<()> {
1695 let workspace = GuardedPath::tempdir()?;
1696 let workspace_root = workspace.as_guarded_path().clone();
1697 let script_path = workspace_root.join("net-listen.ox")?;
1698 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1699 let script = indoc! {"
1700 IMPORT [STD, NET]
1701 LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
1702 NET_CLOSE($l.listener)
1703 "};
1704 resolver.write_file(&script_path, script.as_bytes())?;
1705 let opts = Options {
1706 script: ScriptSource::Path(script_path),
1707 shell: false,
1708 dry_run: false,
1709 endpoints: EndpointFlags {
1712 publishes: vec![(
1713 std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
1714 "23501".to_string(),
1715 )],
1716 ..EndpointFlags::default()
1717 },
1718 remote_serve: false,
1719 mcp: false,
1720 remotes: Vec::new(),
1721 };
1722 execute_with_result(opts, workspace_root)?;
1723 Ok(())
1724 }
1725
1726 #[cfg(feature = "net")]
1730 #[cfg_attr(
1731 miri,
1732 ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
1733 )]
1734 #[test]
1735 fn net_port_addr_observe_publish_mapping() -> Result<()> {
1736 let workspace = GuardedPath::tempdir()?;
1737 let workspace_root = workspace.as_guarded_path().clone();
1738 let script_path = workspace_root.join("net-port.ox")?;
1739 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1740 let script = indoc! {"
1741 IMPORT [STD, NET]
1742 LET $port: INT = NET_PORT(\"routed-svc\")
1743 WRITE port.txt \"{{ $port }}\"
1744 LET $addr: STRING = NET_ADDR(\"routed-svc\")
1745 WRITE addr.txt \"{{ $addr }}\"
1746 "};
1747 resolver.write_file(&script_path, script.as_bytes())?;
1748 let opts = Options {
1749 script: ScriptSource::Path(script_path),
1750 shell: false,
1751 dry_run: false,
1752 endpoints: EndpointFlags {
1753 publishes: vec![(
1754 std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
1755 "routed-svc".to_string(),
1756 )],
1757 ..EndpointFlags::default()
1758 },
1759 remote_serve: false,
1760 mcp: false,
1761 remotes: Vec::new(),
1762 };
1763 let result = execute_with_result(opts, workspace_root)?;
1764 let snapshot = result
1765 .snapshot_path()
1766 .expect("WRITE materializes the snapshot");
1767 let snapshot_resolver = PathResolver::new(snapshot.root(), snapshot.root())?;
1768 let port_path = snapshot.join("port.txt")?;
1769 let port_text = snapshot_resolver.read_to_string(&port_path)?;
1770 let port: u16 = port_text
1771 .trim()
1772 .parse()
1773 .map_err(|_| anyhow::anyhow!("expected a resolved port, got {port_text:?}"))?;
1774 assert_ne!(port, 0, "ephemeral outer port must resolve");
1775 let addr_path = snapshot.join("addr.txt")?;
1776 let addr_text = snapshot_resolver.read_to_string(&addr_path)?;
1777 assert!(
1778 addr_text.trim().ends_with(&format!(":{port}")),
1779 "dial string must carry the resolved port, got {addr_text:?}"
1780 );
1781 Ok(())
1782 }
1783
1784 #[cfg(not(feature = "ssh"))]
1787 #[cfg_attr(
1788 miri,
1789 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1790 )]
1791 #[test]
1792 fn ssh_scripts_rejected_without_feature() -> Result<()> {
1793 let workspace = GuardedPath::tempdir()?;
1794 let workspace_root = workspace.as_guarded_path().clone();
1795 let script_path = workspace_root.join("ssh-serve.ox")?;
1796 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1797 let script = indoc! {"
1798 IMPORT [STD, SSH]
1799 LET $m: SSH_SERVE_INFO = SSH_SERVE(\"23301\", {username: \"test\", password: \"test123\"})
1800 SSH_CLOSE($m.server)
1801 "};
1802 resolver.write_file(&script_path, script.as_bytes())?;
1803 let opts = Options {
1804 script: ScriptSource::Path(script_path),
1805 shell: false,
1806 dry_run: false,
1807 endpoints: EndpointFlags::default(),
1808 remote_serve: false,
1809 mcp: false,
1810 remotes: Vec::new(),
1811 };
1812 let err = match execute_with_result(opts, workspace_root) {
1813 Ok(_) => panic!("SSH names must be unknown without the feature"),
1814 Err(err) => err,
1815 };
1816 assert!(err.to_string().contains("SSH"), "{err}");
1817 Ok(())
1818 }
1819
1820 #[cfg(not(feature = "net"))]
1824 #[cfg_attr(
1825 miri,
1826 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1827 )]
1828 #[test]
1829 fn net_flags_rejected_without_feature() {
1830 let workspace = GuardedPath::tempdir().expect("tempdir");
1831 for args in [
1832 vec!["--listen", "0.0.0.0:2251", "-"],
1833 vec!["-p", "2222:2251", "-"],
1834 vec!["--listen=0.0.0.0:2251", "-"],
1835 ] {
1836 let mut args = args.into_iter().map(str::to_string);
1837 let err = Options::parse(&mut args, workspace.as_guarded_path())
1838 .expect_err("endpoint flag must fail without net");
1839 assert!(
1840 err.to_string().contains("require the `net` feature"),
1841 "{err:?}"
1842 );
1843 }
1844 let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
1845 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1846 assert!(opts.endpoints.offline);
1847 }
1848
1849 #[cfg(not(feature = "net"))]
1852 #[cfg_attr(
1853 miri,
1854 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1855 )]
1856 #[test]
1857 fn net_scripts_rejected_without_feature() -> Result<()> {
1858 let workspace = GuardedPath::tempdir()?;
1859 let workspace_root = workspace.as_guarded_path().clone();
1860 let script_path = workspace_root.join("net-listen.ox")?;
1861 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1862 let script = indoc! {"
1863 IMPORT [STD, NET]
1864 LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
1865 LET $body: STRING = NET_FETCH(\"https://example.com/x\")
1866 NET_CLOSE($l.listener)
1867 "};
1868 resolver.write_file(&script_path, script.as_bytes())?;
1869 let opts = Options {
1870 script: ScriptSource::Path(script_path),
1871 shell: false,
1872 dry_run: false,
1873 endpoints: EndpointFlags::default(),
1874 remote_serve: false,
1875 mcp: false,
1876 remotes: Vec::new(),
1877 };
1878 let err = match execute_with_result(opts, workspace_root) {
1879 Ok(_) => panic!("NET names must be unknown without the feature"),
1880 Err(err) => err,
1881 };
1882 assert!(err.to_string().contains("NET"), "{err}");
1883 Ok(())
1884 }
1885
1886 #[test]
1887 fn process_exit_code_relays_exit_requests() {
1888 let exit = anyhow::Error::new(ExitRequest(3));
1889 assert_eq!(process_exit_code(&exit), 3);
1890 let relayed =
1891 anyhow::Error::new(ExitRequest(3)).context("REMOTE 'prod' exited with code 3");
1892 assert_eq!(process_exit_code(&relayed), 3);
1893 assert_eq!(process_exit_code(&anyhow::anyhow!("boom")), 1);
1894 assert_eq!(
1895 process_exit_code(&anyhow::Error::new(ExitRequest(300))),
1896 255,
1897 "codes clamp to the portable range"
1898 );
1899 assert_eq!(
1900 process_exit_code(&anyhow::Error::new(ExitRequest(-1))),
1901 0,
1902 "negative codes clamp to zero"
1903 );
1904 }
1905}
1906
1907#[cfg(all(test, windows))]
1908mod windows_shell_tests {
1909 use super::*;
1910
1911 #[test]
1912 fn command_path_strips_verbatim_prefix() -> Result<()> {
1913 let temp = GuardedPath::tempdir()?;
1914 let converted = oxdock_fs::command_path(temp.as_guarded_path());
1915 let as_str = converted.as_ref().display().to_string();
1916 assert!(
1917 !as_str.starts_with(r"\\?\"),
1918 "expected non-verbatim path, got {as_str}"
1919 );
1920 Ok(())
1921 }
1922}