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, ExitRequest, FuncKind, FuncMeta, FuncParam, HostModule,
15 HostRegistration, NativeFn, OxDockFn, OxDockType, PureFn, PushManifestSink, StepCtx,
16 TypeDescriptor, Value, exit_code_of, parse_script, parse_script_with_modules, run_steps,
17 run_steps_with_context, run_steps_with_context_result, 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#[cfg(feature = "net")]
31mod serve;
32
33fn cli_host_modules() -> Vec<HostModule<DefaultProcessManager>> {
42 cli_host_modules_with(None)
43}
44
45#[cfg(feature = "net")]
49fn cli_host_modules_for_serve() -> Vec<HostModule<DefaultProcessManager>> {
50 cli_host_modules_with(None)
51}
52
53#[cfg(feature = "net")]
56fn remote_session_module_hash(entries: &[(String, Vec<String>)]) -> String {
57 oxdock_net_plugin::module_hash(entries)
58}
59
60fn cli_host_modules_with(
67 #[cfg(feature = "net")] registry: Option<&Arc<EndpointRegistry>>,
68 #[cfg(not(feature = "net"))] registry: Option<&Arc<()>>,
69) -> Vec<HostModule<DefaultProcessManager>> {
70 #[cfg(any(feature = "net", feature = "markdown"))]
71 let mut modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
72 #[cfg(not(any(feature = "net", feature = "markdown")))]
73 let modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
74 #[cfg(feature = "net")]
75 {
76 let net_module = match registry {
77 Some(registry) => oxdock_net_plugin::module_with_endpoints(Arc::clone(registry)),
78 None => oxdock_net_plugin::module(),
79 };
80 modules.push(net_module);
81 #[cfg(feature = "ssh")]
82 {
83 let ssh_module = match registry {
84 Some(registry) => oxdock_ssh_plugin::module_with_endpoints(Arc::clone(registry)),
85 None => oxdock_ssh_plugin::module(),
86 };
87 modules.push(ssh_module);
88 }
89 }
90 #[cfg(feature = "markdown")]
91 modules.push(oxdock_markdown_plugin::module());
92 let _ = registry;
93 modules
94}
95
96fn cli_host_types() -> Vec<&'static TypeDescriptor> {
98 #[cfg(feature = "net")]
99 let net: &[&'static TypeDescriptor] = &[oxdock_net_plugin::NetListenerTag::descriptor()];
100 #[cfg(not(feature = "net"))]
101 let net: &[&'static TypeDescriptor] = &[];
102 #[cfg(feature = "ssh")]
103 let ssh: &[&'static TypeDescriptor] = &[
104 oxdock_ssh_plugin::SshServerTag::descriptor(),
105 oxdock_ssh_plugin::SshSessionTag::descriptor(),
106 ];
107 #[cfg(not(feature = "ssh"))]
108 let ssh: &[&'static TypeDescriptor] = &[];
109 net.iter().chain(ssh.iter()).copied().collect()
110}
111
112fn parse_cli_script(script: &str) -> Result<Vec<Step>> {
116 let modules = cli_host_modules();
117 if modules.is_empty() {
118 parse_script(script)
119 } else {
120 let mut engine = Engine::new();
121 for module in modules {
122 engine.register_module(module);
123 }
124 parse_script_with_modules(script, engine.module_table())
125 }
126}
127
128pub fn run() -> Result<()> {
129 init_temp_gc();
130 let workspace_root = discover_workspace_root().context("guard workspace root")?;
131
132 let mut args = std::env::args().skip(1);
133 let opts = match Options::parse(&mut args, &workspace_root) {
137 Ok(opts) => opts,
138 Err(err) if err.to_string() == usage() => {
139 print!("{err}");
140 return Ok(());
141 }
142 Err(err) => return Err(err),
143 };
144 #[cfg(feature = "net")]
147 if opts.remote_serve {
148 if opts.shell || !opts.remotes.is_empty() || !matches!(opts.script, ScriptSource::Stdin) {
149 bail!("--remote-serve runs alone (no --script, --shell, or --remote)");
150 }
151 return serve::serve();
152 }
153 #[cfg(not(feature = "net"))]
154 if opts.remote_serve {
155 bail!("--remote-serve requires the `net` feature (rebuild with --features net)");
156 }
157 execute(opts, workspace_root)
158}
159
160pub fn process_exit_code(err: &anyhow::Error) -> i32 {
164 exit_code_of(err)
165 .map(|code| code.clamp(0, 255) as i32)
166 .unwrap_or(1)
167}
168
169#[derive(Debug, Clone)]
170pub enum ScriptSource {
171 Path(GuardedPath),
172 Stdin,
173}
174
175#[derive(Debug, Clone)]
176pub struct Options {
177 pub script: ScriptSource,
178 pub shell: bool,
179 pub endpoints: EndpointFlags,
180 pub remote_serve: bool,
181 pub remotes: Vec<(String, String)>,
184}
185
186impl Options {
187 pub fn parse(
188 args: &mut impl Iterator<Item = String>,
189 workspace_root: &GuardedPath,
190 ) -> Result<Self> {
191 use lexopt::Arg::{Long, Short, Value};
192
193 let mut script: Option<ScriptSource> = None;
194 let mut shell = false;
195 let mut endpoints = EndpointFlags::default();
196 let mut remote_serve = false;
197 let mut remotes: Vec<(String, String)> = Vec::new();
198 let mut set_script = |source: ScriptSource, origin: &str| -> Result<()> {
199 if script.is_some() {
200 bail!("script given multiple times ({origin})");
201 }
202 script = Some(source);
203 Ok(())
204 };
205 let mut parser = lexopt::Parser::from_args(args.by_ref());
210 while let Some(arg) = parser.next()? {
211 match arg {
212 Long("script") => {
213 let path = value_string(
214 parser
215 .value()
216 .map_err(|_| anyhow::anyhow!("--script requires a path"))?,
217 )?;
218 if path.is_empty() {
219 bail!("--script requires a path");
220 }
221 if path == "-" {
222 set_script(ScriptSource::Stdin, "--script -")?;
223 } else {
224 set_script(
225 ScriptSource::Path(
226 workspace_root
227 .join(&path)
228 .with_context(|| format!("guard script path {path}"))?,
229 ),
230 "--script",
231 )?;
232 }
233 }
234 Long("shell") => {
235 shell = true;
236 }
237 Long("listen") => {
238 let raw = value_string(
239 parser
240 .value()
241 .map_err(|_| anyhow::anyhow!("--listen requires an address"))?,
242 )?;
243 #[cfg(not(feature = "net"))]
244 {
245 let _ = endpoints::parse_listen_arg(&raw);
249 bail!(
250 "--listen/-p require the `net` feature (rebuild with --features net)"
251 );
252 }
253 #[cfg(feature = "net")]
254 endpoints.listens.push(endpoints::parse_listen_arg(&raw)?);
255 }
256 Short('p') => {
257 let raw = value_string(
258 parser
259 .value()
260 .map_err(|_| anyhow::anyhow!("-p requires outer:inner"))?,
261 )?;
262 #[cfg(not(feature = "net"))]
263 {
264 let _ = endpoints::parse_publish_arg(&raw);
268 bail!(
269 "--listen/-p require the `net` feature (rebuild with --features net)"
270 );
271 }
272 #[cfg(feature = "net")]
273 endpoints
274 .publishes
275 .push(endpoints::parse_publish_arg(&raw)?);
276 }
277 Long("offline") => {
278 endpoints.offline = true;
279 }
280 Long("remote-serve") => {
281 remote_serve = true;
282 }
283 Long("remote") => {
284 let raw = value_string(parser.value().map_err(|_| {
285 anyhow::anyhow!("--remote requires <target>=\"<command>\"")
286 })?)?;
287 #[cfg(not(feature = "net"))]
288 {
289 let _ = oxdock_net_plugin_stub_parse_remote(&raw);
292 bail!("--remote requires the `net` feature (rebuild with --features net)");
293 }
294 #[cfg(feature = "net")]
295 remotes.push(oxdock_net_plugin::parse_remote_arg(&raw)?);
296 }
297 Long("help") | Short('h') => {
298 bail!("{}", usage());
299 }
300 Value(value) => {
301 let text = value_string(value)?;
302 if text.is_empty() {
303 continue;
304 }
305 if text == "-" {
306 set_script(ScriptSource::Stdin, "positional `-`")?;
307 } else {
308 set_script(
309 ScriptSource::Path(
310 workspace_root
311 .join(&text)
312 .with_context(|| format!("guard script path {text}"))?,
313 ),
314 "positional argument",
315 )?;
316 }
317 }
318 Long(other) => bail!("unexpected flag: --{other}"),
319 Short(other) => bail!("unexpected flag: -{other}"),
320 }
321 }
322
323 let script = script.unwrap_or(ScriptSource::Stdin);
324
325 Ok(Self {
326 script,
327 shell,
328 endpoints,
329 remote_serve,
330 remotes,
331 })
332 }
333}
334
335fn value_string(value: std::ffi::OsString) -> Result<String> {
338 value
339 .into_string()
340 .map_err(|_| anyhow::anyhow!("argument must be UTF-8"))
341}
342
343pub fn usage() -> String {
345 let version = env!("CARGO_PKG_VERSION");
346 let description = env!("CARGO_PKG_DESCRIPTION");
347 #[cfg(feature = "net")]
348 {
349 indoc::formatdoc! {"
350 oxdock {version} — {description}
351 Usage: oxdock [OPTIONS] [SCRIPT]
352 SCRIPT script file path (same as `--script <file>`); `-` reads stdin
353 --script <file|-> script file under the workspace root, or `-` for stdin
354 --shell run the script, then drop into an interactive shell (requires a TTY)
355 --listen <addr> expose a logical service port ([host:]port, repeatable)
356 -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)
357 --offline open no sockets (conflicts with --listen/-p)
358 --remote TARGET=CMD bind a REMOTE target to a stdio transport command (repeatable)
359 --help, -h print this help and exit
360 With no script given, reads the script from stdin (must be piped unless `--shell`).
361 Scripts declare logical endpoints (a port like 2251); the flags above map them to interfaces.
362 "}
363 }
364 #[cfg(not(feature = "net"))]
365 {
366 indoc::formatdoc! {"
367 oxdock {version} — {description}
368 Usage: oxdock [OPTIONS] [SCRIPT]
369 SCRIPT script file path (same as `--script <file>`); `-` reads stdin
370 --script <file|-> script file under the workspace root, or `-` for stdin
371 --shell run the script, then drop into an interactive shell (requires a TTY)
372 --offline open no sockets (endpoint flags require the `net` feature)
373 --help, -h print this help and exit
374 With no script given, reads the script from stdin (must be piped unless `--shell`).
375 Endpoint flags (--listen/-p) require the `net` feature (rebuild with --features net).
376 "}
377 }
378}
379
380pub fn execute(opts: Options, workspace_root: GuardedPath) -> Result<()> {
381 init_temp_gc();
382 execute_with_shell_runner(opts, workspace_root, run_shell, true)
383}
384
385pub struct ExecutionResult {
393 pub snapshot: Arc<LazyGuardedTempDir>,
397 pub final_cwd: GuardedPath,
400 pub bindings: BTreeMap<String, Value>,
404}
405
406impl ExecutionResult {
407 pub fn has_snapshot(&self) -> bool {
409 self.snapshot.is_materialized()
410 }
411
412 pub fn snapshot_path(&self) -> Option<&GuardedPath> {
414 self.snapshot.get()
415 }
416}
417
418pub fn execute_with_result(opts: Options, workspace_root: GuardedPath) -> Result<ExecutionResult> {
419 if opts.shell {
420 bail!("execute_with_result does not support --shell");
421 }
422
423 let script = read_script(&opts.script, &workspace_root)?;
426
427 let mut final_cwd = workspace_root.clone();
428 let snapshot = Arc::new(LazyGuardedTempDir::new());
429 if !script.trim().is_empty() {
430 #[cfg(feature = "net")]
433 let registry = build_registry(&opts.endpoints)?;
434 #[cfg(not(feature = "net"))]
435 check_no_net_endpoints(&opts.endpoints)?;
436 #[cfg(not(feature = "net"))]
437 check_no_net_remotes(&opts.remotes)?;
438 let steps = parse_cli_script(&script)?;
439 #[cfg(feature = "net")]
443 let inventory = {
444 let pairs = opts.remotes.clone();
445 let inventory = oxdock_net_plugin::RemoteInventory::build(pairs)?;
446 inventory.log_resolutions();
447 inventory.validate_script(&steps)?;
448 inventory
449 };
450 #[cfg(feature = "net")]
451 let output = {
452 let mut io_cfg = ExecIo::new();
453 register_remote_runners(&mut io_cfg, &inventory);
454 run_steps_with_lazy_snapshot_and_modules(
455 &workspace_root,
456 &steps,
457 io_cfg,
458 cli_host_modules_with(Some(®istry)),
459 cli_host_types(),
460 )?
461 };
462 #[cfg(not(feature = "net"))]
463 let output = run_steps_with_lazy_snapshot_and_modules(
464 &workspace_root,
465 &steps,
466 ExecIo::new(),
467 cli_host_modules_with(None),
468 cli_host_types(),
469 )?;
470 final_cwd = output.final_cwd;
471 return Ok(ExecutionResult {
472 snapshot: output.snapshot,
473 final_cwd,
474 bindings: output.bindings,
475 });
476 }
477
478 Ok(ExecutionResult {
479 snapshot,
480 final_cwd,
481 bindings: BTreeMap::new(),
482 })
483}
484
485#[cfg(feature = "net")]
490fn register_remote_runners(io: &mut ExecIo, inventory: &oxdock_net_plugin::RemoteInventory) {
491 use std::sync::Arc;
492 let entries = surface_entries();
493 let module_hash = oxdock_net_plugin::module_hash(&entries);
494 let modules: Vec<String> = entries.iter().map(|(name, _)| name.clone()).collect();
495 for target in inventory.targets() {
496 let Some(argv) = inventory.argv(&target) else {
497 continue;
498 };
499 let config = oxdock_net_plugin::SessionConfig {
500 argv: argv.to_vec(),
501 oxdock_version: env!("CARGO_PKG_VERSION").to_string(),
502 modules: modules.clone(),
503 module_hash: module_hash.clone(),
504 };
505 io.set_remote_runner_for_target(
506 target,
507 Arc::new(oxdock_net_plugin::StdioSession::new(config)),
508 );
509 }
510}
511
512#[cfg(feature = "net")]
515fn surface_entries() -> Vec<(String, Vec<String>)> {
516 let mut engine = Engine::new();
517 for module in cli_host_modules() {
518 engine.register_module(module);
519 }
520 let table = engine.module_table();
521 let mut entries: Vec<(String, Vec<String>)> = table
522 .modules
523 .into_iter()
524 .map(|(name, funcs)| {
525 let mut functions: Vec<String> = funcs
526 .map(|surface| surface.functions.into_iter().collect())
527 .unwrap_or_default();
528 functions.sort();
529 (name, functions)
530 })
531 .collect();
532 entries.sort();
533 entries
534}
535#[cfg(feature = "net")]
536fn report_ephemeral_publishes(flags: &EndpointFlags, registry: &Arc<EndpointRegistry>) {
537 use oxdock_net_plugin::{EndpointKey, Protocol, parse_endpoint_ref};
538 for (outer, inner) in &flags.publishes {
539 if outer.port() != 0 {
540 continue;
541 }
542 let Ok((protocol, endpoint)) = parse_endpoint_ref(inner, "-p") else {
543 continue;
544 };
545 let key = EndpointKey {
546 protocol: protocol.unwrap_or(Protocol::Tcp),
547 endpoint,
548 };
549 match registry.resolve_endpoint(&key) {
550 Ok(addr) => eprintln!("oxdock: published {addr} -> {inner}"),
551 Err(_) => eprintln!("oxdock: published <unbound> -> {inner}"),
552 }
553 }
554}
555
556#[cfg(not(feature = "net"))]
559fn oxdock_net_plugin_stub_parse_remote(raw: &str) -> Result<(String, String)> {
560 match raw.split_once('=') {
563 Some((target, command)) if !target.trim().is_empty() && !command.trim().is_empty() => {
564 Ok((target.trim().to_string(), command.to_string()))
565 }
566 _ => bail!("invalid --remote {raw:?}: expected <target>=\"<command>\""),
567 }
568}
569
570#[cfg(not(feature = "net"))]
572fn check_no_net_remotes(remotes: &[(String, String)]) -> Result<()> {
573 if !remotes.is_empty() {
574 bail!("--remote requires the `net` feature (rebuild with --features net)");
575 }
576 Ok(())
577}
578
579#[cfg(not(feature = "net"))]
583fn check_no_net_endpoints(flags: &EndpointFlags) -> Result<()> {
584 if !flags.listens.is_empty() || !flags.publishes.is_empty() {
585 bail!("--listen/-p require the `net` feature (rebuild with --features net)");
586 }
587 Ok(())
588}
589
590fn read_script(source: &ScriptSource, workspace_root: &GuardedPath) -> Result<String> {
592 match source {
593 ScriptSource::Path(path) => {
594 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
595 resolver
596 .read_to_string(path)
597 .with_context(|| format!("failed to read script at {}", path.display()))
598 }
599 ScriptSource::Stdin => {
600 let mut buf = String::new();
601 io::stdin()
602 .lock()
603 .read_to_string(&mut buf)
604 .context("failed to read script from stdin")?;
605 Ok(buf)
606 }
607 }
608}
609
610fn execute_with_shell_runner<F>(
611 opts: Options,
612 workspace_root: GuardedPath,
613 shell_runner: F,
614 require_tty: bool,
615) -> Result<()>
616where
617 F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
618{
619 #[cfg(windows)]
620 maybe_reexec_shell_to_temp(&opts)?;
621
622 let script = match &opts.script {
626 ScriptSource::Path(path) => {
627 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
630 resolver
631 .read_to_string(path)
632 .with_context(|| format!("failed to read script at {}", path.display()))?
633 }
634 ScriptSource::Stdin => {
635 let stdin = io::stdin();
636 if stdin.is_terminal() {
637 if opts.shell {
642 String::new()
643 } else {
644 bail!(
645 "no stdin detected; pass --script <file> or pipe a script into stdin (use --script - if explicit)"
646 );
647 }
648 } else {
649 let mut buf = String::new();
650 stdin
651 .lock()
652 .read_to_string(&mut buf)
653 .context("failed to read script from stdin")?;
654 buf
655 }
656 }
657 };
658
659 let mut final_cwd = workspace_root.clone();
666 let mut snapshot = Arc::new(LazyGuardedTempDir::new());
667 let mut fs: Option<Box<dyn WorkspaceFs>> = None;
668 if !script.trim().is_empty() {
669 #[cfg(feature = "net")]
672 let registry = build_registry(&opts.endpoints)?;
673 #[cfg(not(feature = "net"))]
674 check_no_net_endpoints(&opts.endpoints)?;
675 #[cfg(not(feature = "net"))]
676 check_no_net_remotes(&opts.remotes)?;
677 #[cfg(feature = "net")]
678 report_ephemeral_publishes(&opts.endpoints, ®istry);
679 let steps = parse_cli_script(&script)?;
680 #[cfg(feature = "net")]
684 let inventory = {
685 let inventory = oxdock_net_plugin::RemoteInventory::build(opts.remotes.clone())?;
686 inventory.log_resolutions();
687 inventory.validate_script(&steps)?;
688 inventory
689 };
690 let mut stdin_handle: Option<SharedInput> = None;
695 if let ScriptSource::Path(_) = opts.script {
696 let stdin = io::stdin();
697 if !stdin.is_terminal() {
698 stdin_handle = Some(Arc::new(Mutex::new(stdin)));
704 }
705 }
706
707 let mut io_cfg = ExecIo::new();
708 io_cfg.set_stdin(stdin_handle);
709 #[cfg(feature = "net")]
710 register_remote_runners(&mut io_cfg, &inventory);
711 #[cfg(feature = "net")]
712 let output = run_steps_with_lazy_snapshot_and_modules(
713 &workspace_root,
714 &steps,
715 io_cfg,
716 cli_host_modules_with(Some(®istry)),
717 cli_host_types(),
718 )?;
719 #[cfg(not(feature = "net"))]
720 let output = run_steps_with_lazy_snapshot_and_modules(
721 &workspace_root,
722 &steps,
723 io_cfg,
724 cli_host_modules_with(None),
725 cli_host_types(),
726 )?;
727 final_cwd = output.final_cwd;
728 snapshot = output.snapshot;
729 fs = Some(output.fs);
730 }
731
732 if opts.shell {
734 if require_tty && !has_controlling_tty() {
735 bail!("--shell requires a tty (no controlling tty available)");
736 }
737 match fs.as_ref() {
742 Some(fs) => {
743 if fs.is_snapshot_pending() {
744 snapshot
745 .materialize()
746 .context("failed to create shell temp dir")?;
747 }
748 final_cwd = fs.concretize_cwd(&final_cwd);
749 }
750 None => {
751 snapshot
752 .materialize()
753 .context("failed to create shell temp dir")?;
754 final_cwd = snapshot
755 .get()
756 .cloned()
757 .expect("shell snapshot materialized above");
758 }
759 }
760 return shell_runner(&final_cwd, &workspace_root);
761 }
762
763 Ok(())
764}
765
766#[cfg(test)]
767fn execute_for_test<F>(opts: Options, workspace_root: GuardedPath, shell_runner: F) -> Result<()>
768where
769 F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
770{
771 execute_with_shell_runner(opts, workspace_root, shell_runner, false)
772}
773
774fn has_controlling_tty() -> bool {
775 #[cfg(unix)]
779 {
780 io::stdin().is_terminal() || io::stderr().is_terminal()
781 }
782
783 #[cfg(windows)]
784 {
785 io::stdin().is_terminal() || io::stderr().is_terminal()
786 }
787
788 #[cfg(not(any(unix, windows)))]
789 {
790 false
791 }
792}
793
794#[cfg(windows)]
795fn maybe_reexec_shell_to_temp(opts: &Options) -> Result<()> {
796 if !opts.shell {
799 return Ok(());
800 }
801 if std::env::var(oxdock_env::SHELL_REEXEC).ok().as_deref() == Some("1") {
802 return Ok(());
803 }
804
805 let self_path = std::env::current_exe().context("determine current executable")?;
806 let base_temp =
807 GuardedPath::new_root(std::env::temp_dir().as_path()).context("guard system temp dir")?;
808 let ts = std::time::SystemTime::now()
809 .duration_since(std::time::UNIX_EPOCH)
810 .unwrap_or_default()
811 .as_millis();
812 let temp_file = base_temp
813 .join(&format!("oxdock-shell-{ts}-{}.exe", std::process::id()))
814 .context("construct temp shell path")?;
815
816 let temp_root_guard = temp_file
820 .parent()
821 .ok_or_else(|| anyhow::anyhow!("temp path unexpectedly missing parent"))?;
822 let resolver_temp = PathResolver::new(temp_root_guard.as_path(), temp_root_guard.as_path())?;
823 let dest = temp_file;
824 #[allow(clippy::disallowed_types)]
825 let source = oxdock_fs::UnguardedPath::external(self_path);
826 resolver_temp
827 .copy_file_from_unguarded(&source, &dest)
828 .with_context(|| format!("failed to copy shell runner to {}", dest.display()))?;
829
830 let mut cmd = CommandBuilder::new(dest.as_path());
831 cmd.args(std::env::args_os().skip(1));
832 cmd.env(oxdock_env::SHELL_REEXEC, "1");
833 cmd.spawn()
834 .with_context(|| format!("failed to spawn shell from {}", dest.display()))?;
835
836 std::process::exit(0);
838}
839
840pub fn run_script(workspace_root: &GuardedPath, steps: &[Step]) -> Result<()> {
841 run_steps_with_context(workspace_root, workspace_root, steps)
842}
843
844fn shell_banner(cwd: &GuardedPath, workspace_root: &GuardedPath) -> String {
845 #[cfg(windows)]
846 let cwd_disp = oxdock_fs::command_path(cwd).as_ref().display().to_string();
847 #[cfg(windows)]
848 let workspace_disp = oxdock_fs::command_path(workspace_root)
849 .as_ref()
850 .display()
851 .to_string();
852
853 #[cfg(not(windows))]
854 let cwd_disp = cwd.display().to_string();
855 #[cfg(not(windows))]
856 let workspace_disp = workspace_root.display().to_string();
857
858 let pkg = env::var(oxdock_env::CARGO_PKG_NAME)
859 .unwrap_or_else(|_| oxdock_env::FALLBACK_APP_NAME.to_string());
860 indoc::formatdoc! {"
861 {pkg} shell workspace
862 cwd: {cwd_disp}
863 source: workspace root at {workspace_disp}
864 lifetime: temporary directory created for this shell session; it disappears when you exit
865 creation: temp workspace starts empty unless your script copies files into it
866
867 WARNING: This shell still runs on your host filesystem and is **not** isolated!
868 "}
869}
870
871fn run_shell(cwd: &GuardedPath, workspace_root: &GuardedPath) -> Result<()> {
872 oxdock_process::spawn_interactive_shell(cwd, workspace_root, &shell_banner(cwd, workspace_root))
873}
874
875#[cfg(test)]
878mod tests {
879 use super::*;
880 use indoc::indoc;
881 use oxdock_fs::PathResolver;
882 use std::cell::{Cell, RefCell};
883
884 #[cfg_attr(
885 miri,
886 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
887 )]
888 #[test]
889 fn shell_runner_receives_final_workdir() -> Result<()> {
890 let workspace = GuardedPath::tempdir()?;
891 let workspace_root = workspace.as_guarded_path().clone();
892 let script_path = workspace_root.join("script.ox")?;
893 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
894 let script = indoc! {"
895 WRITE temp.txt 123
896 WORKDIR sub
897 "};
898 resolver.write_file(&script_path, script.as_bytes())?;
899
900 let opts = Options {
901 script: ScriptSource::Path(script_path),
902 shell: true,
903 endpoints: EndpointFlags::default(),
904 remote_serve: false,
905 remotes: Vec::new(),
906 };
907
908 let observed = Cell::new(false);
909 execute_for_test(opts, workspace_root.clone(), |cwd, _| {
910 assert!(
911 cwd.as_path().ends_with("sub"),
912 "final cwd should end in WORKDIR target, got {}",
913 cwd.display()
914 );
915
916 let temp_root = GuardedPath::new_root(cwd.root())
917 .context("construct guard for temp workspace root")?;
918 let sub_dir = temp_root.join("sub")?;
919 assert_eq!(
920 cwd.as_path(),
921 sub_dir.as_path(),
922 "shell runner cwd should match guarded sub dir"
923 );
924 let temp_file = temp_root.join("temp.txt")?;
925 let temp_resolver = PathResolver::new(temp_root.as_path(), temp_root.as_path())?;
926 let contents = temp_resolver.read_to_string(&temp_file)?;
927 assert!(
928 contents.contains("123"),
929 "expected WRITE command to materialize temp file"
930 );
931 observed.set(true);
932 Ok(())
933 })?;
934
935 assert!(
936 observed.into_inner(),
937 "shell runner closure should have been invoked"
938 );
939 Ok(())
940 }
941
942 #[cfg_attr(
943 miri,
944 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
945 )]
946 #[test]
947 fn options_parse_requires_script_path_value() {
948 let workspace = GuardedPath::tempdir().expect("tempdir");
949 let mut args = vec!["--script".to_string()].into_iter();
950 let err = Options::parse(&mut args, workspace.as_guarded_path())
951 .expect_err("expected missing path error");
952 assert!(err.to_string().contains("--script requires a path"));
953 }
954
955 #[cfg_attr(
956 miri,
957 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
958 )]
959 #[test]
960 fn options_parse_script_path_and_shell() {
961 let workspace = GuardedPath::tempdir().expect("tempdir");
962 let workspace_root = workspace.as_guarded_path().clone();
963 let script_path = workspace_root.join("script.txt").expect("script path");
964 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
965 .expect("resolver");
966 resolver
967 .write_file(&script_path, b"WRITE out.txt hi")
968 .expect("write script");
969 let mut args = vec![
970 "--script".to_string(),
971 "script.txt".to_string(),
972 "--shell".to_string(),
973 ]
974 .into_iter();
975 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
976 assert!(opts.shell);
977 match opts.script {
978 ScriptSource::Path(path) => assert_eq!(path, script_path),
979 ScriptSource::Stdin => panic!("expected path script"),
980 }
981 }
982
983 #[cfg_attr(
984 miri,
985 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
986 )]
987 #[test]
988 fn options_parse_positional_script_path() {
989 let workspace = GuardedPath::tempdir().expect("tempdir");
990 let workspace_root = workspace.as_guarded_path().clone();
991 let mut args = vec!["script.txt".to_string()].into_iter();
992 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
993 assert!(!opts.shell);
994 match opts.script {
995 ScriptSource::Path(path) => assert_eq!(
996 path,
997 workspace_root.join("script.txt").expect("script path")
998 ),
999 ScriptSource::Stdin => panic!("expected path script"),
1000 }
1001 }
1002
1003 #[cfg_attr(
1004 miri,
1005 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1006 )]
1007 #[test]
1008 fn options_parse_positional_dash_reads_stdin() {
1009 let workspace = GuardedPath::tempdir().expect("tempdir");
1010 let mut args = vec!["-".to_string()].into_iter();
1011 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1012 assert!(matches!(opts.script, ScriptSource::Stdin));
1013 }
1014
1015 #[cfg_attr(
1016 miri,
1017 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1018 )]
1019 #[test]
1020 fn options_parse_rejects_duplicate_script_sources() {
1021 let workspace = GuardedPath::tempdir().expect("tempdir");
1022 let workspace_root = workspace.as_guarded_path().clone();
1023 let mut args = vec![
1024 "a.ox".to_string(),
1025 "--script".to_string(),
1026 "b.ox".to_string(),
1027 ]
1028 .into_iter();
1029 let err = Options::parse(&mut args, &workspace_root)
1030 .expect_err("expected duplicate script error");
1031 assert!(err.to_string().contains("multiple times"), "{err:?}");
1032
1033 let mut args = vec!["a.ox".to_string(), "b.ox".to_string()].into_iter();
1034 let err = Options::parse(&mut args, &workspace_root)
1035 .expect_err("expected duplicate script error");
1036 assert!(err.to_string().contains("multiple times"), "{err:?}");
1037 }
1038
1039 #[cfg_attr(
1040 miri,
1041 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1042 )]
1043 #[test]
1044 fn options_parse_rejects_unknown_flags() {
1045 let workspace = GuardedPath::tempdir().expect("tempdir");
1046 let mut args = vec!["--frobnicate".to_string()].into_iter();
1047 let err = Options::parse(&mut args, workspace.as_guarded_path())
1048 .expect_err("expected unknown flag error");
1049 assert!(err.to_string().contains("unexpected flag"), "{err:?}");
1050 }
1051
1052 #[test]
1053 fn usage_describes_positional_script_and_help() {
1054 let text = usage();
1055 assert!(text.contains("Usage: oxdock"), "{text}");
1056 assert!(text.contains("SCRIPT"), "{text}");
1057 assert!(text.contains("--script"), "{text}");
1058 assert!(text.contains("--help"), "{text}");
1059 assert!(text.contains("--offline"), "{text}");
1060 #[cfg(feature = "net")]
1061 {
1062 assert!(text.contains("--listen"), "{text}");
1063 assert!(text.contains("-p <[host:]outer:inner>"), "{text}");
1064 }
1065 #[cfg(not(feature = "net"))]
1066 {
1067 assert!(!text.contains("--listen <addr>"), "{text}");
1068 assert!(!text.contains("-p <[host:]outer:inner>"), "{text}");
1069 assert!(text.contains("require the `net` feature"), "{text}");
1070 }
1071 assert!(text.contains(env!("CARGO_PKG_DESCRIPTION")), "{text}");
1073 }
1074
1075 #[cfg(feature = "net")]
1076 #[cfg_attr(
1077 miri,
1078 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1079 )]
1080 #[test]
1081 fn options_parse_endpoint_flags() {
1082 let workspace = GuardedPath::tempdir().expect("tempdir");
1085 let mut args = vec![
1086 "--listen".to_string(),
1087 "0.0.0.0:2251".to_string(),
1088 "-p".to_string(),
1089 "2222:demo-proxy".to_string(),
1090 "-p".to_string(),
1091 "0:2252".to_string(),
1092 "-".to_string(),
1093 ]
1094 .into_iter();
1095 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1096 assert_eq!(opts.endpoints.listens.len(), 1);
1097 assert_eq!(opts.endpoints.publishes.len(), 2);
1098 assert!(!opts.endpoints.offline);
1099 assert!(matches!(opts.script, ScriptSource::Stdin));
1100 }
1101
1102 #[cfg_attr(
1103 miri,
1104 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1105 )]
1106 #[test]
1107 fn options_parse_offline_flag() {
1108 let workspace = GuardedPath::tempdir().expect("tempdir");
1109 let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
1110 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1111 assert!(opts.endpoints.offline);
1112 }
1113
1114 #[cfg(feature = "net")]
1115 #[cfg_attr(
1116 miri,
1117 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1118 )]
1119 #[test]
1120 fn options_parse_rejects_bad_endpoint_flags() {
1121 let workspace = GuardedPath::tempdir().expect("tempdir");
1122 for args in [
1123 vec!["--listen"],
1124 vec!["--listen", "0.0.0.0:0"],
1125 vec!["-p"],
1126 vec!["-p", "2222"],
1127 vec!["-p", "2222:0"],
1128 ] {
1129 let mut args = args.into_iter().map(str::to_string);
1130 Options::parse(&mut args, workspace.as_guarded_path())
1131 .expect_err("bad endpoint flag must fail");
1132 }
1133 }
1134
1135 #[cfg_attr(
1136 miri,
1137 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1138 )]
1139 #[test]
1140 fn options_parse_empty_values_hold_token_boundaries() {
1141 let workspace = GuardedPath::tempdir().expect("tempdir");
1145 let mut args = vec![
1146 "--script".to_string(),
1147 "".to_string(),
1148 "--shell".to_string(),
1149 ]
1150 .into_iter();
1151 let err = Options::parse(&mut args, workspace.as_guarded_path())
1152 .expect_err("empty script path must fail");
1153 assert!(
1154 err.to_string().contains("--script requires a path"),
1155 "{err:?}"
1156 );
1157 let mut args = vec!["".to_string(), "-".to_string()].into_iter();
1158 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1159 assert!(matches!(opts.script, ScriptSource::Stdin));
1160 }
1161
1162 #[cfg(feature = "net")]
1163 #[cfg_attr(
1164 miri,
1165 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1166 )]
1167 #[test]
1168 fn options_parse_accepts_equals_and_attached_forms() {
1169 let workspace = GuardedPath::tempdir().expect("tempdir");
1172 let workspace_root = workspace.as_guarded_path().clone();
1173 let mut args = vec![
1174 "--listen=0.0.0.0:2251".to_string(),
1175 "-p2222:demo-proxy".to_string(),
1176 "--".to_string(),
1177 "script.ox".to_string(),
1178 ]
1179 .into_iter();
1180 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1181 assert_eq!(opts.endpoints.listens.len(), 1);
1182 assert_eq!(opts.endpoints.publishes.len(), 1);
1183 match opts.script {
1184 ScriptSource::Path(path) => {
1185 assert_eq!(path, workspace_root.join("script.ox").expect("script path"))
1186 }
1187 ScriptSource::Stdin => panic!("expected path script after --"),
1188 }
1189 }
1190
1191 #[cfg_attr(
1192 miri,
1193 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1194 )]
1195 #[test]
1196 fn options_parse_help_returns_usage_error_without_exiting() {
1197 let workspace = GuardedPath::tempdir().expect("tempdir");
1200 for flag in ["--help", "-h"] {
1201 let mut args = vec![flag.to_string()].into_iter();
1202 let err = Options::parse(&mut args, workspace.as_guarded_path())
1203 .expect_err("help flag must not parse as options");
1204 assert_eq!(err.to_string(), usage());
1205 }
1206 }
1207
1208 #[cfg_attr(
1209 miri,
1210 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1211 )]
1212 #[test]
1213 fn execute_with_result_runs_script() {
1214 let workspace = GuardedPath::tempdir().expect("tempdir");
1215 let workspace_root = workspace.as_guarded_path().clone();
1216 let script_path = workspace_root.join("script.txt").expect("script path");
1217 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1218 .expect("resolver");
1219 resolver
1220 .write_file(&script_path, b"WRITE out.txt hi")
1221 .expect("write script");
1222 let opts = Options {
1223 script: ScriptSource::Path(script_path),
1224 shell: false,
1225 endpoints: EndpointFlags::default(),
1226 remote_serve: false,
1227 remotes: Vec::new(),
1228 };
1229 let result = execute_with_result(opts, workspace_root).expect("execute");
1230 let snapshot = result
1231 .snapshot_path()
1232 .expect("default WRITE materializes the snapshot");
1233 assert_eq!(snapshot, &result.final_cwd);
1234 let temp_resolver = PathResolver::new(snapshot.root(), snapshot.root()).expect("resolver");
1235 let out = snapshot.join("out.txt").expect("out path");
1236 let contents = temp_resolver.read_to_string(&out).expect("read out");
1237 assert_eq!(contents.trim(), "hi");
1238 }
1239
1240 #[cfg_attr(
1241 miri,
1242 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1243 )]
1244 #[test]
1245 fn execute_with_result_local_only_creates_no_snapshot() {
1246 let workspace = GuardedPath::tempdir().expect("tempdir");
1247 let workspace_root = workspace.as_guarded_path().clone();
1248 let script_path = workspace_root.join("script.txt").expect("script path");
1249 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1250 .expect("resolver");
1251 resolver
1252 .write_file(&script_path, b"WORKSPACE LOCAL\nWRITE out.txt hi")
1253 .expect("write script");
1254 let opts = Options {
1255 script: ScriptSource::Path(script_path),
1256 shell: false,
1257 endpoints: EndpointFlags::default(),
1258 remote_serve: false,
1259 remotes: Vec::new(),
1260 };
1261 let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1262 assert!(
1263 !result.has_snapshot(),
1264 "WORKSPACE LOCAL-only script must not create a snapshot tempdir"
1265 );
1266 assert!(result.snapshot_path().is_none());
1267 let out = workspace_root.join("out.txt").expect("out path");
1269 let contents = resolver.read_to_string(&out).expect("read out");
1270 assert_eq!(contents.trim(), "hi");
1271 assert_eq!(result.final_cwd.root(), workspace_root.as_path());
1273 }
1274
1275 #[cfg_attr(
1276 miri,
1277 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1278 )]
1279 #[test]
1280 fn execute_with_result_empty_script_creates_no_snapshot() {
1281 let workspace = GuardedPath::tempdir().expect("tempdir");
1282 let workspace_root = workspace.as_guarded_path().clone();
1283 let script_path = workspace_root.join("empty.txt").expect("script path");
1284 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1285 .expect("resolver");
1286 resolver
1287 .write_file(&script_path, b"")
1288 .expect("write script");
1289 let opts = Options {
1290 script: ScriptSource::Path(script_path),
1291 shell: false,
1292 endpoints: EndpointFlags::default(),
1293 remote_serve: false,
1294 remotes: Vec::new(),
1295 };
1296 let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1297 assert!(
1298 !result.has_snapshot(),
1299 "empty script must not create a snapshot tempdir"
1300 );
1301 assert_eq!(result.final_cwd, workspace_root);
1302 }
1303
1304 #[cfg_attr(
1305 miri,
1306 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1307 )]
1308 #[test]
1309 fn execute_for_test_invokes_shell_runner() -> Result<()> {
1310 let workspace = GuardedPath::tempdir()?;
1311 let workspace_root = workspace.as_guarded_path().clone();
1312 let script_path = workspace_root.join("empty.txt")?;
1313 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1314 resolver.write_file(&script_path, b"")?;
1315 let opts = Options {
1316 script: ScriptSource::Path(script_path),
1317 shell: true,
1318 endpoints: EndpointFlags::default(),
1319 remote_serve: false,
1320 remotes: Vec::new(),
1321 };
1322 let called = RefCell::new(None::<(String, String)>);
1323 execute_for_test(opts, workspace_root.clone(), |cwd, workspace| {
1324 called.replace(Some((cwd.display(), workspace.display())));
1325 assert!(
1328 cwd.exists(),
1329 "shell cwd must exist on disk, got {}",
1330 cwd.display()
1331 );
1332 Ok(())
1333 })?;
1334 let seen = called.borrow().clone().expect("shell runner called");
1335 assert_eq!(seen.1, workspace_root.display());
1336 Ok(())
1337 }
1338
1339 #[cfg(feature = "ssh")]
1343 #[cfg_attr(
1344 miri,
1345 ignore = "loopback TCP plus threads plus a Tokio runtime; also GuardedPath::tempdir"
1346 )]
1347 #[test]
1348 fn ssh_feature_serves_and_closes() -> Result<()> {
1349 let workspace = GuardedPath::tempdir()?;
1350 let workspace_root = workspace.as_guarded_path().clone();
1351 let script_path = workspace_root.join("ssh-serve.ox")?;
1352 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1353 let script = indoc! {"
1354 IMPORT [STD, SSH]
1355 LET $m: SSH_SERVE_INFO = SSH_SERVE(\"23301\", {username: \"test\", password: \"test123\"})
1356 SSH_CLOSE($m.server)
1357 "};
1358 resolver.write_file(&script_path, script.as_bytes())?;
1359 let opts = Options {
1360 script: ScriptSource::Path(script_path),
1361 shell: false,
1362 endpoints: EndpointFlags::default(),
1363 remote_serve: false,
1364 remotes: Vec::new(),
1365 };
1366 execute_with_result(opts, workspace_root)?;
1367 Ok(())
1368 }
1369
1370 #[cfg(feature = "net")]
1374 #[cfg_attr(
1375 miri,
1376 ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
1377 )]
1378 #[test]
1379 fn net_module_listens_and_closes() -> Result<()> {
1380 let workspace = GuardedPath::tempdir()?;
1381 let workspace_root = workspace.as_guarded_path().clone();
1382 let script_path = workspace_root.join("net-listen.ox")?;
1383 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1384 let script = indoc! {"
1385 IMPORT [STD, NET]
1386 LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
1387 NET_CLOSE($l.listener)
1388 "};
1389 resolver.write_file(&script_path, script.as_bytes())?;
1390 let opts = Options {
1391 script: ScriptSource::Path(script_path),
1392 shell: false,
1393 endpoints: EndpointFlags::default(),
1394 remote_serve: false,
1395 remotes: Vec::new(),
1396 };
1397 execute_with_result(opts, workspace_root)?;
1398 Ok(())
1399 }
1400
1401 #[cfg(feature = "net")]
1405 #[cfg_attr(
1406 miri,
1407 ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
1408 )]
1409 #[test]
1410 fn net_port_addr_observe_publish_mapping() -> Result<()> {
1411 let workspace = GuardedPath::tempdir()?;
1412 let workspace_root = workspace.as_guarded_path().clone();
1413 let script_path = workspace_root.join("net-port.ox")?;
1414 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1415 let script = indoc! {"
1416 IMPORT [STD, NET]
1417 LET $port: INT = NET_PORT(\"routed-svc\")
1418 WRITE port.txt \"{{ $port }}\"
1419 LET $addr: STRING = NET_ADDR(\"routed-svc\")
1420 WRITE addr.txt \"{{ $addr }}\"
1421 "};
1422 resolver.write_file(&script_path, script.as_bytes())?;
1423 let opts = Options {
1424 script: ScriptSource::Path(script_path),
1425 shell: false,
1426 endpoints: EndpointFlags {
1427 publishes: vec![(
1428 std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
1429 "routed-svc".to_string(),
1430 )],
1431 ..EndpointFlags::default()
1432 },
1433 remote_serve: false,
1434 remotes: Vec::new(),
1435 };
1436 let result = execute_with_result(opts, workspace_root)?;
1437 let snapshot = result
1438 .snapshot_path()
1439 .expect("WRITE materializes the snapshot");
1440 let snapshot_resolver = PathResolver::new(snapshot.root(), snapshot.root())?;
1441 let port_path = snapshot.join("port.txt")?;
1442 let port_text = snapshot_resolver.read_to_string(&port_path)?;
1443 let port: u16 = port_text
1444 .trim()
1445 .parse()
1446 .map_err(|_| anyhow::anyhow!("expected a resolved port, got {port_text:?}"))?;
1447 assert_ne!(port, 0, "ephemeral outer port must resolve");
1448 let addr_path = snapshot.join("addr.txt")?;
1449 let addr_text = snapshot_resolver.read_to_string(&addr_path)?;
1450 assert!(
1451 addr_text.trim().ends_with(&format!(":{port}")),
1452 "dial string must carry the resolved port, got {addr_text:?}"
1453 );
1454 Ok(())
1455 }
1456
1457 #[cfg(not(feature = "ssh"))]
1460 #[cfg_attr(
1461 miri,
1462 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1463 )]
1464 #[test]
1465 fn ssh_scripts_rejected_without_feature() -> Result<()> {
1466 let workspace = GuardedPath::tempdir()?;
1467 let workspace_root = workspace.as_guarded_path().clone();
1468 let script_path = workspace_root.join("ssh-serve.ox")?;
1469 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1470 let script = indoc! {"
1471 IMPORT [STD, SSH]
1472 LET $m: SSH_SERVE_INFO = SSH_SERVE(\"23301\", {username: \"test\", password: \"test123\"})
1473 SSH_CLOSE($m.server)
1474 "};
1475 resolver.write_file(&script_path, script.as_bytes())?;
1476 let opts = Options {
1477 script: ScriptSource::Path(script_path),
1478 shell: false,
1479 endpoints: EndpointFlags::default(),
1480 remote_serve: false,
1481 remotes: Vec::new(),
1482 };
1483 let err = match execute_with_result(opts, workspace_root) {
1484 Ok(_) => panic!("SSH names must be unknown without the feature"),
1485 Err(err) => err,
1486 };
1487 assert!(err.to_string().contains("SSH"), "{err}");
1488 Ok(())
1489 }
1490
1491 #[cfg(not(feature = "net"))]
1495 #[cfg_attr(
1496 miri,
1497 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1498 )]
1499 #[test]
1500 fn net_flags_rejected_without_feature() {
1501 let workspace = GuardedPath::tempdir().expect("tempdir");
1502 for args in [
1503 vec!["--listen", "0.0.0.0:2251", "-"],
1504 vec!["-p", "2222:2251", "-"],
1505 vec!["--listen=0.0.0.0:2251", "-"],
1506 ] {
1507 let mut args = args.into_iter().map(str::to_string);
1508 let err = Options::parse(&mut args, workspace.as_guarded_path())
1509 .expect_err("endpoint flag must fail without net");
1510 assert!(
1511 err.to_string().contains("require the `net` feature"),
1512 "{err:?}"
1513 );
1514 }
1515 let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
1516 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1517 assert!(opts.endpoints.offline);
1518 }
1519
1520 #[cfg(not(feature = "net"))]
1523 #[cfg_attr(
1524 miri,
1525 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1526 )]
1527 #[test]
1528 fn net_scripts_rejected_without_feature() -> Result<()> {
1529 let workspace = GuardedPath::tempdir()?;
1530 let workspace_root = workspace.as_guarded_path().clone();
1531 let script_path = workspace_root.join("net-listen.ox")?;
1532 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1533 let script = indoc! {"
1534 IMPORT [STD, NET]
1535 LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
1536 LET $body: STRING = NET_FETCH(\"https://example.com/x\")
1537 NET_CLOSE($l.listener)
1538 "};
1539 resolver.write_file(&script_path, script.as_bytes())?;
1540 let opts = Options {
1541 script: ScriptSource::Path(script_path),
1542 shell: false,
1543 endpoints: EndpointFlags::default(),
1544 remote_serve: false,
1545 remotes: Vec::new(),
1546 };
1547 let err = match execute_with_result(opts, workspace_root) {
1548 Ok(_) => panic!("NET names must be unknown without the feature"),
1549 Err(err) => err,
1550 };
1551 assert!(err.to_string().contains("NET"), "{err}");
1552 Ok(())
1553 }
1554
1555 #[test]
1556 fn process_exit_code_relays_exit_requests() {
1557 let exit = anyhow::Error::new(ExitRequest(3));
1558 assert_eq!(process_exit_code(&exit), 3);
1559 let relayed =
1560 anyhow::Error::new(ExitRequest(3)).context("REMOTE 'prod' exited with code 3");
1561 assert_eq!(process_exit_code(&relayed), 3);
1562 assert_eq!(process_exit_code(&anyhow::anyhow!("boom")), 1);
1563 assert_eq!(
1564 process_exit_code(&anyhow::Error::new(ExitRequest(300))),
1565 255,
1566 "codes clamp to the portable range"
1567 );
1568 assert_eq!(
1569 process_exit_code(&anyhow::Error::new(ExitRequest(-1))),
1570 0,
1571 "negative codes clamp to zero"
1572 );
1573 }
1574}
1575
1576#[cfg(all(test, windows))]
1577mod windows_shell_tests {
1578 use super::*;
1579
1580 #[test]
1581 fn command_path_strips_verbatim_prefix() -> Result<()> {
1582 let temp = GuardedPath::tempdir()?;
1583 let converted = oxdock_fs::command_path(temp.as_guarded_path());
1584 let as_str = converted.as_ref().display().to_string();
1585 assert!(
1586 !as_str.starts_with(r"\\?\"),
1587 "expected non-verbatim path, got {as_str}"
1588 );
1589 Ok(())
1590 }
1591}