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
27use oxdock_macros::oxdock_embed;
32oxdock_embed! {
33 name: UsageAssets,
34 script: {
35 INHERIT_ENV [CARGO_PKG_VERSION, CARGO_PKG_DESCRIPTION]
36 FUNC EMIT_BODY($is_net: BOOL) {
37 ECHO "oxdock {{ env:CARGO_PKG_VERSION }} — {{ env:CARGO_PKG_DESCRIPTION }}"
38 ECHO ""
39 ECHO "Usage: oxdock [OPTIONS] [SCRIPT]"
40 ECHO " SCRIPT script file path (same as `--script <file>`); `-` reads stdin"
41 ECHO " --script <file|-> script file (relative resolves under the OxDock workspace root), or `-` for stdin"
42 ECHO " --shell run the script, then drop into an interactive shell (requires a TTY)"
43 IF $is_net {
44 ECHO " --listen <addr> expose a logical service port ([host:]port, repeatable)"
45 ECHO " -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)"
46 ECHO " --offline open no sockets (conflicts with --listen/-p)"
47 ECHO " --remote TARGET=CMD bind a REMOTE target to a stdio transport command (repeatable)"
48 } ELSE {
49 ECHO " --offline open no sockets (endpoint flags require the `net` feature)"
50 }
51 ECHO " --help, -h print this help and exit"
52 ECHO " --version, -V print the version and exit"
53 ECHO ""
54 ECHO "With no script given, reads the script from stdin (must be piped unless `--shell`)."
55 IF $is_net {
56 ECHO "Scripts declare logical endpoints (a port like 2251); the flags above map them to interfaces."
57 } ELSE {
58 ECHO "Endpoint flags (--listen/-p) require the `net` feature (rebuild with --features net)."
59 }
60 }
61 LET $p: PIPE
62 WITH_IO [stdout=$p] {
63 EMIT_BODY(true)
64 }
65 WITH_IO [stdin=$p] WRITE dist/usage-net.txt
66 WITH_IO [stdout=$p] {
67 EMIT_BODY(false)
68 }
69 WITH_IO [stdin=$p] WRITE dist/usage-lean.txt
70 },
71 out_dir: "usage-prebuilt",
72}
73#[cfg(feature = "net")]
74pub use endpoints::build_registry;
75#[cfg(feature = "net")]
76use oxdock_net_plugin::EndpointRegistry;
77#[cfg(feature = "net")]
78mod serve;
79
80fn cli_host_modules() -> Vec<HostModule<DefaultProcessManager>> {
89 cli_host_modules_with(None)
90}
91
92#[cfg(feature = "net")]
96fn cli_host_modules_for_serve() -> Vec<HostModule<DefaultProcessManager>> {
97 cli_host_modules_with(None)
98}
99
100#[cfg(feature = "net")]
103fn remote_session_module_hash(entries: &[(String, Vec<String>)]) -> String {
104 oxdock_net_plugin::module_hash(entries)
105}
106
107fn cli_host_modules_with(
114 #[cfg(feature = "net")] registry: Option<&Arc<EndpointRegistry>>,
115 #[cfg(not(feature = "net"))] registry: Option<&Arc<()>>,
116) -> Vec<HostModule<DefaultProcessManager>> {
117 #[cfg(any(feature = "net", feature = "markdown"))]
118 let mut modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
119 #[cfg(not(any(feature = "net", feature = "markdown")))]
120 let modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
121 #[cfg(feature = "net")]
122 {
123 let net_module = match registry {
124 Some(registry) => oxdock_net_plugin::module_with_endpoints(Arc::clone(registry)),
125 None => oxdock_net_plugin::module(),
126 };
127 modules.push(net_module);
128 #[cfg(feature = "ssh")]
129 {
130 let ssh_module = match registry {
131 Some(registry) => oxdock_ssh_plugin::module_with_endpoints(Arc::clone(registry)),
132 None => oxdock_ssh_plugin::module(),
133 };
134 modules.push(ssh_module);
135 }
136 }
137 #[cfg(feature = "markdown")]
138 modules.push(oxdock_markdown_plugin::module());
139 let _ = registry;
140 modules
141}
142
143fn cli_host_types() -> Vec<&'static TypeDescriptor> {
145 #[cfg(feature = "net")]
146 let net: &[&'static TypeDescriptor] = &[oxdock_net_plugin::NetListenerTag::descriptor()];
147 #[cfg(not(feature = "net"))]
148 let net: &[&'static TypeDescriptor] = &[];
149 #[cfg(feature = "ssh")]
150 let ssh: &[&'static TypeDescriptor] = &[
151 oxdock_ssh_plugin::SshServerTag::descriptor(),
152 oxdock_ssh_plugin::SshSessionTag::descriptor(),
153 ];
154 #[cfg(not(feature = "ssh"))]
155 let ssh: &[&'static TypeDescriptor] = &[];
156 net.iter().chain(ssh.iter()).copied().collect()
157}
158
159fn parse_cli_script(script: &str) -> Result<Vec<Step>> {
163 let modules = cli_host_modules();
164 if modules.is_empty() {
165 parse_script(script)
166 } else {
167 let mut engine = Engine::new();
168 for module in modules {
169 engine.register_module(module);
170 }
171 parse_script_with_modules(script, engine.module_table())
172 }
173}
174
175pub fn run() -> Result<()> {
176 init_temp_gc();
177 let workspace_root = discover_workspace_root().context("guard workspace root")?;
178
179 let mut args = std::env::args().skip(1);
180 let opts = match Options::parse(&mut args, &workspace_root) {
184 Ok(opts) => opts,
185 Err(err) if err.to_string() == version() => {
186 println!("{err}");
187 return Ok(());
188 }
189 Err(err) if err.to_string() == usage() => {
190 print!("{err}");
191 return Ok(());
192 }
193 Err(err) => return Err(err),
194 };
195 #[cfg(feature = "net")]
198 if opts.remote_serve {
199 if opts.shell || !opts.remotes.is_empty() || !matches!(opts.script, ScriptSource::Stdin) {
200 bail!("--remote-serve runs alone (no --script, --shell, or --remote)");
201 }
202 return serve::serve();
203 }
204 #[cfg(not(feature = "net"))]
205 if opts.remote_serve {
206 bail!("--remote-serve requires the `net` feature (rebuild with --features net)");
207 }
208 execute(opts, workspace_root)
209}
210
211pub fn process_exit_code(err: &anyhow::Error) -> i32 {
215 exit_code_of(err)
216 .map(|code| code.clamp(0, 255) as i32)
217 .unwrap_or(1)
218}
219
220#[derive(Debug, Clone)]
221pub enum ScriptSource {
222 Path(GuardedPath),
223 Stdin,
224}
225
226fn reject_url_script(text: &str) -> Result<()> {
230 if text.contains("://") {
231 bail!("not a local path: {text:?} (pass a workspace path or `-` for stdin)");
232 }
233 Ok(())
234}
235
236#[derive(Debug, Clone)]
237pub struct Options {
238 pub script: ScriptSource,
239 pub shell: bool,
240 pub endpoints: EndpointFlags,
241 pub remote_serve: bool,
242 pub remotes: Vec<(String, String)>,
245}
246
247impl Options {
248 pub fn parse(
249 args: &mut impl Iterator<Item = String>,
250 workspace_root: &GuardedPath,
251 ) -> Result<Self> {
252 use lexopt::Arg::{Long, Short, Value};
253
254 let mut script: Option<ScriptSource> = None;
255 let mut shell = false;
256 let mut endpoints = EndpointFlags::default();
257 let mut remote_serve = false;
258 #[cfg_attr(not(feature = "net"), allow(unused_mut))]
260 let mut remotes: Vec<(String, String)> = Vec::new();
261 let mut set_script = |source: ScriptSource, origin: &str| -> Result<()> {
262 if script.is_some() {
263 bail!("script given multiple times ({origin})");
264 }
265 script = Some(source);
266 Ok(())
267 };
268 let mut parser = lexopt::Parser::from_args(args.by_ref());
273 while let Some(arg) = parser.next()? {
274 match arg {
275 Long("script") => {
276 let path = value_string(
277 parser
278 .value()
279 .map_err(|_| anyhow::anyhow!("--script requires a path"))?,
280 )?;
281 if path.is_empty() {
282 bail!("--script requires a path");
283 }
284 if path == "-" {
285 set_script(ScriptSource::Stdin, "--script -")?;
286 } else {
287 reject_url_script(&path)?;
288 set_script(
289 ScriptSource::Path(
290 workspace_root
291 .join_script(&path)
292 .with_context(|| format!("guard script path {path}"))?,
293 ),
294 "--script",
295 )?;
296 }
297 }
298 Long("shell") => {
299 shell = true;
300 }
301 Long("listen") => {
302 let raw = value_string(
303 parser
304 .value()
305 .map_err(|_| anyhow::anyhow!("--listen requires an address"))?,
306 )?;
307 #[cfg(not(feature = "net"))]
308 {
309 let _ = endpoints::parse_listen_arg(&raw);
313 bail!(
314 "--listen/-p require the `net` feature (rebuild with --features net)"
315 );
316 }
317 #[cfg(feature = "net")]
318 endpoints.listens.push(endpoints::parse_listen_arg(&raw)?);
319 }
320 Short('p') => {
321 let raw = value_string(
322 parser
323 .value()
324 .map_err(|_| anyhow::anyhow!("-p requires outer:inner"))?,
325 )?;
326 #[cfg(not(feature = "net"))]
327 {
328 let _ = endpoints::parse_publish_arg(&raw);
332 bail!(
333 "--listen/-p require the `net` feature (rebuild with --features net)"
334 );
335 }
336 #[cfg(feature = "net")]
337 endpoints
338 .publishes
339 .push(endpoints::parse_publish_arg(&raw)?);
340 }
341 Long("offline") => {
342 endpoints.offline = true;
343 }
344 Long("remote-serve") => {
345 remote_serve = true;
346 }
347 Long("remote") => {
348 let raw = value_string(parser.value().map_err(|_| {
349 anyhow::anyhow!("--remote requires <target>=\"<command>\"")
350 })?)?;
351 #[cfg(not(feature = "net"))]
352 {
353 let _ = oxdock_net_plugin_stub_parse_remote(&raw);
356 bail!("--remote requires the `net` feature (rebuild with --features net)");
357 }
358 #[cfg(feature = "net")]
359 remotes.push(oxdock_net_plugin::parse_remote_arg(&raw)?);
360 }
361 Long("help") | Short('h') => {
362 bail!("{}", usage());
363 }
364 Long("version") | Short('V') => {
365 bail!("{}", version());
366 }
367 Value(value) => {
368 let text = value_string(value)?;
369 if text.is_empty() {
370 continue;
371 }
372 if text == "-" {
373 set_script(ScriptSource::Stdin, "positional `-`")?;
374 } else {
375 reject_url_script(&text)?;
376 set_script(
377 ScriptSource::Path(
378 workspace_root
379 .join_script(&text)
380 .with_context(|| format!("guard script path {text}"))?,
381 ),
382 "positional argument",
383 )?;
384 }
385 }
386 Long(other) => bail!("unexpected flag: --{other}"),
387 Short(other) => bail!("unexpected flag: -{other}"),
388 }
389 }
390
391 let script = script.unwrap_or(ScriptSource::Stdin);
392
393 Ok(Self {
394 script,
395 shell,
396 endpoints,
397 remote_serve,
398 remotes,
399 })
400 }
401}
402
403fn value_string(value: std::ffi::OsString) -> Result<String> {
406 value
407 .into_string()
408 .map_err(|_| anyhow::anyhow!("argument must be UTF-8"))
409}
410
411pub fn version() -> String {
413 format!("oxdock {}", env!("CARGO_PKG_VERSION"))
414}
415
416pub fn usage() -> String {
422 #[cfg(feature = "net")]
423 let asset = "dist/usage-net.txt";
424 #[cfg(not(feature = "net"))]
425 let asset = "dist/usage-lean.txt";
426 let file = UsageAssets::get(asset).expect("usage must be embedded");
427 str::from_utf8(file.data.as_ref())
428 .expect("usage is UTF-8")
429 .to_string()
430}
431
432pub fn execute(opts: Options, workspace_root: GuardedPath) -> Result<()> {
433 init_temp_gc();
434 execute_with_shell_runner(opts, workspace_root, run_shell, true)
435}
436
437pub struct ExecutionResult {
445 pub snapshot: Arc<LazyGuardedTempDir>,
449 pub final_cwd: GuardedPath,
452 pub bindings: BTreeMap<String, Value>,
456}
457
458impl ExecutionResult {
459 pub fn has_snapshot(&self) -> bool {
461 self.snapshot.is_materialized()
462 }
463
464 pub fn snapshot_path(&self) -> Option<&GuardedPath> {
466 self.snapshot.get()
467 }
468}
469
470pub fn execute_with_result(opts: Options, workspace_root: GuardedPath) -> Result<ExecutionResult> {
471 if opts.shell {
472 bail!("execute_with_result does not support --shell");
473 }
474
475 let script = read_script(&opts.script)?;
478
479 let mut final_cwd = workspace_root.clone();
480 let snapshot = Arc::new(LazyGuardedTempDir::new());
481 if !script.trim().is_empty() {
482 #[cfg(feature = "net")]
485 let registry = build_registry(&opts.endpoints)?;
486 #[cfg(not(feature = "net"))]
487 check_no_net_endpoints(&opts.endpoints)?;
488 #[cfg(not(feature = "net"))]
489 check_no_net_remotes(&opts.remotes)?;
490 let steps = parse_cli_script(&script)?;
491 #[cfg(feature = "net")]
495 let inventory = {
496 let pairs = opts.remotes.clone();
497 let inventory = oxdock_net_plugin::RemoteInventory::build(pairs)?;
498 inventory.log_resolutions();
499 inventory.validate_script(&steps)?;
500 inventory
501 };
502 #[cfg(feature = "net")]
503 let output = {
504 let mut io_cfg = ExecIo::new();
505 register_remote_runners(&mut io_cfg, &inventory);
506 run_steps_with_lazy_snapshot_and_modules(
507 &workspace_root,
508 &steps,
509 io_cfg,
510 cli_host_modules_with(Some(®istry)),
511 cli_host_types(),
512 )?
513 };
514 #[cfg(not(feature = "net"))]
515 let output = run_steps_with_lazy_snapshot_and_modules(
516 &workspace_root,
517 &steps,
518 ExecIo::new(),
519 cli_host_modules_with(None),
520 cli_host_types(),
521 )?;
522 final_cwd = output.final_cwd;
523 return Ok(ExecutionResult {
524 snapshot: output.snapshot,
525 final_cwd,
526 bindings: output.bindings,
527 });
528 }
529
530 Ok(ExecutionResult {
531 snapshot,
532 final_cwd,
533 bindings: BTreeMap::new(),
534 })
535}
536
537#[cfg(feature = "net")]
542fn register_remote_runners(io: &mut ExecIo, inventory: &oxdock_net_plugin::RemoteInventory) {
543 use std::sync::Arc;
544 let entries = surface_entries();
545 let module_hash = oxdock_net_plugin::module_hash(&entries);
546 let modules: Vec<String> = entries.iter().map(|(name, _)| name.clone()).collect();
547 for target in inventory.targets() {
548 let Some(argv) = inventory.argv(&target) else {
549 continue;
550 };
551 let config = oxdock_net_plugin::SessionConfig {
552 argv: argv.to_vec(),
553 oxdock_version: env!("CARGO_PKG_VERSION").to_string(),
554 modules: modules.clone(),
555 module_hash: module_hash.clone(),
556 };
557 io.set_remote_runner_for_target(
558 target,
559 Arc::new(oxdock_net_plugin::StdioSession::new(config)),
560 );
561 }
562}
563
564#[cfg(feature = "net")]
567fn surface_entries() -> Vec<(String, Vec<String>)> {
568 let mut engine = Engine::new();
569 for module in cli_host_modules() {
570 engine.register_module(module);
571 }
572 let table = engine.module_table();
573 let mut entries: Vec<(String, Vec<String>)> = table
574 .modules
575 .into_iter()
576 .map(|(name, funcs)| {
577 let mut functions: Vec<String> = funcs
578 .map(|surface| surface.functions.into_iter().collect())
579 .unwrap_or_default();
580 functions.sort();
581 (name, functions)
582 })
583 .collect();
584 entries.sort();
585 entries
586}
587#[cfg(feature = "net")]
588fn report_ephemeral_publishes(flags: &EndpointFlags, registry: &Arc<EndpointRegistry>) {
589 use oxdock_net_plugin::{EndpointKey, Protocol, parse_endpoint_ref};
590 for (outer, inner) in &flags.publishes {
591 if outer.port() != 0 {
592 continue;
593 }
594 let Ok((protocol, endpoint)) = parse_endpoint_ref(inner, "-p") else {
595 continue;
596 };
597 let key = EndpointKey {
598 protocol: protocol.unwrap_or(Protocol::Tcp),
599 endpoint,
600 };
601 match registry.resolve_endpoint(&key) {
602 Ok(addr) => eprintln!("oxdock: published {addr} -> {inner}"),
603 Err(_) => eprintln!("oxdock: published <unbound> -> {inner}"),
604 }
605 }
606}
607
608#[cfg(not(feature = "net"))]
611fn oxdock_net_plugin_stub_parse_remote(raw: &str) -> Result<(String, String)> {
612 match raw.split_once('=') {
615 Some((target, command)) if !target.trim().is_empty() && !command.trim().is_empty() => {
616 Ok((target.trim().to_string(), command.to_string()))
617 }
618 _ => bail!("invalid --remote {raw:?}: expected <target>=\"<command>\""),
619 }
620}
621
622#[cfg(not(feature = "net"))]
624fn check_no_net_remotes(remotes: &[(String, String)]) -> Result<()> {
625 if !remotes.is_empty() {
626 bail!("--remote requires the `net` feature (rebuild with --features net)");
627 }
628 Ok(())
629}
630
631#[cfg(not(feature = "net"))]
635fn check_no_net_endpoints(flags: &EndpointFlags) -> Result<()> {
636 if !flags.listens.is_empty() || !flags.publishes.is_empty() {
637 bail!("--listen/-p require the `net` feature (rebuild with --features net)");
638 }
639 Ok(())
640}
641
642fn read_script(source: &ScriptSource) -> Result<String> {
646 match source {
647 ScriptSource::Path(path) => {
648 let resolver = PathResolver::new(path.root(), path.root())?;
649 resolver
650 .read_to_string(path)
651 .with_context(|| format!("failed to read script at {}", path.display()))
652 }
653 ScriptSource::Stdin => {
654 let mut buf = String::new();
655 io::stdin()
656 .lock()
657 .read_to_string(&mut buf)
658 .context("failed to read script from stdin")?;
659 Ok(buf)
660 }
661 }
662}
663
664fn execute_with_shell_runner<F>(
665 opts: Options,
666 workspace_root: GuardedPath,
667 shell_runner: F,
668 require_tty: bool,
669) -> Result<()>
670where
671 F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
672{
673 #[cfg(windows)]
674 maybe_reexec_shell_to_temp(&opts)?;
675
676 let script = match &opts.script {
680 ScriptSource::Path(_) => read_script(&opts.script)?,
681 ScriptSource::Stdin => {
682 let stdin = io::stdin();
683 if stdin.is_terminal() {
684 if opts.shell {
689 String::new()
690 } else {
691 bail!(
692 "no stdin detected; pass --script <file> or pipe a script into stdin (use --script - if explicit)"
693 );
694 }
695 } else {
696 let mut buf = String::new();
697 stdin
698 .lock()
699 .read_to_string(&mut buf)
700 .context("failed to read script from stdin")?;
701 buf
702 }
703 }
704 };
705
706 let mut final_cwd = workspace_root.clone();
713 let mut snapshot = Arc::new(LazyGuardedTempDir::new());
714 let mut fs: Option<Box<dyn WorkspaceFs>> = None;
715 if !script.trim().is_empty() {
716 #[cfg(feature = "net")]
719 let registry = build_registry(&opts.endpoints)?;
720 #[cfg(not(feature = "net"))]
721 check_no_net_endpoints(&opts.endpoints)?;
722 #[cfg(not(feature = "net"))]
723 check_no_net_remotes(&opts.remotes)?;
724 #[cfg(feature = "net")]
725 report_ephemeral_publishes(&opts.endpoints, ®istry);
726 let steps = parse_cli_script(&script)?;
727 #[cfg(feature = "net")]
731 let inventory = {
732 let inventory = oxdock_net_plugin::RemoteInventory::build(opts.remotes.clone())?;
733 inventory.log_resolutions();
734 inventory.validate_script(&steps)?;
735 inventory
736 };
737 let mut stdin_handle: Option<SharedInput> = None;
742 if let ScriptSource::Path(_) = opts.script {
743 let stdin = io::stdin();
744 if !stdin.is_terminal() {
745 stdin_handle = Some(Arc::new(Mutex::new(stdin)));
751 }
752 }
753
754 let mut io_cfg = ExecIo::new();
755 io_cfg.set_stdin(stdin_handle);
756 #[cfg(feature = "net")]
757 register_remote_runners(&mut io_cfg, &inventory);
758 #[cfg(feature = "net")]
759 let output = run_steps_with_lazy_snapshot_and_modules(
760 &workspace_root,
761 &steps,
762 io_cfg,
763 cli_host_modules_with(Some(®istry)),
764 cli_host_types(),
765 )?;
766 #[cfg(not(feature = "net"))]
767 let output = run_steps_with_lazy_snapshot_and_modules(
768 &workspace_root,
769 &steps,
770 io_cfg,
771 cli_host_modules_with(None),
772 cli_host_types(),
773 )?;
774 final_cwd = output.final_cwd;
775 snapshot = output.snapshot;
776 fs = Some(output.fs);
777 }
778
779 if opts.shell {
781 if require_tty && !has_controlling_tty() {
782 bail!("--shell requires a tty (no controlling tty available)");
783 }
784 match fs.as_ref() {
789 Some(fs) => {
790 if fs.is_snapshot_pending() {
791 snapshot
792 .materialize()
793 .context("failed to create shell temp dir")?;
794 }
795 final_cwd = fs.concretize_cwd(&final_cwd);
796 }
797 None => {
798 snapshot
799 .materialize()
800 .context("failed to create shell temp dir")?;
801 final_cwd = snapshot
802 .get()
803 .cloned()
804 .expect("shell snapshot materialized above");
805 }
806 }
807 return shell_runner(&final_cwd, &workspace_root);
808 }
809
810 Ok(())
811}
812
813#[cfg(test)]
814fn execute_for_test<F>(opts: Options, workspace_root: GuardedPath, shell_runner: F) -> Result<()>
815where
816 F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
817{
818 execute_with_shell_runner(opts, workspace_root, shell_runner, false)
819}
820
821fn has_controlling_tty() -> bool {
822 #[cfg(unix)]
826 {
827 io::stdin().is_terminal() || io::stderr().is_terminal()
828 }
829
830 #[cfg(windows)]
831 {
832 io::stdin().is_terminal() || io::stderr().is_terminal()
833 }
834
835 #[cfg(not(any(unix, windows)))]
836 {
837 false
838 }
839}
840
841#[cfg(windows)]
842fn maybe_reexec_shell_to_temp(opts: &Options) -> Result<()> {
843 if !opts.shell {
846 return Ok(());
847 }
848 if std::env::var(oxdock_env::SHELL_REEXEC).ok().as_deref() == Some("1") {
849 return Ok(());
850 }
851
852 let self_path = std::env::current_exe().context("determine current executable")?;
853 let base_temp =
854 GuardedPath::new_root(std::env::temp_dir().as_path()).context("guard system temp dir")?;
855 let ts = std::time::SystemTime::now()
856 .duration_since(std::time::UNIX_EPOCH)
857 .unwrap_or_default()
858 .as_millis();
859 let temp_file = base_temp
860 .join(&format!("oxdock-shell-{ts}-{}.exe", std::process::id()))
861 .context("construct temp shell path")?;
862
863 let temp_root_guard = temp_file
867 .parent()
868 .ok_or_else(|| anyhow::anyhow!("temp path unexpectedly missing parent"))?;
869 let resolver_temp = PathResolver::new(temp_root_guard.as_path(), temp_root_guard.as_path())?;
870 let dest = temp_file;
871 #[allow(clippy::disallowed_types)]
872 let source = oxdock_fs::UnguardedPath::external(self_path);
873 resolver_temp
874 .copy_file_from_unguarded(&source, &dest)
875 .with_context(|| format!("failed to copy shell runner to {}", dest.display()))?;
876
877 let mut cmd = CommandBuilder::new(dest.as_path());
878 cmd.args(std::env::args_os().skip(1));
879 cmd.env(oxdock_env::SHELL_REEXEC, "1");
880 cmd.spawn()
881 .with_context(|| format!("failed to spawn shell from {}", dest.display()))?;
882
883 std::process::exit(0);
885}
886
887pub fn run_script(workspace_root: &GuardedPath, steps: &[Step]) -> Result<()> {
888 run_steps_with_context(workspace_root, workspace_root, steps)
889}
890
891fn shell_banner(cwd: &GuardedPath, workspace_root: &GuardedPath) -> String {
892 #[cfg(windows)]
893 let cwd_disp = oxdock_fs::command_path(cwd).as_ref().display().to_string();
894 #[cfg(windows)]
895 let workspace_disp = oxdock_fs::command_path(workspace_root)
896 .as_ref()
897 .display()
898 .to_string();
899
900 #[cfg(not(windows))]
901 let cwd_disp = cwd.display().to_string();
902 #[cfg(not(windows))]
903 let workspace_disp = workspace_root.display().to_string();
904
905 let pkg = env::var(oxdock_env::CARGO_PKG_NAME)
906 .unwrap_or_else(|_| oxdock_env::FALLBACK_APP_NAME.to_string());
907 indoc::formatdoc! {"
908 {pkg} shell workspace
909 cwd: {cwd_disp}
910 source: workspace root at {workspace_disp}
911 lifetime: temporary directory created for this shell session; it disappears when you exit
912 creation: temp workspace starts empty unless your script copies files into it
913
914 WARNING: This shell still runs on your host filesystem and is **not** isolated!
915 "}
916}
917
918fn run_shell(cwd: &GuardedPath, workspace_root: &GuardedPath) -> Result<()> {
919 oxdock_process::spawn_interactive_shell(cwd, workspace_root, &shell_banner(cwd, workspace_root))
920}
921
922#[cfg(test)]
925mod tests {
926 use super::*;
927 use indoc::indoc;
928 use oxdock_fs::PathResolver;
929 use std::cell::{Cell, RefCell};
930
931 #[cfg_attr(
932 miri,
933 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
934 )]
935 #[test]
936 fn shell_runner_receives_final_workdir() -> Result<()> {
937 let workspace = GuardedPath::tempdir()?;
938 let workspace_root = workspace.as_guarded_path().clone();
939 let script_path = workspace_root.join("script.ox")?;
940 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
941 let script = indoc! {"
942 WRITE temp.txt 123
943 WORKDIR sub
944 "};
945 resolver.write_file(&script_path, script.as_bytes())?;
946
947 let opts = Options {
948 script: ScriptSource::Path(script_path),
949 shell: true,
950 endpoints: EndpointFlags::default(),
951 remote_serve: false,
952 remotes: Vec::new(),
953 };
954
955 let observed = Cell::new(false);
956 execute_for_test(opts, workspace_root.clone(), |cwd, _| {
957 assert!(
958 cwd.as_path().ends_with("sub"),
959 "final cwd should end in WORKDIR target, got {}",
960 cwd.display()
961 );
962
963 let temp_root = GuardedPath::new_root(cwd.root())
964 .context("construct guard for temp workspace root")?;
965 let sub_dir = temp_root.join("sub")?;
966 assert_eq!(
967 cwd.as_path(),
968 sub_dir.as_path(),
969 "shell runner cwd should match guarded sub dir"
970 );
971 let temp_file = temp_root.join("temp.txt")?;
972 let temp_resolver = PathResolver::new(temp_root.as_path(), temp_root.as_path())?;
973 let contents = temp_resolver.read_to_string(&temp_file)?;
974 assert!(
975 contents.contains("123"),
976 "expected WRITE command to materialize temp file"
977 );
978 observed.set(true);
979 Ok(())
980 })?;
981
982 assert!(
983 observed.into_inner(),
984 "shell runner closure should have been invoked"
985 );
986 Ok(())
987 }
988
989 #[cfg_attr(
990 miri,
991 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
992 )]
993 #[test]
994 fn options_parse_requires_script_path_value() {
995 let workspace = GuardedPath::tempdir().expect("tempdir");
996 let mut args = vec!["--script".to_string()].into_iter();
997 let err = Options::parse(&mut args, workspace.as_guarded_path())
998 .expect_err("expected missing path error");
999 assert!(err.to_string().contains("--script requires a path"));
1000 }
1001
1002 #[cfg_attr(
1003 miri,
1004 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1005 )]
1006 #[test]
1007 fn options_parse_script_path_and_shell() {
1008 let workspace = GuardedPath::tempdir().expect("tempdir");
1009 let workspace_root = workspace.as_guarded_path().clone();
1010 let script_path = workspace_root.join("script.txt").expect("script path");
1011 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1012 .expect("resolver");
1013 resolver
1014 .write_file(&script_path, b"WRITE out.txt hi")
1015 .expect("write script");
1016 let mut args = vec![
1017 "--script".to_string(),
1018 "script.txt".to_string(),
1019 "--shell".to_string(),
1020 ]
1021 .into_iter();
1022 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1023 assert!(opts.shell);
1024 match opts.script {
1025 ScriptSource::Path(path) => assert_eq!(path, script_path),
1026 ScriptSource::Stdin => panic!("expected path script"),
1027 }
1028 }
1029
1030 #[cfg_attr(
1031 miri,
1032 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1033 )]
1034 #[test]
1035 fn options_parse_positional_script_path() {
1036 let workspace = GuardedPath::tempdir().expect("tempdir");
1037 let workspace_root = workspace.as_guarded_path().clone();
1038 let mut args = vec!["script.txt".to_string()].into_iter();
1039 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1040 assert!(!opts.shell);
1041 match opts.script {
1042 ScriptSource::Path(path) => assert_eq!(
1043 path,
1044 workspace_root.join("script.txt").expect("script path")
1045 ),
1046 ScriptSource::Stdin => panic!("expected path script"),
1047 }
1048 }
1049
1050 #[cfg_attr(
1051 miri,
1052 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1053 )]
1054 #[test]
1055 fn options_parse_positional_dash_reads_stdin() {
1056 let workspace = GuardedPath::tempdir().expect("tempdir");
1057 let mut args = vec!["-".to_string()].into_iter();
1058 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1059 assert!(matches!(opts.script, ScriptSource::Stdin));
1060 }
1061
1062 #[cfg_attr(
1063 miri,
1064 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1065 )]
1066 #[test]
1067 fn options_parse_rejects_duplicate_script_sources() {
1068 let workspace = GuardedPath::tempdir().expect("tempdir");
1069 let workspace_root = workspace.as_guarded_path().clone();
1070 let mut args = vec![
1071 "a.ox".to_string(),
1072 "--script".to_string(),
1073 "b.ox".to_string(),
1074 ]
1075 .into_iter();
1076 let err = Options::parse(&mut args, &workspace_root)
1077 .expect_err("expected duplicate script error");
1078 assert!(err.to_string().contains("multiple times"), "{err:?}");
1079
1080 let mut args = vec!["a.ox".to_string(), "b.ox".to_string()].into_iter();
1081 let err = Options::parse(&mut args, &workspace_root)
1082 .expect_err("expected duplicate script error");
1083 assert!(err.to_string().contains("multiple times"), "{err:?}");
1084 }
1085
1086 #[cfg_attr(
1087 miri,
1088 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1089 )]
1090 #[test]
1091 fn options_parse_absolute_script_outside_execution_workspace_loads() {
1092 let workspace = GuardedPath::tempdir().expect("tempdir");
1095 let outside = GuardedPath::tempdir().expect("outside");
1096 let target = outside
1097 .as_guarded_path()
1098 .as_path()
1099 .join("step.ox")
1100 .to_string_lossy()
1101 .into_owned();
1102 let mut args = vec!["--script".to_string(), target.clone()].into_iter();
1103 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1104 match opts.script {
1105 ScriptSource::Path(path) => {
1106 assert_eq!(path.as_path().to_string_lossy(), target);
1107 assert_eq!(path.root(), outside.as_guarded_path().as_path());
1108 }
1109 ScriptSource::Stdin => panic!("absolute script must not parse as stdin"),
1110 }
1111 }
1112
1113 #[cfg_attr(
1114 miri,
1115 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1116 )]
1117 #[test]
1118 fn options_parse_relative_escape_stays_rejected() {
1119 let workspace = GuardedPath::tempdir().expect("tempdir");
1120 let mut args = vec!["--script".to_string(), "../escape.ox".to_string()].into_iter();
1121 let err =
1122 Options::parse(&mut args, workspace.as_guarded_path()).expect_err("escape must fail");
1123 assert!(err.to_string().contains("guard script path"), "{err:?}");
1124 }
1125
1126 #[cfg_attr(
1127 miri,
1128 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1129 )]
1130 #[test]
1131 fn options_parse_rejects_unknown_flags() {
1132 let workspace = GuardedPath::tempdir().expect("tempdir");
1133 let mut args = vec!["--frobnicate".to_string()].into_iter();
1134 let err = Options::parse(&mut args, workspace.as_guarded_path())
1135 .expect_err("expected unknown flag error");
1136 assert!(err.to_string().contains("unexpected flag"), "{err:?}");
1137 }
1138
1139 #[test]
1140 fn usage_describes_positional_script_and_help() {
1141 let text = usage();
1142 assert!(text.contains("Usage: oxdock"), "{text}");
1143 assert!(text.contains("SCRIPT"), "{text}");
1144 assert!(text.contains("--script"), "{text}");
1145 assert!(text.contains("--help"), "{text}");
1146 assert!(text.contains("--offline"), "{text}");
1147 #[cfg(feature = "net")]
1148 {
1149 assert!(text.contains("--listen"), "{text}");
1150 assert!(text.contains("-p <[host:]outer:inner>"), "{text}");
1151 }
1152 #[cfg(not(feature = "net"))]
1153 {
1154 assert!(!text.contains("--listen <addr>"), "{text}");
1155 assert!(!text.contains("-p <[host:]outer:inner>"), "{text}");
1156 assert!(text.contains("require the `net` feature"), "{text}");
1157 }
1158 assert!(text.contains(env!("CARGO_PKG_DESCRIPTION")), "{text}");
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_endpoint_flags() {
1169 let workspace = GuardedPath::tempdir().expect("tempdir");
1172 let mut args = vec![
1173 "--listen".to_string(),
1174 "0.0.0.0:2251".to_string(),
1175 "-p".to_string(),
1176 "2222:demo-proxy".to_string(),
1177 "-p".to_string(),
1178 "0:2252".to_string(),
1179 "-".to_string(),
1180 ]
1181 .into_iter();
1182 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1183 assert_eq!(opts.endpoints.listens.len(), 1);
1184 assert_eq!(opts.endpoints.publishes.len(), 2);
1185 assert!(!opts.endpoints.offline);
1186 assert!(matches!(opts.script, ScriptSource::Stdin));
1187 }
1188
1189 #[cfg_attr(
1190 miri,
1191 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1192 )]
1193 #[test]
1194 fn options_parse_offline_flag() {
1195 let workspace = GuardedPath::tempdir().expect("tempdir");
1196 let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
1197 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1198 assert!(opts.endpoints.offline);
1199 }
1200
1201 #[cfg(feature = "net")]
1202 #[cfg_attr(
1203 miri,
1204 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1205 )]
1206 #[test]
1207 fn options_parse_rejects_bad_endpoint_flags() {
1208 let workspace = GuardedPath::tempdir().expect("tempdir");
1209 for args in [
1210 vec!["--listen"],
1211 vec!["--listen", "0.0.0.0:0"],
1212 vec!["-p"],
1213 vec!["-p", "2222"],
1214 vec!["-p", "2222:0"],
1215 ] {
1216 let mut args = args.into_iter().map(str::to_string);
1217 Options::parse(&mut args, workspace.as_guarded_path())
1218 .expect_err("bad endpoint flag must fail");
1219 }
1220 }
1221
1222 #[cfg_attr(
1223 miri,
1224 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1225 )]
1226 #[test]
1227 fn options_parse_empty_values_hold_token_boundaries() {
1228 let workspace = GuardedPath::tempdir().expect("tempdir");
1232 let mut args = vec![
1233 "--script".to_string(),
1234 "".to_string(),
1235 "--shell".to_string(),
1236 ]
1237 .into_iter();
1238 let err = Options::parse(&mut args, workspace.as_guarded_path())
1239 .expect_err("empty script path must fail");
1240 assert!(
1241 err.to_string().contains("--script requires a path"),
1242 "{err:?}"
1243 );
1244 let mut args = vec!["".to_string(), "-".to_string()].into_iter();
1245 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1246 assert!(matches!(opts.script, ScriptSource::Stdin));
1247 }
1248
1249 #[cfg(feature = "net")]
1250 #[cfg_attr(
1251 miri,
1252 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1253 )]
1254 #[test]
1255 fn options_parse_accepts_equals_and_attached_forms() {
1256 let workspace = GuardedPath::tempdir().expect("tempdir");
1259 let workspace_root = workspace.as_guarded_path().clone();
1260 let mut args = vec![
1261 "--listen=0.0.0.0:2251".to_string(),
1262 "-p2222:demo-proxy".to_string(),
1263 "--".to_string(),
1264 "script.ox".to_string(),
1265 ]
1266 .into_iter();
1267 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1268 assert_eq!(opts.endpoints.listens.len(), 1);
1269 assert_eq!(opts.endpoints.publishes.len(), 1);
1270 match opts.script {
1271 ScriptSource::Path(path) => {
1272 assert_eq!(path, workspace_root.join("script.ox").expect("script path"))
1273 }
1274 ScriptSource::Stdin => panic!("expected path script after --"),
1275 }
1276 }
1277
1278 #[cfg_attr(
1279 miri,
1280 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1281 )]
1282 #[test]
1283 fn options_parse_version_returns_version_without_exiting() {
1284 let workspace = GuardedPath::tempdir().expect("tempdir");
1288 for flag in ["--version", "-V"] {
1289 let mut args = vec![flag.to_string()].into_iter();
1290 let err = Options::parse(&mut args, workspace.as_guarded_path())
1291 .expect_err("version flag must not parse as options");
1292 assert_eq!(err.to_string(), version());
1293 }
1294 }
1295
1296 #[cfg_attr(
1297 miri,
1298 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1299 )]
1300 #[test]
1301 fn options_parse_help_returns_usage_error_without_exiting() {
1302 let workspace = GuardedPath::tempdir().expect("tempdir");
1305 for flag in ["--help", "-h"] {
1306 let mut args = vec![flag.to_string()].into_iter();
1307 let err = Options::parse(&mut args, workspace.as_guarded_path())
1308 .expect_err("help flag must not parse as options");
1309 assert_eq!(err.to_string(), usage());
1310 }
1311 }
1312
1313 #[cfg_attr(
1314 miri,
1315 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1316 )]
1317 #[test]
1318 fn options_parse_rejects_remote_script_with_input_intact() {
1319 let workspace = GuardedPath::tempdir().expect("tempdir");
1320 for args in [
1321 vec!["https://example.com/process.oxfile".to_string()],
1322 vec![
1323 "--script".to_string(),
1324 "https://example.com/process.oxfile".to_string(),
1325 ],
1326 ] {
1327 let err = Options::parse(&mut args.into_iter(), workspace.as_guarded_path())
1328 .expect_err("remote script must not parse as a path");
1329 let rendered = format!("{err:#}");
1330 assert!(
1331 rendered.contains("not a local path")
1332 && rendered.contains("https://example.com/process.oxfile"),
1333 "rejection names the intact input: {rendered}"
1334 );
1335 assert!(
1336 !rendered.contains("https:/example.com"),
1337 "scheme must never come out mangled: {rendered}"
1338 );
1339 }
1340 }
1341
1342 #[test]
1343 fn execute_with_result_runs_script() {
1344 let workspace = GuardedPath::tempdir().expect("tempdir");
1345 let workspace_root = workspace.as_guarded_path().clone();
1346 let script_path = workspace_root.join("script.txt").expect("script path");
1347 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1348 .expect("resolver");
1349 resolver
1350 .write_file(&script_path, b"WRITE out.txt hi")
1351 .expect("write script");
1352 let opts = Options {
1353 script: ScriptSource::Path(script_path),
1354 shell: false,
1355 endpoints: EndpointFlags::default(),
1356 remote_serve: false,
1357 remotes: Vec::new(),
1358 };
1359 let result = execute_with_result(opts, workspace_root).expect("execute");
1360 let snapshot = result
1361 .snapshot_path()
1362 .expect("default WRITE materializes the snapshot");
1363 assert_eq!(snapshot, &result.final_cwd);
1364 let temp_resolver = PathResolver::new(snapshot.root(), snapshot.root()).expect("resolver");
1365 let out = snapshot.join("out.txt").expect("out path");
1366 let contents = temp_resolver.read_to_string(&out).expect("read out");
1367 assert_eq!(contents.trim(), "hi");
1368 }
1369
1370 #[cfg_attr(
1371 miri,
1372 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1373 )]
1374 #[test]
1375 fn execute_with_result_local_only_creates_no_snapshot() {
1376 let workspace = GuardedPath::tempdir().expect("tempdir");
1377 let workspace_root = workspace.as_guarded_path().clone();
1378 let script_path = workspace_root.join("script.txt").expect("script path");
1379 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1380 .expect("resolver");
1381 resolver
1382 .write_file(&script_path, b"WORKSPACE LOCAL\nWRITE out.txt hi")
1383 .expect("write script");
1384 let opts = Options {
1385 script: ScriptSource::Path(script_path),
1386 shell: false,
1387 endpoints: EndpointFlags::default(),
1388 remote_serve: false,
1389 remotes: Vec::new(),
1390 };
1391 let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1392 assert!(
1393 !result.has_snapshot(),
1394 "WORKSPACE LOCAL-only script must not create a snapshot tempdir"
1395 );
1396 assert!(result.snapshot_path().is_none());
1397 let out = workspace_root.join("out.txt").expect("out path");
1399 let contents = resolver.read_to_string(&out).expect("read out");
1400 assert_eq!(contents.trim(), "hi");
1401 assert_eq!(result.final_cwd.root(), workspace_root.as_path());
1403 }
1404
1405 #[cfg_attr(
1406 miri,
1407 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1408 )]
1409 #[test]
1410 fn execute_with_result_empty_script_creates_no_snapshot() {
1411 let workspace = GuardedPath::tempdir().expect("tempdir");
1412 let workspace_root = workspace.as_guarded_path().clone();
1413 let script_path = workspace_root.join("empty.txt").expect("script path");
1414 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1415 .expect("resolver");
1416 resolver
1417 .write_file(&script_path, b"")
1418 .expect("write script");
1419 let opts = Options {
1420 script: ScriptSource::Path(script_path),
1421 shell: false,
1422 endpoints: EndpointFlags::default(),
1423 remote_serve: false,
1424 remotes: Vec::new(),
1425 };
1426 let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1427 assert!(
1428 !result.has_snapshot(),
1429 "empty script must not create a snapshot tempdir"
1430 );
1431 assert_eq!(result.final_cwd, workspace_root);
1432 }
1433
1434 #[cfg_attr(
1435 miri,
1436 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1437 )]
1438 #[test]
1439 fn execute_for_test_invokes_shell_runner() -> Result<()> {
1440 let workspace = GuardedPath::tempdir()?;
1441 let workspace_root = workspace.as_guarded_path().clone();
1442 let script_path = workspace_root.join("empty.txt")?;
1443 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1444 resolver.write_file(&script_path, b"")?;
1445 let opts = Options {
1446 script: ScriptSource::Path(script_path),
1447 shell: true,
1448 endpoints: EndpointFlags::default(),
1449 remote_serve: false,
1450 remotes: Vec::new(),
1451 };
1452 let called = RefCell::new(None::<(String, String)>);
1453 execute_for_test(opts, workspace_root.clone(), |cwd, workspace| {
1454 called.replace(Some((cwd.display(), workspace.display())));
1455 assert!(
1458 cwd.exists(),
1459 "shell cwd must exist on disk, got {}",
1460 cwd.display()
1461 );
1462 Ok(())
1463 })?;
1464 let seen = called.borrow().clone().expect("shell runner called");
1465 assert_eq!(seen.1, workspace_root.display());
1466 Ok(())
1467 }
1468
1469 #[cfg(feature = "ssh")]
1473 #[cfg_attr(
1474 miri,
1475 ignore = "loopback TCP plus threads plus a Tokio runtime; also GuardedPath::tempdir"
1476 )]
1477 #[test]
1478 fn ssh_feature_serves_and_closes() -> Result<()> {
1479 let workspace = GuardedPath::tempdir()?;
1480 let workspace_root = workspace.as_guarded_path().clone();
1481 let script_path = workspace_root.join("ssh-serve.ox")?;
1482 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1483 let script = indoc! {"
1484 IMPORT [STD, SSH]
1485 LET $m: SSH_SERVE_INFO = SSH_SERVE(\"23301\", {username: \"test\", password: \"test123\"})
1486 SSH_CLOSE($m.server)
1487 "};
1488 resolver.write_file(&script_path, script.as_bytes())?;
1489 let opts = Options {
1490 script: ScriptSource::Path(script_path),
1491 shell: false,
1492 endpoints: EndpointFlags::default(),
1493 remote_serve: false,
1494 remotes: Vec::new(),
1495 };
1496 execute_with_result(opts, workspace_root)?;
1497 Ok(())
1498 }
1499
1500 #[cfg(feature = "net")]
1504 #[cfg_attr(
1505 miri,
1506 ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
1507 )]
1508 #[test]
1509 fn net_module_listens_and_closes() -> Result<()> {
1510 let workspace = GuardedPath::tempdir()?;
1511 let workspace_root = workspace.as_guarded_path().clone();
1512 let script_path = workspace_root.join("net-listen.ox")?;
1513 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1514 let script = indoc! {"
1515 IMPORT [STD, NET]
1516 LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
1517 NET_CLOSE($l.listener)
1518 "};
1519 resolver.write_file(&script_path, script.as_bytes())?;
1520 let opts = Options {
1521 script: ScriptSource::Path(script_path),
1522 shell: false,
1523 endpoints: EndpointFlags::default(),
1524 remote_serve: false,
1525 remotes: Vec::new(),
1526 };
1527 execute_with_result(opts, workspace_root)?;
1528 Ok(())
1529 }
1530
1531 #[cfg(feature = "net")]
1535 #[cfg_attr(
1536 miri,
1537 ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
1538 )]
1539 #[test]
1540 fn net_port_addr_observe_publish_mapping() -> Result<()> {
1541 let workspace = GuardedPath::tempdir()?;
1542 let workspace_root = workspace.as_guarded_path().clone();
1543 let script_path = workspace_root.join("net-port.ox")?;
1544 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1545 let script = indoc! {"
1546 IMPORT [STD, NET]
1547 LET $port: INT = NET_PORT(\"routed-svc\")
1548 WRITE port.txt \"{{ $port }}\"
1549 LET $addr: STRING = NET_ADDR(\"routed-svc\")
1550 WRITE addr.txt \"{{ $addr }}\"
1551 "};
1552 resolver.write_file(&script_path, script.as_bytes())?;
1553 let opts = Options {
1554 script: ScriptSource::Path(script_path),
1555 shell: false,
1556 endpoints: EndpointFlags {
1557 publishes: vec![(
1558 std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
1559 "routed-svc".to_string(),
1560 )],
1561 ..EndpointFlags::default()
1562 },
1563 remote_serve: false,
1564 remotes: Vec::new(),
1565 };
1566 let result = execute_with_result(opts, workspace_root)?;
1567 let snapshot = result
1568 .snapshot_path()
1569 .expect("WRITE materializes the snapshot");
1570 let snapshot_resolver = PathResolver::new(snapshot.root(), snapshot.root())?;
1571 let port_path = snapshot.join("port.txt")?;
1572 let port_text = snapshot_resolver.read_to_string(&port_path)?;
1573 let port: u16 = port_text
1574 .trim()
1575 .parse()
1576 .map_err(|_| anyhow::anyhow!("expected a resolved port, got {port_text:?}"))?;
1577 assert_ne!(port, 0, "ephemeral outer port must resolve");
1578 let addr_path = snapshot.join("addr.txt")?;
1579 let addr_text = snapshot_resolver.read_to_string(&addr_path)?;
1580 assert!(
1581 addr_text.trim().ends_with(&format!(":{port}")),
1582 "dial string must carry the resolved port, got {addr_text:?}"
1583 );
1584 Ok(())
1585 }
1586
1587 #[cfg(not(feature = "ssh"))]
1590 #[cfg_attr(
1591 miri,
1592 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1593 )]
1594 #[test]
1595 fn ssh_scripts_rejected_without_feature() -> Result<()> {
1596 let workspace = GuardedPath::tempdir()?;
1597 let workspace_root = workspace.as_guarded_path().clone();
1598 let script_path = workspace_root.join("ssh-serve.ox")?;
1599 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1600 let script = indoc! {"
1601 IMPORT [STD, SSH]
1602 LET $m: SSH_SERVE_INFO = SSH_SERVE(\"23301\", {username: \"test\", password: \"test123\"})
1603 SSH_CLOSE($m.server)
1604 "};
1605 resolver.write_file(&script_path, script.as_bytes())?;
1606 let opts = Options {
1607 script: ScriptSource::Path(script_path),
1608 shell: false,
1609 endpoints: EndpointFlags::default(),
1610 remote_serve: false,
1611 remotes: Vec::new(),
1612 };
1613 let err = match execute_with_result(opts, workspace_root) {
1614 Ok(_) => panic!("SSH names must be unknown without the feature"),
1615 Err(err) => err,
1616 };
1617 assert!(err.to_string().contains("SSH"), "{err}");
1618 Ok(())
1619 }
1620
1621 #[cfg(not(feature = "net"))]
1625 #[cfg_attr(
1626 miri,
1627 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1628 )]
1629 #[test]
1630 fn net_flags_rejected_without_feature() {
1631 let workspace = GuardedPath::tempdir().expect("tempdir");
1632 for args in [
1633 vec!["--listen", "0.0.0.0:2251", "-"],
1634 vec!["-p", "2222:2251", "-"],
1635 vec!["--listen=0.0.0.0:2251", "-"],
1636 ] {
1637 let mut args = args.into_iter().map(str::to_string);
1638 let err = Options::parse(&mut args, workspace.as_guarded_path())
1639 .expect_err("endpoint flag must fail without net");
1640 assert!(
1641 err.to_string().contains("require the `net` feature"),
1642 "{err:?}"
1643 );
1644 }
1645 let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
1646 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1647 assert!(opts.endpoints.offline);
1648 }
1649
1650 #[cfg(not(feature = "net"))]
1653 #[cfg_attr(
1654 miri,
1655 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1656 )]
1657 #[test]
1658 fn net_scripts_rejected_without_feature() -> Result<()> {
1659 let workspace = GuardedPath::tempdir()?;
1660 let workspace_root = workspace.as_guarded_path().clone();
1661 let script_path = workspace_root.join("net-listen.ox")?;
1662 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1663 let script = indoc! {"
1664 IMPORT [STD, NET]
1665 LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
1666 LET $body: STRING = NET_FETCH(\"https://example.com/x\")
1667 NET_CLOSE($l.listener)
1668 "};
1669 resolver.write_file(&script_path, script.as_bytes())?;
1670 let opts = Options {
1671 script: ScriptSource::Path(script_path),
1672 shell: false,
1673 endpoints: EndpointFlags::default(),
1674 remote_serve: false,
1675 remotes: Vec::new(),
1676 };
1677 let err = match execute_with_result(opts, workspace_root) {
1678 Ok(_) => panic!("NET names must be unknown without the feature"),
1679 Err(err) => err,
1680 };
1681 assert!(err.to_string().contains("NET"), "{err}");
1682 Ok(())
1683 }
1684
1685 #[test]
1686 fn process_exit_code_relays_exit_requests() {
1687 let exit = anyhow::Error::new(ExitRequest(3));
1688 assert_eq!(process_exit_code(&exit), 3);
1689 let relayed =
1690 anyhow::Error::new(ExitRequest(3)).context("REMOTE 'prod' exited with code 3");
1691 assert_eq!(process_exit_code(&relayed), 3);
1692 assert_eq!(process_exit_code(&anyhow::anyhow!("boom")), 1);
1693 assert_eq!(
1694 process_exit_code(&anyhow::Error::new(ExitRequest(300))),
1695 255,
1696 "codes clamp to the portable range"
1697 );
1698 assert_eq!(
1699 process_exit_code(&anyhow::Error::new(ExitRequest(-1))),
1700 0,
1701 "negative codes clamp to zero"
1702 );
1703 }
1704}
1705
1706#[cfg(all(test, windows))]
1707mod windows_shell_tests {
1708 use super::*;
1709
1710 #[test]
1711 fn command_path_strips_verbatim_prefix() -> Result<()> {
1712 let temp = GuardedPath::tempdir()?;
1713 let converted = oxdock_fs::command_path(temp.as_guarded_path());
1714 let as_str = converted.as_ref().display().to_string();
1715 assert!(
1716 !as_str.starts_with(r"\\?\"),
1717 "expected non-verbatim path, got {as_str}"
1718 );
1719 Ok(())
1720 }
1721}