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