1use anyhow::{Context, Result, bail};
2use oxdock_fs::{
3 GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, discover_workspace_root,
4 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, build_registry};
26use oxdock_net_plugin::EndpointRegistry;
27
28#[cfg(feature = "ssh")]
35fn cli_host_modules() -> Vec<HostModule<DefaultProcessManager>> {
36 cli_host_modules_with(&Arc::new(EndpointRegistry::new(false)))
37}
38
39#[cfg(not(feature = "ssh"))]
41fn cli_host_modules() -> Vec<HostModule<DefaultProcessManager>> {
42 cli_host_modules_with(&Arc::new(EndpointRegistry::new(false)))
43}
44
45#[cfg(feature = "ssh")]
49fn cli_host_modules_with(
50 registry: &Arc<EndpointRegistry>,
51) -> Vec<HostModule<DefaultProcessManager>> {
52 vec![
53 oxdock_net_plugin::module_with_endpoints(Arc::clone(registry)),
54 oxdock_ssh_plugin::module_with_endpoints(Arc::clone(registry)),
55 ]
56}
57
58#[cfg(not(feature = "ssh"))]
60fn cli_host_modules_with(
61 registry: &Arc<EndpointRegistry>,
62) -> Vec<HostModule<DefaultProcessManager>> {
63 vec![oxdock_net_plugin::module_with_endpoints(Arc::clone(
64 registry,
65 ))]
66}
67
68#[cfg(feature = "ssh")]
70fn cli_host_types() -> Vec<&'static TypeDescriptor> {
71 vec![
72 oxdock_net_plugin::NetListenerTag::descriptor(),
73 oxdock_ssh_plugin::SshServerTag::descriptor(),
74 oxdock_ssh_plugin::SshSessionTag::descriptor(),
75 ]
76}
77
78#[cfg(not(feature = "ssh"))]
80fn cli_host_types() -> Vec<&'static TypeDescriptor> {
81 vec![oxdock_net_plugin::NetListenerTag::descriptor()]
82}
83
84fn parse_cli_script(script: &str) -> Result<Vec<Step>> {
88 let modules = cli_host_modules();
89 if modules.is_empty() {
90 parse_script(script)
91 } else {
92 let mut engine = Engine::new();
93 for module in modules {
94 engine.register_module(module);
95 }
96 parse_script_with_modules(script, engine.module_table())
97 }
98}
99
100pub fn run() -> Result<()> {
101 init_temp_gc();
102 let workspace_root = discover_workspace_root().context("guard workspace root")?;
103
104 let mut args = std::env::args().skip(1);
105 let opts = match Options::parse(&mut args, &workspace_root) {
109 Ok(opts) => opts,
110 Err(err) if err.to_string() == usage() => {
111 print!("{err}");
112 return Ok(());
113 }
114 Err(err) => return Err(err),
115 };
116 execute(opts, workspace_root)
117}
118
119#[derive(Debug, Clone)]
120pub enum ScriptSource {
121 Path(GuardedPath),
122 Stdin,
123}
124
125#[derive(Debug, Clone)]
126pub struct Options {
127 pub script: ScriptSource,
128 pub shell: bool,
129 pub endpoints: EndpointFlags,
130}
131
132impl Options {
133 pub fn parse(
134 args: &mut impl Iterator<Item = String>,
135 workspace_root: &GuardedPath,
136 ) -> Result<Self> {
137 use lexopt::Arg::{Long, Short, Value};
138
139 let mut script: Option<ScriptSource> = None;
140 let mut shell = false;
141 let mut endpoints = EndpointFlags::default();
142 let mut set_script = |source: ScriptSource, origin: &str| -> Result<()> {
143 if script.is_some() {
144 bail!("script given multiple times ({origin})");
145 }
146 script = Some(source);
147 Ok(())
148 };
149 let mut parser = lexopt::Parser::from_args(args.by_ref());
154 while let Some(arg) = parser.next()? {
155 match arg {
156 Long("script") => {
157 let path = value_string(
158 parser
159 .value()
160 .map_err(|_| anyhow::anyhow!("--script requires a path"))?,
161 )?;
162 if path.is_empty() {
163 bail!("--script requires a path");
164 }
165 if path == "-" {
166 set_script(ScriptSource::Stdin, "--script -")?;
167 } else {
168 set_script(
169 ScriptSource::Path(
170 workspace_root
171 .join(&path)
172 .with_context(|| format!("guard script path {path}"))?,
173 ),
174 "--script",
175 )?;
176 }
177 }
178 Long("shell") => {
179 shell = true;
180 }
181 Long("listen") => {
182 let raw = value_string(
183 parser
184 .value()
185 .map_err(|_| anyhow::anyhow!("--listen requires an address"))?,
186 )?;
187 endpoints.listens.push(endpoints::parse_listen_arg(&raw)?);
188 }
189 Short('p') => {
190 let raw = value_string(
191 parser
192 .value()
193 .map_err(|_| anyhow::anyhow!("-p requires outer:inner"))?,
194 )?;
195 endpoints
196 .publishes
197 .push(endpoints::parse_publish_arg(&raw)?);
198 }
199 Long("offline") => {
200 endpoints.offline = true;
201 }
202 Long("help") | Short('h') => {
203 bail!("{}", usage());
204 }
205 Value(value) => {
206 let text = value_string(value)?;
207 if text.is_empty() {
208 continue;
209 }
210 if text == "-" {
211 set_script(ScriptSource::Stdin, "positional `-`")?;
212 } else {
213 set_script(
214 ScriptSource::Path(
215 workspace_root
216 .join(&text)
217 .with_context(|| format!("guard script path {text}"))?,
218 ),
219 "positional argument",
220 )?;
221 }
222 }
223 Long(other) => bail!("unexpected flag: --{other}"),
224 Short(other) => bail!("unexpected flag: -{other}"),
225 }
226 }
227
228 let script = script.unwrap_or(ScriptSource::Stdin);
229
230 Ok(Self {
231 script,
232 shell,
233 endpoints,
234 })
235 }
236}
237
238fn value_string(value: std::ffi::OsString) -> Result<String> {
241 value
242 .into_string()
243 .map_err(|_| anyhow::anyhow!("argument must be UTF-8"))
244}
245
246pub fn usage() -> String {
248 let version = env!("CARGO_PKG_VERSION");
249 let description = env!("CARGO_PKG_DESCRIPTION");
250 indoc::formatdoc! {"
251 oxdock {version} — {description}
252 Usage: oxdock [OPTIONS] [SCRIPT]
253 SCRIPT script file path (same as `--script <file>`); `-` reads stdin
254 --script <file|-> script file under the workspace root, or `-` for stdin
255 --shell run the script, then drop into an interactive shell (requires a TTY)
256 --listen <addr> expose a logical service port ([host:]port, repeatable)
257 -p <[host:]outer:inner> map outer port to an inner service port or name (repeatable; outer 0 is ephemeral)
258 --offline open no sockets (conflicts with --listen/-p)
259 --help, -h print this help and exit
260 With no script given, reads the script from stdin (must be piped unless `--shell`).
261 Scripts declare logical endpoints (a port like 2251); the flags above map them to interfaces.
262 "}
263}
264
265pub fn execute(opts: Options, workspace_root: GuardedPath) -> Result<()> {
266 init_temp_gc();
267 execute_with_shell_runner(opts, workspace_root, run_shell, true)
268}
269
270pub struct ExecutionResult {
278 pub snapshot: Arc<LazyGuardedTempDir>,
282 pub final_cwd: GuardedPath,
285 pub bindings: BTreeMap<String, Value>,
289}
290
291impl ExecutionResult {
292 pub fn has_snapshot(&self) -> bool {
294 self.snapshot.is_materialized()
295 }
296
297 pub fn snapshot_path(&self) -> Option<&GuardedPath> {
299 self.snapshot.get()
300 }
301}
302
303pub fn execute_with_result(opts: Options, workspace_root: GuardedPath) -> Result<ExecutionResult> {
304 if opts.shell {
305 bail!("execute_with_result does not support --shell");
306 }
307
308 let script = read_script(&opts.script, &workspace_root)?;
311
312 let mut final_cwd = workspace_root.clone();
313 let snapshot = Arc::new(LazyGuardedTempDir::new());
314 if !script.trim().is_empty() {
315 let endpoints = build_registry(&opts.endpoints)?;
318 let steps = parse_cli_script(&script)?;
319 let output = run_steps_with_lazy_snapshot_and_modules(
320 &workspace_root,
321 &steps,
322 ExecIo::new(),
323 cli_host_modules_with(&endpoints),
324 cli_host_types(),
325 )?;
326 final_cwd = output.final_cwd;
327 return Ok(ExecutionResult {
328 snapshot: output.snapshot,
329 final_cwd,
330 bindings: output.bindings,
331 });
332 }
333
334 Ok(ExecutionResult {
335 snapshot,
336 final_cwd,
337 bindings: BTreeMap::new(),
338 })
339}
340
341fn report_ephemeral_publishes(flags: &EndpointFlags, registry: &Arc<EndpointRegistry>) {
345 for (outer, inner) in &flags.publishes {
346 if outer.port() != 0 {
347 continue;
348 }
349 match registry.bound_addr(inner) {
350 Some(addr) => eprintln!("oxdock: published {addr} -> {inner}"),
351 None => eprintln!("oxdock: published <unbound> -> {inner}"),
352 }
353 }
354}
355
356fn read_script(source: &ScriptSource, workspace_root: &GuardedPath) -> Result<String> {
358 match source {
359 ScriptSource::Path(path) => {
360 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
361 resolver
362 .read_to_string(path)
363 .with_context(|| format!("failed to read script at {}", path.display()))
364 }
365 ScriptSource::Stdin => {
366 let mut buf = String::new();
367 io::stdin()
368 .lock()
369 .read_to_string(&mut buf)
370 .context("failed to read script from stdin")?;
371 Ok(buf)
372 }
373 }
374}
375
376fn execute_with_shell_runner<F>(
377 opts: Options,
378 workspace_root: GuardedPath,
379 shell_runner: F,
380 require_tty: bool,
381) -> Result<()>
382where
383 F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
384{
385 #[cfg(windows)]
386 maybe_reexec_shell_to_temp(&opts)?;
387
388 let script = match &opts.script {
392 ScriptSource::Path(path) => {
393 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
396 resolver
397 .read_to_string(path)
398 .with_context(|| format!("failed to read script at {}", path.display()))?
399 }
400 ScriptSource::Stdin => {
401 let stdin = io::stdin();
402 if stdin.is_terminal() {
403 if opts.shell {
408 String::new()
409 } else {
410 bail!(
411 "no stdin detected; pass --script <file> or pipe a script into stdin (use --script - if explicit)"
412 );
413 }
414 } else {
415 let mut buf = String::new();
416 stdin
417 .lock()
418 .read_to_string(&mut buf)
419 .context("failed to read script from stdin")?;
420 buf
421 }
422 }
423 };
424
425 let mut final_cwd = workspace_root.clone();
432 let mut snapshot = Arc::new(LazyGuardedTempDir::new());
433 let mut fs: Option<Box<dyn WorkspaceFs>> = None;
434 if !script.trim().is_empty() {
435 let endpoints = build_registry(&opts.endpoints)?;
438 report_ephemeral_publishes(&opts.endpoints, &endpoints);
439 let steps = parse_cli_script(&script)?;
440 let mut stdin_handle: Option<SharedInput> = None;
445 if let ScriptSource::Path(_) = opts.script {
446 let stdin = io::stdin();
447 if !stdin.is_terminal() {
448 stdin_handle = Some(Arc::new(Mutex::new(stdin)));
454 }
455 }
456
457 let mut io_cfg = ExecIo::new();
458 io_cfg.set_stdin(stdin_handle);
459 let output = run_steps_with_lazy_snapshot_and_modules(
460 &workspace_root,
461 &steps,
462 io_cfg,
463 cli_host_modules_with(&endpoints),
464 cli_host_types(),
465 )?;
466 final_cwd = output.final_cwd;
467 snapshot = output.snapshot;
468 fs = Some(output.fs);
469 }
470
471 if opts.shell {
473 if require_tty && !has_controlling_tty() {
474 bail!("--shell requires a tty (no controlling tty available)");
475 }
476 match fs.as_ref() {
481 Some(fs) => {
482 if fs.is_snapshot_pending() {
483 snapshot
484 .materialize()
485 .context("failed to create shell temp dir")?;
486 }
487 final_cwd = fs.concretize_cwd(&final_cwd);
488 }
489 None => {
490 snapshot
491 .materialize()
492 .context("failed to create shell temp dir")?;
493 final_cwd = snapshot
494 .get()
495 .cloned()
496 .expect("shell snapshot materialized above");
497 }
498 }
499 return shell_runner(&final_cwd, &workspace_root);
500 }
501
502 Ok(())
503}
504
505#[cfg(test)]
506fn execute_for_test<F>(opts: Options, workspace_root: GuardedPath, shell_runner: F) -> Result<()>
507where
508 F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
509{
510 execute_with_shell_runner(opts, workspace_root, shell_runner, false)
511}
512
513fn has_controlling_tty() -> bool {
514 #[cfg(unix)]
518 {
519 io::stdin().is_terminal() || io::stderr().is_terminal()
520 }
521
522 #[cfg(windows)]
523 {
524 io::stdin().is_terminal() || io::stderr().is_terminal()
525 }
526
527 #[cfg(not(any(unix, windows)))]
528 {
529 false
530 }
531}
532
533#[cfg(windows)]
534fn maybe_reexec_shell_to_temp(opts: &Options) -> Result<()> {
535 if !opts.shell {
538 return Ok(());
539 }
540 if std::env::var("OXDOCK_SHELL_REEXEC").ok().as_deref() == Some("1") {
541 return Ok(());
542 }
543
544 let self_path = std::env::current_exe().context("determine current executable")?;
545 let base_temp =
546 GuardedPath::new_root(std::env::temp_dir().as_path()).context("guard system temp dir")?;
547 let ts = std::time::SystemTime::now()
548 .duration_since(std::time::UNIX_EPOCH)
549 .unwrap_or_default()
550 .as_millis();
551 let temp_file = base_temp
552 .join(&format!("oxdock-shell-{ts}-{}.exe", std::process::id()))
553 .context("construct temp shell path")?;
554
555 let temp_root_guard = temp_file
559 .parent()
560 .ok_or_else(|| anyhow::anyhow!("temp path unexpectedly missing parent"))?;
561 let resolver_temp = PathResolver::new(temp_root_guard.as_path(), temp_root_guard.as_path())?;
562 let dest = temp_file;
563 #[allow(clippy::disallowed_types)]
564 let source = oxdock_fs::UnguardedPath::external(self_path);
565 resolver_temp
566 .copy_file_from_unguarded(&source, &dest)
567 .with_context(|| format!("failed to copy shell runner to {}", dest.display()))?;
568
569 let mut cmd = CommandBuilder::new(dest.as_path());
570 cmd.args(std::env::args_os().skip(1));
571 cmd.env("OXDOCK_SHELL_REEXEC", "1");
572 cmd.spawn()
573 .with_context(|| format!("failed to spawn shell from {}", dest.display()))?;
574
575 std::process::exit(0);
577}
578
579pub fn run_script(workspace_root: &GuardedPath, steps: &[Step]) -> Result<()> {
580 run_steps_with_context(workspace_root, workspace_root, steps)
581}
582
583fn shell_banner(cwd: &GuardedPath, workspace_root: &GuardedPath) -> String {
584 #[cfg(windows)]
585 let cwd_disp = oxdock_fs::command_path(cwd).as_ref().display().to_string();
586 #[cfg(windows)]
587 let workspace_disp = oxdock_fs::command_path(workspace_root)
588 .as_ref()
589 .display()
590 .to_string();
591
592 #[cfg(not(windows))]
593 let cwd_disp = cwd.display().to_string();
594 #[cfg(not(windows))]
595 let workspace_disp = workspace_root.display().to_string();
596
597 let pkg = env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "oxdock".to_string());
598 indoc::formatdoc! {"
599 {pkg} shell workspace
600 cwd: {cwd_disp}
601 source: workspace root at {workspace_disp}
602 lifetime: temporary directory created for this shell session; it disappears when you exit
603 creation: temp workspace starts empty unless your script copies files into it
604
605 WARNING: This shell still runs on your host filesystem and is **not** isolated!
606 "}
607}
608
609fn run_shell(cwd: &GuardedPath, workspace_root: &GuardedPath) -> Result<()> {
610 oxdock_process::spawn_interactive_shell(cwd, workspace_root, &shell_banner(cwd, workspace_root))
611}
612
613#[cfg(test)]
616mod tests {
617 use super::*;
618 use indoc::indoc;
619 use oxdock_fs::PathResolver;
620 use std::cell::{Cell, RefCell};
621
622 #[cfg_attr(
623 miri,
624 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
625 )]
626 #[test]
627 fn shell_runner_receives_final_workdir() -> Result<()> {
628 let workspace = GuardedPath::tempdir()?;
629 let workspace_root = workspace.as_guarded_path().clone();
630 let script_path = workspace_root.join("script.ox")?;
631 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
632 let script = indoc! {"
633 WRITE temp.txt 123
634 WORKDIR sub
635 "};
636 resolver.write_file(&script_path, script.as_bytes())?;
637
638 let opts = Options {
639 script: ScriptSource::Path(script_path),
640 shell: true,
641 endpoints: EndpointFlags::default(),
642 };
643
644 let observed = Cell::new(false);
645 execute_for_test(opts, workspace_root.clone(), |cwd, _| {
646 assert!(
647 cwd.as_path().ends_with("sub"),
648 "final cwd should end in WORKDIR target, got {}",
649 cwd.display()
650 );
651
652 let temp_root = GuardedPath::new_root(cwd.root())
653 .context("construct guard for temp workspace root")?;
654 let sub_dir = temp_root.join("sub")?;
655 assert_eq!(
656 cwd.as_path(),
657 sub_dir.as_path(),
658 "shell runner cwd should match guarded sub dir"
659 );
660 let temp_file = temp_root.join("temp.txt")?;
661 let temp_resolver = PathResolver::new(temp_root.as_path(), temp_root.as_path())?;
662 let contents = temp_resolver.read_to_string(&temp_file)?;
663 assert!(
664 contents.contains("123"),
665 "expected WRITE command to materialize temp file"
666 );
667 observed.set(true);
668 Ok(())
669 })?;
670
671 assert!(
672 observed.into_inner(),
673 "shell runner closure should have been invoked"
674 );
675 Ok(())
676 }
677
678 #[cfg_attr(
679 miri,
680 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
681 )]
682 #[test]
683 fn options_parse_requires_script_path_value() {
684 let workspace = GuardedPath::tempdir().expect("tempdir");
685 let mut args = vec!["--script".to_string()].into_iter();
686 let err = Options::parse(&mut args, workspace.as_guarded_path())
687 .expect_err("expected missing path error");
688 assert!(err.to_string().contains("--script requires a path"));
689 }
690
691 #[cfg_attr(
692 miri,
693 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
694 )]
695 #[test]
696 fn options_parse_script_path_and_shell() {
697 let workspace = GuardedPath::tempdir().expect("tempdir");
698 let workspace_root = workspace.as_guarded_path().clone();
699 let script_path = workspace_root.join("script.txt").expect("script path");
700 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
701 .expect("resolver");
702 resolver
703 .write_file(&script_path, b"WRITE out.txt hi")
704 .expect("write script");
705 let mut args = vec![
706 "--script".to_string(),
707 "script.txt".to_string(),
708 "--shell".to_string(),
709 ]
710 .into_iter();
711 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
712 assert!(opts.shell);
713 match opts.script {
714 ScriptSource::Path(path) => assert_eq!(path, script_path),
715 ScriptSource::Stdin => panic!("expected path script"),
716 }
717 }
718
719 #[cfg_attr(
720 miri,
721 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
722 )]
723 #[test]
724 fn options_parse_positional_script_path() {
725 let workspace = GuardedPath::tempdir().expect("tempdir");
726 let workspace_root = workspace.as_guarded_path().clone();
727 let mut args = vec!["script.txt".to_string()].into_iter();
728 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
729 assert!(!opts.shell);
730 match opts.script {
731 ScriptSource::Path(path) => assert_eq!(
732 path,
733 workspace_root.join("script.txt").expect("script path")
734 ),
735 ScriptSource::Stdin => panic!("expected path script"),
736 }
737 }
738
739 #[cfg_attr(
740 miri,
741 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
742 )]
743 #[test]
744 fn options_parse_positional_dash_reads_stdin() {
745 let workspace = GuardedPath::tempdir().expect("tempdir");
746 let mut args = vec!["-".to_string()].into_iter();
747 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
748 assert!(matches!(opts.script, ScriptSource::Stdin));
749 }
750
751 #[cfg_attr(
752 miri,
753 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
754 )]
755 #[test]
756 fn options_parse_rejects_duplicate_script_sources() {
757 let workspace = GuardedPath::tempdir().expect("tempdir");
758 let workspace_root = workspace.as_guarded_path().clone();
759 let mut args = vec![
760 "a.ox".to_string(),
761 "--script".to_string(),
762 "b.ox".to_string(),
763 ]
764 .into_iter();
765 let err = Options::parse(&mut args, &workspace_root)
766 .expect_err("expected duplicate script error");
767 assert!(err.to_string().contains("multiple times"), "{err:?}");
768
769 let mut args = vec!["a.ox".to_string(), "b.ox".to_string()].into_iter();
770 let err = Options::parse(&mut args, &workspace_root)
771 .expect_err("expected duplicate script error");
772 assert!(err.to_string().contains("multiple times"), "{err:?}");
773 }
774
775 #[cfg_attr(
776 miri,
777 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
778 )]
779 #[test]
780 fn options_parse_rejects_unknown_flags() {
781 let workspace = GuardedPath::tempdir().expect("tempdir");
782 let mut args = vec!["--frobnicate".to_string()].into_iter();
783 let err = Options::parse(&mut args, workspace.as_guarded_path())
784 .expect_err("expected unknown flag error");
785 assert!(err.to_string().contains("unexpected flag"), "{err:?}");
786 }
787
788 #[test]
789 fn usage_describes_positional_script_and_help() {
790 let text = usage();
791 assert!(text.contains("Usage: oxdock"), "{text}");
792 assert!(text.contains("SCRIPT"), "{text}");
793 assert!(text.contains("--script"), "{text}");
794 assert!(text.contains("--help"), "{text}");
795 assert!(text.contains("--listen"), "{text}");
796 assert!(text.contains("-p <[host:]outer:inner>"), "{text}");
797 assert!(text.contains("--offline"), "{text}");
798 assert!(text.contains(env!("CARGO_PKG_DESCRIPTION")), "{text}");
800 }
801
802 #[cfg_attr(
803 miri,
804 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
805 )]
806 #[test]
807 fn options_parse_endpoint_flags() {
808 let workspace = GuardedPath::tempdir().expect("tempdir");
811 let mut args = vec![
812 "--listen".to_string(),
813 "0.0.0.0:2251".to_string(),
814 "-p".to_string(),
815 "2222:demo-proxy".to_string(),
816 "-p".to_string(),
817 "0:2252".to_string(),
818 "-".to_string(),
819 ]
820 .into_iter();
821 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
822 assert_eq!(opts.endpoints.listens.len(), 1);
823 assert_eq!(opts.endpoints.publishes.len(), 2);
824 assert!(!opts.endpoints.offline);
825 assert!(matches!(opts.script, ScriptSource::Stdin));
826 }
827
828 #[cfg_attr(
829 miri,
830 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
831 )]
832 #[test]
833 fn options_parse_offline_flag() {
834 let workspace = GuardedPath::tempdir().expect("tempdir");
835 let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
836 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
837 assert!(opts.endpoints.offline);
838 }
839
840 #[cfg_attr(
841 miri,
842 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
843 )]
844 #[test]
845 fn options_parse_rejects_bad_endpoint_flags() {
846 let workspace = GuardedPath::tempdir().expect("tempdir");
847 for args in [
848 vec!["--listen"],
849 vec!["--listen", "0.0.0.0:0"],
850 vec!["-p"],
851 vec!["-p", "2222"],
852 vec!["-p", "2222:0"],
853 ] {
854 let mut args = args.into_iter().map(str::to_string);
855 Options::parse(&mut args, workspace.as_guarded_path())
856 .expect_err("bad endpoint flag must fail");
857 }
858 }
859
860 #[cfg_attr(
861 miri,
862 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
863 )]
864 #[test]
865 fn options_parse_empty_values_hold_token_boundaries() {
866 let workspace = GuardedPath::tempdir().expect("tempdir");
870 let mut args = vec![
871 "--script".to_string(),
872 "".to_string(),
873 "--shell".to_string(),
874 ]
875 .into_iter();
876 let err = Options::parse(&mut args, workspace.as_guarded_path())
877 .expect_err("empty script path must fail");
878 assert!(
879 err.to_string().contains("--script requires a path"),
880 "{err:?}"
881 );
882 let mut args = vec!["".to_string(), "-".to_string()].into_iter();
883 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
884 assert!(matches!(opts.script, ScriptSource::Stdin));
885 }
886
887 #[cfg_attr(
888 miri,
889 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
890 )]
891 #[test]
892 fn options_parse_accepts_equals_and_attached_forms() {
893 let workspace = GuardedPath::tempdir().expect("tempdir");
896 let workspace_root = workspace.as_guarded_path().clone();
897 let mut args = vec![
898 "--listen=0.0.0.0:2251".to_string(),
899 "-p2222:demo-proxy".to_string(),
900 "--".to_string(),
901 "script.ox".to_string(),
902 ]
903 .into_iter();
904 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
905 assert_eq!(opts.endpoints.listens.len(), 1);
906 assert_eq!(opts.endpoints.publishes.len(), 1);
907 match opts.script {
908 ScriptSource::Path(path) => {
909 assert_eq!(path, workspace_root.join("script.ox").expect("script path"))
910 }
911 ScriptSource::Stdin => panic!("expected path script after --"),
912 }
913 }
914
915 #[cfg_attr(
916 miri,
917 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
918 )]
919 #[test]
920 fn options_parse_help_returns_usage_error_without_exiting() {
921 let workspace = GuardedPath::tempdir().expect("tempdir");
924 for flag in ["--help", "-h"] {
925 let mut args = vec![flag.to_string()].into_iter();
926 let err = Options::parse(&mut args, workspace.as_guarded_path())
927 .expect_err("help flag must not parse as options");
928 assert_eq!(err.to_string(), usage());
929 }
930 }
931
932 #[cfg_attr(
933 miri,
934 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
935 )]
936 #[test]
937 fn execute_with_result_runs_script() {
938 let workspace = GuardedPath::tempdir().expect("tempdir");
939 let workspace_root = workspace.as_guarded_path().clone();
940 let script_path = workspace_root.join("script.txt").expect("script path");
941 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
942 .expect("resolver");
943 resolver
944 .write_file(&script_path, b"WRITE out.txt hi")
945 .expect("write script");
946 let opts = Options {
947 script: ScriptSource::Path(script_path),
948 shell: false,
949 endpoints: EndpointFlags::default(),
950 };
951 let result = execute_with_result(opts, workspace_root).expect("execute");
952 let snapshot = result
953 .snapshot_path()
954 .expect("default WRITE materializes the snapshot");
955 assert_eq!(snapshot, &result.final_cwd);
956 let temp_resolver = PathResolver::new(snapshot.root(), snapshot.root()).expect("resolver");
957 let out = snapshot.join("out.txt").expect("out path");
958 let contents = temp_resolver.read_to_string(&out).expect("read out");
959 assert_eq!(contents.trim(), "hi");
960 }
961
962 #[cfg_attr(
963 miri,
964 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
965 )]
966 #[test]
967 fn execute_with_result_local_only_creates_no_snapshot() {
968 let workspace = GuardedPath::tempdir().expect("tempdir");
969 let workspace_root = workspace.as_guarded_path().clone();
970 let script_path = workspace_root.join("script.txt").expect("script path");
971 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
972 .expect("resolver");
973 resolver
974 .write_file(&script_path, b"WORKSPACE LOCAL\nWRITE out.txt hi")
975 .expect("write script");
976 let opts = Options {
977 script: ScriptSource::Path(script_path),
978 shell: false,
979 endpoints: EndpointFlags::default(),
980 };
981 let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
982 assert!(
983 !result.has_snapshot(),
984 "WORKSPACE LOCAL-only script must not create a snapshot tempdir"
985 );
986 assert!(result.snapshot_path().is_none());
987 let out = workspace_root.join("out.txt").expect("out path");
989 let contents = resolver.read_to_string(&out).expect("read out");
990 assert_eq!(contents.trim(), "hi");
991 assert_eq!(result.final_cwd.root(), workspace_root.as_path());
993 }
994
995 #[cfg_attr(
996 miri,
997 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
998 )]
999 #[test]
1000 fn execute_with_result_empty_script_creates_no_snapshot() {
1001 let workspace = GuardedPath::tempdir().expect("tempdir");
1002 let workspace_root = workspace.as_guarded_path().clone();
1003 let script_path = workspace_root.join("empty.txt").expect("script path");
1004 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1005 .expect("resolver");
1006 resolver
1007 .write_file(&script_path, b"")
1008 .expect("write script");
1009 let opts = Options {
1010 script: ScriptSource::Path(script_path),
1011 shell: false,
1012 endpoints: EndpointFlags::default(),
1013 };
1014 let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1015 assert!(
1016 !result.has_snapshot(),
1017 "empty script must not create a snapshot tempdir"
1018 );
1019 assert_eq!(result.final_cwd, workspace_root);
1020 }
1021
1022 #[cfg_attr(
1023 miri,
1024 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1025 )]
1026 #[test]
1027 fn execute_for_test_invokes_shell_runner() -> Result<()> {
1028 let workspace = GuardedPath::tempdir()?;
1029 let workspace_root = workspace.as_guarded_path().clone();
1030 let script_path = workspace_root.join("empty.txt")?;
1031 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1032 resolver.write_file(&script_path, b"")?;
1033 let opts = Options {
1034 script: ScriptSource::Path(script_path),
1035 shell: true,
1036 endpoints: EndpointFlags::default(),
1037 };
1038 let called = RefCell::new(None::<(String, String)>);
1039 execute_for_test(opts, workspace_root.clone(), |cwd, workspace| {
1040 called.replace(Some((cwd.display(), workspace.display())));
1041 assert!(
1044 cwd.exists(),
1045 "shell cwd must exist on disk, got {}",
1046 cwd.display()
1047 );
1048 Ok(())
1049 })?;
1050 let seen = called.borrow().clone().expect("shell runner called");
1051 assert_eq!(seen.1, workspace_root.display());
1052 Ok(())
1053 }
1054
1055 #[cfg(feature = "ssh")]
1059 #[cfg_attr(
1060 miri,
1061 ignore = "loopback TCP plus threads plus a Tokio runtime; also GuardedPath::tempdir"
1062 )]
1063 #[test]
1064 fn ssh_feature_serves_and_closes() -> Result<()> {
1065 let workspace = GuardedPath::tempdir()?;
1066 let workspace_root = workspace.as_guarded_path().clone();
1067 let script_path = workspace_root.join("ssh-serve.ox")?;
1068 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1069 let script = indoc! {"
1070 IMPORT [STD, SSH]
1071 LET $m: MAP = SSH_SERVE(\"23301\", {username: \"test\", password: \"test123\"})
1072 SSH_CLOSE($m.server)
1073 "};
1074 resolver.write_file(&script_path, script.as_bytes())?;
1075 let opts = Options {
1076 script: ScriptSource::Path(script_path),
1077 shell: false,
1078 endpoints: EndpointFlags::default(),
1079 };
1080 execute_with_result(opts, workspace_root)?;
1081 Ok(())
1082 }
1083
1084 #[cfg_attr(
1088 miri,
1089 ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
1090 )]
1091 #[test]
1092 fn net_module_listens_and_closes() -> Result<()> {
1093 let workspace = GuardedPath::tempdir()?;
1094 let workspace_root = workspace.as_guarded_path().clone();
1095 let script_path = workspace_root.join("net-listen.ox")?;
1096 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1097 let script = indoc! {"
1098 IMPORT [STD, NET]
1099 LET $l: MAP = NET_LISTEN(\"23501\", {})
1100 NET_CLOSE($l.listener)
1101 "};
1102 resolver.write_file(&script_path, script.as_bytes())?;
1103 let opts = Options {
1104 script: ScriptSource::Path(script_path),
1105 shell: false,
1106 endpoints: EndpointFlags::default(),
1107 };
1108 execute_with_result(opts, workspace_root)?;
1109 Ok(())
1110 }
1111
1112 #[cfg(not(feature = "ssh"))]
1115 #[cfg_attr(
1116 miri,
1117 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1118 )]
1119 #[test]
1120 fn ssh_scripts_rejected_without_feature() -> Result<()> {
1121 let workspace = GuardedPath::tempdir()?;
1122 let workspace_root = workspace.as_guarded_path().clone();
1123 let script_path = workspace_root.join("ssh-serve.ox")?;
1124 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1125 let script = indoc! {"
1126 IMPORT [STD, SSH]
1127 LET $m: MAP = SSH_SERVE(\"23301\", {username: \"test\", password: \"test123\"})
1128 SSH_CLOSE($m.server)
1129 "};
1130 resolver.write_file(&script_path, script.as_bytes())?;
1131 let opts = Options {
1132 script: ScriptSource::Path(script_path),
1133 shell: false,
1134 endpoints: EndpointFlags::default(),
1135 };
1136 let err = match execute_with_result(opts, workspace_root) {
1137 Ok(_) => panic!("SSH names must be unknown without the feature"),
1138 Err(err) => err,
1139 };
1140 assert!(err.to_string().contains("SSH"), "{err}");
1141 Ok(())
1142 }
1143}
1144
1145#[cfg(all(test, windows))]
1146mod windows_shell_tests {
1147 use super::*;
1148
1149 #[test]
1150 fn command_path_strips_verbatim_prefix() -> Result<()> {
1151 let temp = GuardedPath::tempdir()?;
1152 let converted = oxdock_fs::command_path(temp.as_guarded_path());
1153 let as_str = converted.as_ref().display().to_string();
1154 assert!(
1155 !as_str.starts_with(r"\\?\"),
1156 "expected non-verbatim path, got {as_str}"
1157 );
1158 Ok(())
1159 }
1160}