1use anyhow::{Result, bail};
2use oxdock_fs::{
3 GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, discover_workspace_root,
4 env as oxdock_env, init_temp_gc,
5};
6#[cfg(windows)]
7use oxdock_process::CommandBuilder;
8use oxdock_process::{DefaultProcessManager, SharedInput};
9use std::env;
10use std::io::{self, IsTerminal, Read};
11use std::sync::{Arc, Mutex};
12
13use oxdock_core::ExecIo;
14pub use oxdock_core::{
15 Engine, EngineOutput, ExecState, ExitRequest, FuncKind, FuncMeta, FuncParam, HostModule,
16 HostRegistration, NativeFn, OxDockFn, OxDockType, PureFn, PushManifestSink, StepCtx,
17 TypeDescriptor, Value, dry_run_closure, exit_code_of, parse_script, parse_script_with_modules,
18 run_steps, run_steps_with_context, run_steps_with_context_result,
19 run_steps_with_lazy_snapshot_and_modules_and_entry, run_steps_with_manager_with_modules,
20 run_steps_with_manager_with_modules_and_entry, run_steps_without_snapshot,
21};
22pub use oxdock_parser::{Guard, Step, StepKind};
23pub use oxdock_process::shell_program;
24use std::collections::BTreeMap;
25
26mod endpoints;
27pub use endpoints::EndpointFlags;
28mod errors;
29pub use errors::{
30 endpoint_duplicate_inner, endpoint_duplicate_outer, feature_required, offline_conflict, usage,
31};
32#[cfg(feature = "mcp")]
33mod mcp;
34
35#[cfg(feature = "net")]
38pub use endpoints::build_registry;
39#[cfg(feature = "net")]
40use oxdock_net_plugin::EndpointRegistry;
41#[cfg(feature = "net")]
42mod serve;
43
44fn cli_host_modules() -> Vec<HostModule<DefaultProcessManager>> {
53 cli_host_modules_with(None)
54}
55
56#[cfg(feature = "net")]
60fn cli_host_modules_for_serve() -> Vec<HostModule<DefaultProcessManager>> {
61 cli_host_modules_with(None)
62}
63
64#[cfg(feature = "net")]
67fn remote_session_module_hash(entries: &[(String, Vec<String>)]) -> String {
68 oxdock_net_plugin::module_hash(entries)
69}
70
71fn cli_host_modules_with(
78 #[cfg(feature = "net")] registry: Option<&Arc<EndpointRegistry>>,
79 #[cfg(not(feature = "net"))] registry: Option<&Arc<()>>,
80) -> Vec<HostModule<DefaultProcessManager>> {
81 #[cfg(any(feature = "net", feature = "markdown"))]
82 let mut modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
83 #[cfg(not(any(feature = "net", feature = "markdown")))]
84 let modules: Vec<HostModule<DefaultProcessManager>> = Vec::new();
85 #[cfg(feature = "net")]
86 {
87 let net_module = match registry {
88 Some(registry) => oxdock_net_plugin::module_with_endpoints(Arc::clone(registry)),
89 None => oxdock_net_plugin::module(),
90 };
91 modules.push(net_module);
92 #[cfg(feature = "ssh")]
93 {
94 let ssh_module = match registry {
95 Some(registry) => oxdock_ssh_plugin::module_with_endpoints(Arc::clone(registry)),
96 None => oxdock_ssh_plugin::module(),
97 };
98 modules.push(ssh_module);
99 }
100 }
101 #[cfg(feature = "markdown")]
102 modules.push(oxdock_markdown_plugin::module());
103 let _ = registry;
104 modules
105}
106
107fn cli_host_types() -> Vec<&'static TypeDescriptor> {
109 #[cfg(feature = "net")]
110 let net: &[&'static TypeDescriptor] = &[oxdock_net_plugin::NetListenerTag::descriptor()];
111 #[cfg(not(feature = "net"))]
112 let net: &[&'static TypeDescriptor] = &[];
113 #[cfg(feature = "ssh")]
114 let ssh: &[&'static TypeDescriptor] = &[
115 oxdock_ssh_plugin::SshServerTag::descriptor(),
116 oxdock_ssh_plugin::SshSessionTag::descriptor(),
117 ];
118 #[cfg(not(feature = "ssh"))]
119 let ssh: &[&'static TypeDescriptor] = &[];
120 net.iter().chain(ssh.iter()).copied().collect()
121}
122
123fn run_cli_steps(
129 workspace_root: &GuardedPath,
130 steps: &[Step],
131 io: ExecIo,
132 #[cfg(feature = "net")] registry: Option<&Arc<EndpointRegistry>>,
133 #[cfg(not(feature = "net"))] registry: Option<&Arc<()>>,
134 entry_file: Option<GuardedPath>,
135) -> Result<oxdock_core::exec::LazyRunOutput> {
136 run_steps_with_lazy_snapshot_and_modules_and_entry(
137 workspace_root,
138 steps,
139 io,
140 cli_host_modules_with(registry),
141 cli_host_types(),
142 entry_file,
143 )
144}
145
146fn parse_cli_script(script: &str) -> Result<Vec<Step>> {
150 parse_script_with_modules(script, cli_module_table()).map_err(|e| {
151 if let Some(unlinked) = unlinked_module_error(script) {
152 return unlinked;
153 }
154 e
155 })
156}
157
158fn unlinked_modules() -> Vec<(&'static str, &'static str)> {
162 let modules: &[(&'static str, &'static str)] = &[
163 #[cfg(not(feature = "net"))]
164 ("NET", "net"),
165 #[cfg(not(feature = "ssh"))]
166 ("SSH", "ssh"),
167 ];
168 modules.to_vec()
169}
170
171fn unlinked_module_error(script: &str) -> Option<anyhow::Error> {
180 let unlinked = unlinked_modules();
181 if unlinked.is_empty() {
182 return None;
183 }
184 let toks = oxdock_parser::lex_str(script).ok()?;
185 for (module, feature) in unlinked {
186 if imports_module(&toks, module) {
187 return Some(errors::module_unlinked(module, feature));
188 }
189 }
190 None
191}
192
193fn imports_module(toks: &[oxdock_parser::Tok], module: &str) -> bool {
199 use oxdock_parser::{GroupDelim, TokKind};
200 let mut i = 0;
201 while i < toks.len() {
202 match &toks[i].kind {
203 TokKind::Word(w) if w == "IMPORT" => {
204 let mut j = i + 1;
205 while j < toks.len()
206 && matches!(
207 toks[j].kind,
208 TokKind::Newline | TokKind::Comment(_) | TokKind::Semicolon
209 )
210 {
211 j += 1;
212 }
213 if let Some(next) = toks.get(j)
214 && let TokKind::Group {
215 delim: GroupDelim::Bracket,
216 inner,
217 ..
218 } = &next.kind
219 && inner
220 .iter()
221 .any(|t| matches!(&t.kind, TokKind::Word(w) if w == module))
222 {
223 return true;
224 }
225 }
226 TokKind::Group { inner, .. } if imports_module(inner, module) => {
227 return true;
228 }
229 _ => {}
230 }
231 i += 1;
232 }
233 false
234}
235
236fn cli_module_table() -> oxdock_parser::ModuleTable {
239 let modules = cli_host_modules();
240 if modules.is_empty() {
241 return oxdock_core::std_module_table();
242 }
243 let mut engine = Engine::new();
244 for module in modules {
245 engine.register_module(module);
246 }
247 engine.module_table()
248}
249
250fn entry_file_of(script: &ScriptSource) -> Option<GuardedPath> {
253 match script {
254 ScriptSource::Path(path) => Some(path.clone()),
255 ScriptSource::Stdin => None,
256 }
257}
258
259fn print_dry_run(
265 steps: &[Step],
266 script: &ScriptSource,
267 workspace_root: &GuardedPath,
268) -> Result<()> {
269 let table = cli_module_table();
270 let entry_file = entry_file_of(script);
271 {
275 let resolver = PathResolver::new_lazy(workspace_root.clone())?;
276 let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
277 oxdock_core::validate_steps_with_fs_modules_and_entry(
278 fs,
279 steps,
280 cli_host_modules_with(None),
281 cli_host_types(),
282 entry_file.clone(),
283 )?;
284 }
285 let (label, base) = match script {
286 ScriptSource::Path(path) => (
287 path.display(),
288 path.parent().unwrap_or_else(|| workspace_root.clone()),
289 ),
290 ScriptSource::Stdin => ("<stdin>".to_string(), workspace_root.clone()),
291 };
292 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
293 let listing = dry_run_closure(steps, &label, &base, &resolver, &table)?;
294 for item in listing {
295 println!("{}:{} {}", item.file, item.step.line, item.step.kind);
296 }
297 Ok(())
298}
299
300pub fn run() -> Result<()> {
301 init_temp_gc();
302 let workspace_root = discover_workspace_root().map_err(|e| errors::guard_workspace_root(&e))?;
303
304 let mut args = std::env::args().skip(1);
305 let opts = match Options::parse(&mut args, &workspace_root) {
309 Ok(opts) => opts,
310 Err(err) if err.to_string() == version() => {
311 println!("{err}");
312 return Ok(());
313 }
314 Err(err) if err.to_string() == usage() => {
315 print!("{err}");
316 return Ok(());
317 }
318 Err(err) => return Err(err),
319 };
320 #[cfg(feature = "net")]
323 if opts.remote_serve {
324 if opts.shell
325 || !opts.remotes.is_empty()
326 || !matches!(opts.script, ScriptSource::Stdin)
327 || !opts.script_args.is_empty()
328 {
329 return Err(errors::remote_serve_runs_alone());
330 }
331 return serve::serve();
332 }
333 #[cfg(not(feature = "net"))]
334 if opts.remote_serve {
335 return Err(errors::feature_required("--remote-serve", "net"));
336 }
337 if opts.mcp {
340 #[cfg(feature = "mcp")]
341 {
342 if opts.shell || opts.remote_serve || !opts.remotes.is_empty() {
343 return Err(errors::mcp_runs_alone(&[
344 "--shell",
345 "--remote-serve",
346 "--remote",
347 ]));
348 }
349 if !opts.endpoints.listens.is_empty() || !opts.endpoints.publishes.is_empty() {
350 return Err(errors::mcp_runs_alone(&["--listen/-p"]));
351 }
352 if opts.dry_run {
353 return Err(errors::mcp_runs_alone(&["--dry-run"]));
354 }
355 if !opts.script_args.is_empty() {
356 return Err(errors::mcp_runs_alone(&["script args"]));
357 }
358 return mcp::serve_mcp(opts, workspace_root);
359 }
360 #[cfg(not(feature = "mcp"))]
361 {
362 return Err(errors::feature_required("--mcp", "mcp"));
363 }
364 }
365 execute(opts, workspace_root)
366}
367
368pub fn process_exit_code(err: &anyhow::Error) -> i32 {
372 exit_code_of(err)
373 .map(|code| code.clamp(0, 255) as i32)
374 .unwrap_or(1)
375}
376
377#[derive(Debug, Clone)]
378pub enum ScriptSource {
379 Path(GuardedPath),
380 Stdin,
381}
382
383fn reject_url_script(text: &str) -> Result<()> {
387 if text.contains("://") {
388 return Err(errors::script_not_local(text));
389 }
390 Ok(())
391}
392
393#[derive(Debug, Clone)]
394pub struct Options {
395 pub script: ScriptSource,
396 pub shell: bool,
397 pub dry_run: bool,
400 pub endpoints: EndpointFlags,
401 pub remote_serve: bool,
402 pub mcp: bool,
405 pub remotes: Vec<(String, String)>,
408 pub script_args: Vec<String>,
413}
414
415impl Options {
416 pub fn parse(
417 args: &mut impl Iterator<Item = String>,
418 workspace_root: &GuardedPath,
419 ) -> Result<Self> {
420 use lexopt::Arg::{Long, Short, Value};
421
422 let mut script: Option<ScriptSource> = None;
423 let mut shell = false;
424 let mut dry_run = false;
425 let mut endpoints = EndpointFlags::default();
426 let mut remote_serve = false;
427 let mut mcp = false;
428 #[cfg_attr(not(feature = "net"), allow(unused_mut))]
430 let mut remotes: Vec<(String, String)> = Vec::new();
431 let mut script_args: Vec<String> = Vec::new();
432 let drain_tail =
441 |parser: &mut lexopt::Parser, strip_leading: bool| -> Result<Vec<String>> {
442 let mut raw = parser.raw_args().map_err(|e| errors::arg_lex_error(&e))?;
443 let Some(first_os) = raw.next() else {
444 return Ok(Vec::new());
445 };
446 let first = value_string(first_os)?;
447 if strip_leading && first == "--" {
448 raw.map(value_string).collect()
449 } else {
450 std::iter::once(Ok(first))
451 .chain(raw.map(value_string))
452 .collect()
453 }
454 };
455 let mut parser = lexopt::Parser::from_args(args.by_ref());
460 while let Some(arg) = parser.next()? {
461 match arg {
462 Long("script") => {
463 let path = value_string(
464 parser
465 .value()
466 .map_err(|_| errors::script_flag_needs_path())?,
467 )?;
468 if path.is_empty() {
469 return Err(errors::script_flag_needs_path());
470 }
471 if path == "-" {
472 script = Some(ScriptSource::Stdin);
473 } else {
474 reject_url_script(&path)?;
475 script = Some(ScriptSource::Path(
476 workspace_root
477 .join_script(&path)
478 .map_err(|e| errors::guard_script_path(&path, &e))?,
479 ));
480 }
481 script_args = drain_tail(&mut parser, true)?;
484 break;
485 }
486 Long("shell") => {
487 shell = true;
488 }
489 Long("dry-run") => {
490 dry_run = true;
491 }
492 Long("listen") => {
493 let raw = value_string(
494 parser
495 .value()
496 .map_err(|_| errors::listen_requires_address())?,
497 )?;
498 #[cfg(not(feature = "net"))]
499 {
500 let _ = endpoints::parse_listen_arg(&raw);
504 return Err(errors::feature_required("--listen/-p", "net"));
505 }
506 #[cfg(feature = "net")]
507 endpoints.listens.push(endpoints::parse_listen_arg(&raw)?);
508 }
509 Short('p') => {
510 let raw = value_string(
511 parser
512 .value()
513 .map_err(|_| errors::publish_requires_shape(""))?,
514 )?;
515 #[cfg(not(feature = "net"))]
516 {
517 let _ = endpoints::parse_publish_arg(&raw);
521 return Err(errors::feature_required("--listen/-p", "net"));
522 }
523 #[cfg(feature = "net")]
524 endpoints
525 .publishes
526 .push(endpoints::parse_publish_arg(&raw)?);
527 }
528 Long("offline") => {
529 endpoints.offline = true;
530 }
531 Long("remote-serve") => {
532 remote_serve = true;
533 }
534 Long("mcp") => {
535 mcp = true;
536 }
537 Long("remote") => {
538 let raw = value_string(
539 parser
540 .value()
541 .map_err(|_| errors::remote_requires_value())?,
542 )?;
543 #[cfg(not(feature = "net"))]
544 {
545 let _ = oxdock_net_plugin_stub_parse_remote(&raw);
548 return Err(errors::feature_required("--remote", "net"));
549 }
550 #[cfg(feature = "net")]
551 remotes.push(oxdock_net_plugin::parse_remote_arg(&raw)?);
552 }
553 Long("help") | Short('h') => {
554 bail!("{}", usage());
555 }
556 Long("version") | Short('V') | Short('v') => {
557 bail!("{}", version());
558 }
559 Value(value) => {
560 let text = value_string(value)?;
561 if text.is_empty() {
562 continue;
563 }
564 if text == "--" {
565 script = Some(ScriptSource::Stdin);
569 script_args = drain_tail(&mut parser, false)?;
570 break;
571 }
572 if text == "-" {
573 script = Some(ScriptSource::Stdin);
574 script_args = drain_tail(&mut parser, true)?;
575 break;
576 }
577 if text.starts_with('-') {
578 script = Some(ScriptSource::Stdin);
585 let mut tail = drain_tail(&mut parser, false)?;
586 tail.insert(0, text);
587 script_args = tail;
588 break;
589 }
590 reject_url_script(&text)?;
591 script = Some(ScriptSource::Path(
592 workspace_root
593 .join_script(&text)
594 .map_err(|e| errors::guard_script_path(&text, &e))?,
595 ));
596 script_args = drain_tail(&mut parser, true)?;
597 break;
598 }
599 Long(other) => return Err(errors::unexpected_flag(other, true)),
600 Short(other) => return Err(errors::unexpected_flag(&other.to_string(), false)),
601 }
602 }
603
604 let script = script.unwrap_or(ScriptSource::Stdin);
605
606 Ok(Self {
607 script,
608 shell,
609 dry_run,
610 endpoints,
611 remote_serve,
612 mcp,
613 remotes,
614 script_args,
615 })
616 }
617}
618
619fn value_string(value: std::ffi::OsString) -> Result<String> {
622 value.into_string().map_err(|_| errors::arg_not_utf8())
623}
624
625pub fn version() -> String {
627 format!("oxdock {}", env!("CARGO_PKG_VERSION"))
628}
629
630pub fn execute(opts: Options, workspace_root: GuardedPath) -> Result<()> {
631 init_temp_gc();
632 execute_with_shell_runner(opts, workspace_root, run_shell, true)
633}
634
635pub struct ExecutionResult {
643 pub snapshot: Arc<LazyGuardedTempDir>,
647 pub final_cwd: GuardedPath,
650 pub bindings: BTreeMap<String, Value>,
654}
655
656impl ExecutionResult {
657 pub fn has_snapshot(&self) -> bool {
659 self.snapshot.is_materialized()
660 }
661
662 pub fn snapshot_path(&self) -> Option<&GuardedPath> {
664 self.snapshot.get()
665 }
666}
667
668pub fn execute_with_result(opts: Options, workspace_root: GuardedPath) -> Result<ExecutionResult> {
669 if opts.shell {
670 return Err(errors::shell_unsupported_in_result());
671 }
672
673 let script = read_script(&opts.script)?;
676
677 let mut final_cwd = workspace_root.clone();
678 let snapshot = Arc::new(LazyGuardedTempDir::new());
679 if !script.trim().is_empty() {
680 let steps = parse_cli_script(&script)?;
681 if opts.dry_run {
684 print_dry_run(&steps, &opts.script, &workspace_root)?;
685 return Ok(ExecutionResult {
686 snapshot,
687 final_cwd,
688 bindings: BTreeMap::new(),
689 });
690 }
691 #[cfg(feature = "net")]
694 let registry = build_registry(&opts.endpoints)?;
695 #[cfg(not(feature = "net"))]
696 check_no_net_endpoints(&opts.endpoints)?;
697 #[cfg(not(feature = "net"))]
698 check_no_net_remotes(&opts.remotes)?;
699 #[cfg(feature = "net")]
703 let inventory = {
704 let pairs = opts.remotes.clone();
705 let inventory = oxdock_net_plugin::RemoteInventory::build(pairs)?;
706 inventory.log_resolutions();
707 inventory.validate_script(&steps)?;
708 inventory
709 };
710 let entry_file = entry_file_of(&opts.script);
711 #[cfg(feature = "net")]
712 let io_cfg = {
713 let mut io_cfg = ExecIo::new();
714 io_cfg.set_script_args(opts.script_args.clone());
715 register_remote_runners(&mut io_cfg, &inventory);
716 io_cfg
717 };
718 #[cfg(not(feature = "net"))]
719 let io_cfg = {
720 let mut io_cfg = ExecIo::new();
721 io_cfg.set_script_args(opts.script_args.clone());
722 io_cfg
723 };
724 #[cfg(feature = "net")]
725 let output = run_cli_steps(&workspace_root, &steps, io_cfg, Some(®istry), entry_file)?;
726 #[cfg(not(feature = "net"))]
727 let output = run_cli_steps(&workspace_root, &steps, io_cfg, None, entry_file)?;
728 final_cwd = output.final_cwd;
729 return Ok(ExecutionResult {
730 snapshot: output.snapshot,
731 final_cwd,
732 bindings: output.bindings,
733 });
734 }
735
736 Ok(ExecutionResult {
737 snapshot,
738 final_cwd,
739 bindings: BTreeMap::new(),
740 })
741}
742
743#[cfg(feature = "net")]
748fn register_remote_runners(io: &mut ExecIo, inventory: &oxdock_net_plugin::RemoteInventory) {
749 use std::sync::Arc;
750 let entries = surface_entries();
751 let module_hash = oxdock_net_plugin::module_hash(&entries);
752 let modules: Vec<String> = entries.iter().map(|(name, _)| name.clone()).collect();
753 for target in inventory.targets() {
754 let Some(argv) = inventory.argv(&target) else {
755 continue;
756 };
757 let config = oxdock_net_plugin::SessionConfig {
758 argv: argv.to_vec(),
759 oxdock_version: env!("CARGO_PKG_VERSION").to_string(),
760 modules: modules.clone(),
761 module_hash: module_hash.clone(),
762 };
763 io.set_remote_runner_for_target(
764 target,
765 Arc::new(oxdock_net_plugin::StdioSession::new(config)),
766 );
767 }
768}
769
770#[cfg(feature = "net")]
773fn surface_entries() -> Vec<(String, Vec<String>)> {
774 let mut engine = Engine::new();
775 for module in cli_host_modules() {
776 engine.register_module(module);
777 }
778 let table = engine.module_table();
779 let mut entries: Vec<(String, Vec<String>)> = table
780 .modules
781 .into_iter()
782 .map(|(name, module_funcs)| {
783 let mut func_names: Vec<String> = module_funcs
784 .map(|surface| surface.func_names.into_iter().collect())
785 .unwrap_or_default();
786 func_names.sort();
787 (name, func_names)
788 })
789 .collect();
790 entries.sort();
791 entries
792}
793#[cfg(feature = "net")]
794fn report_ephemeral_publishes(flags: &EndpointFlags, registry: &Arc<EndpointRegistry>) {
795 use oxdock_net_plugin::{EndpointKey, Protocol, parse_endpoint_ref};
796 for (outer, inner) in &flags.publishes {
797 if outer.port() != 0 {
798 continue;
799 }
800 let Ok((protocol, endpoint)) = parse_endpoint_ref(inner, "-p") else {
801 continue;
802 };
803 let key = EndpointKey {
804 protocol: protocol.unwrap_or(Protocol::Tcp),
805 endpoint,
806 };
807 match registry.resolve_endpoint(&key) {
808 Ok(addr) => eprintln!("oxdock: published {addr} -> {inner}"),
809 Err(_) => eprintln!("oxdock: published <unbound> -> {inner}"),
810 }
811 }
812}
813
814#[cfg(not(feature = "net"))]
817fn oxdock_net_plugin_stub_parse_remote(raw: &str) -> Result<(String, String)> {
818 match raw.split_once('=') {
821 Some((target, command)) if !target.trim().is_empty() && !command.trim().is_empty() => {
822 Ok((target.trim().to_string(), command.to_string()))
823 }
824 _ => Err(errors::remote_requires_shape(raw)),
825 }
826}
827
828#[cfg(not(feature = "net"))]
830fn check_no_net_remotes(remotes: &[(String, String)]) -> Result<()> {
831 if !remotes.is_empty() {
832 return Err(errors::feature_required("--remote", "net"));
833 }
834 Ok(())
835}
836
837#[cfg(not(feature = "net"))]
841fn check_no_net_endpoints(flags: &EndpointFlags) -> Result<()> {
842 if !flags.listens.is_empty() || !flags.publishes.is_empty() {
843 return Err(errors::feature_required("--listen/-p", "net"));
844 }
845 Ok(())
846}
847
848fn read_script(source: &ScriptSource) -> Result<String> {
852 match source {
853 ScriptSource::Path(path) => {
854 let resolver = PathResolver::new(path.root(), path.root())?;
855 resolver
856 .read_to_string(path)
857 .map_err(|e| errors::read_script_at(&path.display().to_string(), &e))
858 }
859 ScriptSource::Stdin => {
860 let mut buf = String::new();
861 io::stdin()
862 .lock()
863 .read_to_string(&mut buf)
864 .map_err(|e| errors::read_script_stdin(&anyhow::Error::from(e)))?;
865 Ok(buf)
866 }
867 }
868}
869
870fn execute_with_shell_runner<F>(
871 opts: Options,
872 workspace_root: GuardedPath,
873 shell_runner: F,
874 require_tty: bool,
875) -> Result<()>
876where
877 F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
878{
879 #[cfg(windows)]
880 maybe_reexec_shell_to_temp(&opts)?;
881
882 let script = match &opts.script {
886 ScriptSource::Path(_) => read_script(&opts.script)?,
887 ScriptSource::Stdin => {
888 let stdin = io::stdin();
889 if stdin.is_terminal() {
890 if opts.shell {
895 String::new()
896 } else {
897 return Err(errors::script_stdin_missing());
898 }
899 } else {
900 let mut buf = String::new();
901 stdin
902 .lock()
903 .read_to_string(&mut buf)
904 .map_err(|e| errors::read_script_stdin(&anyhow::Error::from(e)))?;
905 buf
906 }
907 }
908 };
909
910 let mut final_cwd = workspace_root.clone();
917 let mut snapshot = Arc::new(LazyGuardedTempDir::new());
918 let mut fs: Option<Box<dyn WorkspaceFs>> = None;
919 if !script.trim().is_empty() {
920 let steps = parse_cli_script(&script)?;
921 if opts.dry_run {
924 print_dry_run(&steps, &opts.script, &workspace_root)?;
925 return Ok(());
926 }
927 #[cfg(feature = "net")]
930 let registry = build_registry(&opts.endpoints)?;
931 #[cfg(not(feature = "net"))]
932 check_no_net_endpoints(&opts.endpoints)?;
933 #[cfg(not(feature = "net"))]
934 check_no_net_remotes(&opts.remotes)?;
935 #[cfg(feature = "net")]
936 report_ephemeral_publishes(&opts.endpoints, ®istry);
937 #[cfg(feature = "net")]
941 let inventory = {
942 let inventory = oxdock_net_plugin::RemoteInventory::build(opts.remotes.clone())?;
943 inventory.log_resolutions();
944 inventory.validate_script(&steps)?;
945 inventory
946 };
947 let mut stdin_handle: Option<SharedInput> = None;
952 if let ScriptSource::Path(_) = opts.script {
953 let stdin = io::stdin();
954 if !stdin.is_terminal() {
955 stdin_handle = Some(Arc::new(Mutex::new(stdin)));
961 }
962 }
963
964 let mut io_cfg = ExecIo::new();
965 io_cfg.set_stdin(stdin_handle);
966 io_cfg.set_script_args(opts.script_args.clone());
967 #[cfg(feature = "net")]
968 register_remote_runners(&mut io_cfg, &inventory);
969 let entry_file = entry_file_of(&opts.script);
970 #[cfg(feature = "net")]
971 let output = run_cli_steps(&workspace_root, &steps, io_cfg, Some(®istry), entry_file)?;
972 #[cfg(not(feature = "net"))]
973 let output = run_cli_steps(&workspace_root, &steps, io_cfg, None, entry_file)?;
974 final_cwd = output.final_cwd;
975 snapshot = output.snapshot;
976 fs = Some(output.fs);
977 }
978
979 if opts.shell {
981 if require_tty && !has_controlling_tty() {
982 return Err(errors::shell_needs_tty());
983 }
984 match fs.as_ref() {
989 Some(fs) => {
990 if fs.is_snapshot_pending() {
991 snapshot
992 .materialize()
993 .map_err(|e| errors::create_shell_temp_dir(&e))?;
994 }
995 final_cwd = fs.concretize_cwd(&final_cwd);
996 }
997 None => {
998 snapshot
999 .materialize()
1000 .map_err(|e| errors::create_shell_temp_dir(&e))?;
1001 final_cwd = snapshot
1002 .get()
1003 .cloned()
1004 .expect("shell snapshot materialized above");
1005 }
1006 }
1007 return shell_runner(&final_cwd, &workspace_root);
1008 }
1009
1010 Ok(())
1011}
1012
1013#[cfg(test)]
1014fn execute_for_test<F>(opts: Options, workspace_root: GuardedPath, shell_runner: F) -> Result<()>
1015where
1016 F: FnOnce(&GuardedPath, &GuardedPath) -> Result<()>,
1017{
1018 execute_with_shell_runner(opts, workspace_root, shell_runner, false)
1019}
1020
1021fn has_controlling_tty() -> bool {
1022 #[cfg(unix)]
1026 {
1027 io::stdin().is_terminal() || io::stderr().is_terminal()
1028 }
1029
1030 #[cfg(windows)]
1031 {
1032 io::stdin().is_terminal() || io::stderr().is_terminal()
1033 }
1034
1035 #[cfg(not(any(unix, windows)))]
1036 {
1037 false
1038 }
1039}
1040
1041#[cfg(windows)]
1042fn maybe_reexec_shell_to_temp(opts: &Options) -> Result<()> {
1043 if !opts.shell {
1046 return Ok(());
1047 }
1048 if std::env::var(oxdock_env::oxdock::SHELL_REEXEC)
1049 .ok()
1050 .as_deref()
1051 == Some("1")
1052 {
1053 return Ok(());
1054 }
1055
1056 let self_path = std::env::current_exe()
1057 .map_err(|e| errors::determine_current_exe(&anyhow::Error::from(e)))?;
1058 let base_temp = GuardedPath::new_root(std::env::temp_dir().as_path())
1059 .map_err(|e| errors::guard_system_temp_dir(&e))?;
1060 let ts = std::time::SystemTime::now()
1061 .duration_since(std::time::UNIX_EPOCH)
1062 .unwrap_or_default()
1063 .as_millis();
1064 let temp_file = base_temp
1065 .join(&format!("oxdock-shell-{ts}-{}.exe", std::process::id()))
1066 .map_err(|e| errors::construct_temp_shell_path(&e))?;
1067
1068 let temp_root_guard = temp_file
1072 .parent()
1073 .ok_or_else(errors::shell_temp_missing_parent)?;
1074 let resolver_temp = PathResolver::new(temp_root_guard.as_path(), temp_root_guard.as_path())?;
1075 let dest = temp_file;
1076 #[allow(clippy::disallowed_types)]
1077 let source = oxdock_fs::UnguardedPath::external(self_path);
1078 resolver_temp
1079 .copy_file_from_unguarded(&source, &dest)
1080 .map_err(|e| errors::copy_shell_runner(&dest.display().to_string(), &e))?;
1081
1082 let mut cmd = CommandBuilder::new(dest.as_path());
1083 cmd.args(std::env::args_os().skip(1));
1084 cmd.env(oxdock_env::oxdock::SHELL_REEXEC, "1");
1085 cmd.spawn().map_err(|e| {
1086 errors::spawn_shell_from(&dest.display().to_string(), &anyhow::Error::from(e))
1087 })?;
1088
1089 std::process::exit(0);
1091}
1092
1093pub fn run_script(workspace_root: &GuardedPath, steps: &[Step]) -> Result<()> {
1094 run_steps_with_context(workspace_root, workspace_root, steps)
1095}
1096
1097fn shell_banner(cwd: &GuardedPath, workspace_root: &GuardedPath) -> String {
1098 #[cfg(windows)]
1099 let cwd_disp = oxdock_fs::command_path(cwd).as_ref().display().to_string();
1100 #[cfg(windows)]
1101 let workspace_disp = oxdock_fs::command_path(workspace_root)
1102 .as_ref()
1103 .display()
1104 .to_string();
1105
1106 #[cfg(not(windows))]
1107 let cwd_disp = cwd.display().to_string();
1108 #[cfg(not(windows))]
1109 let workspace_disp = workspace_root.display().to_string();
1110
1111 let pkg = env::var(oxdock_env::cargo::PKG_NAME)
1112 .unwrap_or_else(|_| oxdock_env::oxdock::FALLBACK_APP_NAME.to_string());
1113 indoc::formatdoc! {"
1114 {pkg} shell workspace
1115 cwd: {cwd_disp}
1116 source: workspace root at {workspace_disp}
1117 lifetime: temporary directory created for this shell session; it disappears when you exit
1118 creation: temp workspace starts empty unless your script copies files into it
1119
1120 WARNING: This shell still runs on your host filesystem and is **not** isolated!
1121 "}
1122}
1123
1124fn run_shell(cwd: &GuardedPath, workspace_root: &GuardedPath) -> Result<()> {
1125 Ok(oxdock_process::spawn_interactive_shell(
1126 cwd,
1127 workspace_root,
1128 &shell_banner(cwd, workspace_root),
1129 )?)
1130}
1131
1132#[cfg(test)]
1135mod tests {
1136 use super::*;
1137 use anyhow::Context;
1138 use indoc::indoc;
1139 use oxdock_fs::PathResolver;
1140 use std::cell::{Cell, RefCell};
1141
1142 #[cfg_attr(
1143 miri,
1144 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1145 )]
1146 #[test]
1147 fn shell_runner_receives_final_workdir() -> Result<()> {
1148 let workspace = GuardedPath::tempdir()?;
1149 let workspace_root = workspace.as_guarded_path().clone();
1150 let script_path = workspace_root.join("script.ox")?;
1151 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1152 let script = indoc! {"
1153 WRITE temp.txt 123
1154 WORKDIR sub
1155 "};
1156 resolver.write_file(&script_path, script.as_bytes())?;
1157
1158 let opts = Options {
1159 script: ScriptSource::Path(script_path),
1160 shell: true,
1161 dry_run: false,
1162 endpoints: EndpointFlags::default(),
1163 remote_serve: false,
1164 mcp: false,
1165 remotes: Vec::new(),
1166 script_args: Vec::new(),
1167 };
1168
1169 let observed = Cell::new(false);
1170 execute_for_test(opts, workspace_root.clone(), |cwd, _| {
1171 assert!(
1172 cwd.as_path().ends_with("sub"),
1173 "final cwd should end in WORKDIR target, got {}",
1174 cwd.display()
1175 );
1176
1177 let temp_root = GuardedPath::new_root(cwd.root())
1178 .context("construct guard for temp workspace root")?;
1179 let sub_dir = temp_root.join("sub")?;
1180 assert_eq!(
1181 cwd.as_path(),
1182 sub_dir.as_path(),
1183 "shell runner cwd should match guarded sub dir"
1184 );
1185 let temp_file = temp_root.join("temp.txt")?;
1186 let temp_resolver = PathResolver::new(temp_root.as_path(), temp_root.as_path())?;
1187 let contents = temp_resolver.read_to_string(&temp_file)?;
1188 assert!(
1189 contents.contains("123"),
1190 "expected WRITE command to materialize temp file"
1191 );
1192 observed.set(true);
1193 Ok(())
1194 })?;
1195
1196 assert!(
1197 observed.into_inner(),
1198 "shell runner closure should have been invoked"
1199 );
1200 Ok(())
1201 }
1202
1203 #[cfg_attr(
1204 miri,
1205 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1206 )]
1207 #[test]
1208 fn options_parse_requires_script_path_value() {
1209 let workspace = GuardedPath::tempdir().expect("tempdir");
1210 let mut args = vec!["--script".to_string()].into_iter();
1211 let err = Options::parse(&mut args, workspace.as_guarded_path())
1212 .expect_err("expected missing path error");
1213 assert!(err.to_string().contains("--script requires a path"));
1214 }
1215
1216 #[cfg_attr(
1217 miri,
1218 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1219 )]
1220 #[test]
1221 fn options_parse_script_flag_takes_dash_leading_path() {
1222 let workspace = GuardedPath::tempdir().expect("tempdir");
1225 let workspace_root = workspace.as_guarded_path().clone();
1226 let mut args = vec!["--script".to_string(), "--weird.ox".to_string()].into_iter();
1227 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1228 match opts.script {
1229 ScriptSource::Path(path) => assert_eq!(
1230 path,
1231 workspace_root.join("--weird.ox").expect("script path")
1232 ),
1233 ScriptSource::Stdin => panic!("expected path script"),
1234 }
1235 assert!(opts.script_args.is_empty());
1236 }
1237
1238 #[cfg_attr(
1239 miri,
1240 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1241 )]
1242 #[test]
1243 fn options_parse_script_path_and_shell() {
1244 let workspace = GuardedPath::tempdir().expect("tempdir");
1245 let workspace_root = workspace.as_guarded_path().clone();
1246 let script_path = workspace_root.join("script.txt").expect("script path");
1247 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1248 .expect("resolver");
1249 resolver
1250 .write_file(&script_path, b"WRITE out.txt hi")
1251 .expect("write script");
1252 let mut args = vec![
1255 "--shell".to_string(),
1256 "--script".to_string(),
1257 "script.txt".to_string(),
1258 ]
1259 .into_iter();
1260 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1261 assert!(opts.shell);
1262 match opts.script {
1263 ScriptSource::Path(path) => assert_eq!(path, script_path),
1264 ScriptSource::Stdin => panic!("expected path script"),
1265 }
1266 assert!(opts.script_args.is_empty());
1267
1268 let mut args = vec![
1269 "--script".to_string(),
1270 "script.txt".to_string(),
1271 "--shell".to_string(),
1272 ]
1273 .into_iter();
1274 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1275 assert!(
1276 !opts.shell,
1277 "--shell after the script is data, not the interpreter flag"
1278 );
1279 assert_eq!(opts.script_args, vec!["--shell"]);
1280 }
1281
1282 #[cfg_attr(
1283 miri,
1284 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1285 )]
1286 #[test]
1287 fn options_parse_mcp_flag() {
1288 let workspace = GuardedPath::tempdir().expect("tempdir");
1289 let workspace_root = workspace.as_guarded_path().clone();
1290 let mut args = vec!["--mcp".to_string(), "tools.oxdock".to_string()].into_iter();
1291 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1292 assert!(opts.mcp);
1293 match opts.script {
1294 ScriptSource::Path(path) => assert_eq!(
1295 path,
1296 workspace_root.join("tools.oxdock").expect("script path")
1297 ),
1298 ScriptSource::Stdin => panic!("expected path script"),
1299 }
1300 }
1301
1302 #[cfg_attr(
1303 miri,
1304 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1305 )]
1306 #[test]
1307 fn options_parse_mcp_defaults_off() {
1308 let workspace = GuardedPath::tempdir().expect("tempdir");
1309 let workspace_root = workspace.as_guarded_path().clone();
1310 let mut args = vec!["script.txt".to_string()].into_iter();
1311 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1312 assert!(!opts.mcp);
1313 }
1314
1315 #[cfg_attr(
1316 miri,
1317 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1318 )]
1319 #[test]
1320 fn options_parse_positional_script_path() {
1321 let workspace = GuardedPath::tempdir().expect("tempdir");
1322 let workspace_root = workspace.as_guarded_path().clone();
1323 let mut args = vec!["script.txt".to_string()].into_iter();
1324 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1325 assert!(!opts.shell);
1326 match opts.script {
1327 ScriptSource::Path(path) => assert_eq!(
1328 path,
1329 workspace_root.join("script.txt").expect("script path")
1330 ),
1331 ScriptSource::Stdin => panic!("expected path script"),
1332 }
1333 }
1334
1335 #[cfg_attr(
1336 miri,
1337 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1338 )]
1339 #[test]
1340 fn options_parse_positional_dash_reads_stdin() {
1341 let workspace = GuardedPath::tempdir().expect("tempdir");
1342 let mut args = vec!["-".to_string()].into_iter();
1343 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1344 assert!(matches!(opts.script, ScriptSource::Stdin));
1345 }
1346
1347 #[cfg_attr(
1348 miri,
1349 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1350 )]
1351 #[test]
1352 fn options_parse_second_positional_is_script_arg() {
1353 let workspace = GuardedPath::tempdir().expect("tempdir");
1357 let workspace_root = workspace.as_guarded_path().clone();
1358 let mut args = vec![
1359 "a.ox".to_string(),
1360 "--script".to_string(),
1361 "b.ox".to_string(),
1362 ]
1363 .into_iter();
1364 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1365 match &opts.script {
1366 ScriptSource::Path(path) => assert_eq!(
1367 path,
1368 &workspace_root.join("a.ox").expect("script path"),
1369 "first positional fixes the script"
1370 ),
1371 ScriptSource::Stdin => panic!("expected path script"),
1372 }
1373 assert_eq!(opts.script_args, vec!["--script", "b.ox"]);
1374
1375 let mut args = vec!["a.ox".to_string(), "b.ox".to_string()].into_iter();
1376 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1377 assert_eq!(opts.script_args, vec!["b.ox"]);
1378 }
1379
1380 #[cfg_attr(
1381 miri,
1382 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1383 )]
1384 #[test]
1385 fn options_parse_absolute_script_outside_execution_workspace_loads() {
1386 let workspace = GuardedPath::tempdir().expect("tempdir");
1389 let outside = GuardedPath::tempdir().expect("outside");
1390 let target = outside
1391 .as_guarded_path()
1392 .as_path()
1393 .join("step.ox")
1394 .to_string_lossy()
1395 .into_owned();
1396 let mut args = vec!["--script".to_string(), target.clone()].into_iter();
1397 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1398 match opts.script {
1399 ScriptSource::Path(path) => {
1400 assert_eq!(path.as_path().to_string_lossy(), target);
1401 assert_eq!(path.root(), outside.as_guarded_path().as_path());
1402 }
1403 ScriptSource::Stdin => panic!("absolute script must not parse as stdin"),
1404 }
1405 }
1406
1407 #[cfg_attr(
1408 miri,
1409 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1410 )]
1411 #[test]
1412 fn options_parse_relative_escape_stays_rejected() {
1413 let workspace = GuardedPath::tempdir().expect("tempdir");
1414 let mut args = vec!["--script".to_string(), "../escape.ox".to_string()].into_iter();
1415 let err =
1416 Options::parse(&mut args, workspace.as_guarded_path()).expect_err("escape must fail");
1417 assert!(err.to_string().contains("guard script path"), "{err:?}");
1418 }
1419
1420 #[cfg_attr(
1421 miri,
1422 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1423 )]
1424 #[test]
1425 fn options_parse_rejects_unknown_flags() {
1426 let workspace = GuardedPath::tempdir().expect("tempdir");
1427 let mut args = vec!["--frobnicate".to_string()].into_iter();
1428 let err = Options::parse(&mut args, workspace.as_guarded_path())
1429 .expect_err("expected unknown flag error");
1430 assert!(err.to_string().contains("unexpected flag"), "{err:?}");
1431 }
1432
1433 #[test]
1434 fn usage_describes_positional_script_and_help() {
1435 let text = usage();
1436 assert!(text.contains("Usage: oxdock"), "{text}");
1437 assert!(text.contains("SCRIPT"), "{text}");
1438 assert!(text.contains("--script"), "{text}");
1439 assert!(text.contains("--help"), "{text}");
1440 assert!(text.contains("--offline"), "{text}");
1441 #[cfg(feature = "net")]
1442 {
1443 assert!(text.contains("--listen"), "{text}");
1444 assert!(text.contains("-p <[host:]outer:inner>"), "{text}");
1445 }
1446 #[cfg(not(feature = "net"))]
1447 {
1448 assert!(!text.contains("--listen <addr>"), "{text}");
1449 assert!(!text.contains("-p <[host:]outer:inner>"), "{text}");
1450 assert!(text.contains("require the `net` feature"), "{text}");
1451 }
1452 assert!(text.contains(env!("CARGO_PKG_DESCRIPTION")), "{text}");
1454 }
1455
1456 #[cfg(feature = "net")]
1457 #[cfg_attr(
1458 miri,
1459 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1460 )]
1461 #[test]
1462 fn options_parse_endpoint_flags() {
1463 let workspace = GuardedPath::tempdir().expect("tempdir");
1466 let mut args = vec![
1467 "--listen".to_string(),
1468 "0.0.0.0:2251".to_string(),
1469 "-p".to_string(),
1470 "2222:demo-proxy".to_string(),
1471 "-p".to_string(),
1472 "0:2252".to_string(),
1473 "-".to_string(),
1474 ]
1475 .into_iter();
1476 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1477 assert_eq!(opts.endpoints.listens.len(), 1);
1478 assert_eq!(opts.endpoints.publishes.len(), 2);
1479 assert!(!opts.endpoints.offline);
1480 assert!(matches!(opts.script, ScriptSource::Stdin));
1481 }
1482
1483 #[cfg_attr(
1484 miri,
1485 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1486 )]
1487 #[test]
1488 fn options_parse_offline_flag() {
1489 let workspace = GuardedPath::tempdir().expect("tempdir");
1490 let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
1491 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1492 assert!(opts.endpoints.offline);
1493 }
1494
1495 #[cfg(feature = "net")]
1496 #[cfg_attr(
1497 miri,
1498 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1499 )]
1500 #[test]
1501 fn options_parse_rejects_bad_endpoint_flags() {
1502 let workspace = GuardedPath::tempdir().expect("tempdir");
1503 for args in [
1504 vec!["--listen"],
1505 vec!["--listen", "0.0.0.0:0"],
1506 vec!["-p"],
1507 vec!["-p", "2222"],
1508 vec!["-p", "2222:0"],
1509 ] {
1510 let mut args = args.into_iter().map(str::to_string);
1511 Options::parse(&mut args, workspace.as_guarded_path())
1512 .expect_err("bad endpoint flag must fail");
1513 }
1514 }
1515
1516 #[cfg_attr(
1517 miri,
1518 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1519 )]
1520 #[test]
1521 fn options_parse_empty_values_hold_token_boundaries() {
1522 let workspace = GuardedPath::tempdir().expect("tempdir");
1526 let mut args = vec![
1527 "--script".to_string(),
1528 "".to_string(),
1529 "--shell".to_string(),
1530 ]
1531 .into_iter();
1532 let err = Options::parse(&mut args, workspace.as_guarded_path())
1533 .expect_err("empty script path must fail");
1534 assert!(
1535 err.to_string().contains("--script requires a path"),
1536 "{err:?}"
1537 );
1538 let mut args = vec!["".to_string(), "-".to_string()].into_iter();
1539 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1540 assert!(matches!(opts.script, ScriptSource::Stdin));
1541 }
1542
1543 #[cfg(feature = "net")]
1544 #[cfg_attr(
1545 miri,
1546 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1547 )]
1548 #[test]
1549 fn options_parse_accepts_equals_and_attached_forms() {
1550 let workspace = GuardedPath::tempdir().expect("tempdir");
1553 let workspace_root = workspace.as_guarded_path().clone();
1554 let mut args = vec![
1555 "--listen=0.0.0.0:2251".to_string(),
1556 "-p2222:demo-proxy".to_string(),
1557 "--".to_string(),
1558 "script.ox".to_string(),
1559 ]
1560 .into_iter();
1561 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1562 assert_eq!(opts.endpoints.listens.len(), 1);
1563 assert_eq!(opts.endpoints.publishes.len(), 1);
1564 match opts.script {
1565 ScriptSource::Path(path) => {
1566 assert_eq!(path, workspace_root.join("script.ox").expect("script path"))
1567 }
1568 ScriptSource::Stdin => panic!("expected path script after --"),
1569 }
1570 assert!(opts.script_args.is_empty());
1571 }
1572
1573 #[cfg_attr(
1574 miri,
1575 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1576 )]
1577 #[test]
1578 fn options_parse_routes_verbatim_tail_to_script_args() {
1579 let workspace = GuardedPath::tempdir().expect("tempdir");
1582 let workspace_root = workspace.as_guarded_path().clone();
1583 let mut args = vec![
1584 "my.ox".to_string(),
1585 "--dry-run".to_string(),
1586 "--listen".to_string(),
1587 "0.0.0.0:2251".to_string(),
1588 ]
1589 .into_iter();
1590 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1591 assert_eq!(
1592 opts.script_args,
1593 vec!["--dry-run", "--listen", "0.0.0.0:2251"]
1594 );
1595
1596 let mut args = vec![
1597 "my.ox".to_string(),
1598 "--".to_string(),
1599 "--dry-run".to_string(),
1600 ]
1601 .into_iter();
1602 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1603 assert_eq!(opts.script_args, vec!["--dry-run"]);
1604
1605 let mut args = vec![
1606 "--script".to_string(),
1607 "my.ox".to_string(),
1608 "--".to_string(),
1609 "a".to_string(),
1610 "--".to_string(),
1611 "b".to_string(),
1612 ]
1613 .into_iter();
1614 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1615 assert_eq!(opts.script_args, vec!["a", "--", "b"]);
1616 }
1617
1618 #[cfg_attr(
1619 miri,
1620 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1621 )]
1622 #[test]
1623 fn options_parse_help_after_script_is_data() {
1624 let workspace = GuardedPath::tempdir().expect("tempdir");
1626 let workspace_root = workspace.as_guarded_path().clone();
1627 let mut args = vec!["my.ox".to_string(), "--help".to_string()].into_iter();
1628 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1629 assert_eq!(opts.script_args, vec!["--help"]);
1630 let mut args = vec!["my.ox".to_string(), "--version".to_string()].into_iter();
1631 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1632 assert_eq!(opts.script_args, vec!["--version"]);
1633 }
1634
1635 #[cfg_attr(
1636 miri,
1637 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1638 )]
1639 #[test]
1640 fn options_parse_dash_leading_after_separator_is_stdin_args() {
1641 let workspace = GuardedPath::tempdir().expect("tempdir");
1644 let workspace_root = workspace.as_guarded_path().clone();
1645 let mut args = vec!["--".to_string(), "--foo".to_string()].into_iter();
1646 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1647 assert!(matches!(opts.script, ScriptSource::Stdin));
1648 assert_eq!(opts.script_args, vec!["--foo"]);
1649
1650 let mut args = vec!["--".to_string(), "script.ox".to_string()].into_iter();
1651 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1652 match opts.script {
1653 ScriptSource::Path(path) => {
1654 assert_eq!(path, workspace_root.join("script.ox").expect("script path"))
1655 }
1656 ScriptSource::Stdin => panic!("expected path script"),
1657 }
1658 assert!(opts.script_args.is_empty());
1659
1660 let mut args = vec!["--".to_string(), "--".to_string(), "a".to_string()].into_iter();
1661 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1662 assert!(matches!(opts.script, ScriptSource::Stdin));
1663 assert_eq!(opts.script_args, vec!["a"]);
1664 }
1665
1666 #[cfg_attr(
1667 miri,
1668 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1669 )]
1670 #[test]
1671 fn options_parse_preserves_inner_separators_in_tail() {
1672 let workspace = GuardedPath::tempdir().expect("tempdir");
1674 let workspace_root = workspace.as_guarded_path().clone();
1675 let mut args = vec![
1676 "--".to_string(),
1677 "--foo".to_string(),
1678 "--".to_string(),
1679 "--bar".to_string(),
1680 ]
1681 .into_iter();
1682 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1683 assert!(matches!(opts.script, ScriptSource::Stdin));
1684 assert_eq!(opts.script_args, vec!["--foo", "--", "--bar"]);
1685
1686 let mut args = vec![
1687 "my.ox".to_string(),
1688 "a".to_string(),
1689 "--".to_string(),
1690 "b".to_string(),
1691 ]
1692 .into_iter();
1693 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1694 assert_eq!(opts.script_args, vec!["a", "--", "b"]);
1695 }
1696
1697 #[cfg_attr(
1698 miri,
1699 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1700 )]
1701 #[test]
1702 fn options_parse_version_returns_version_without_exiting() {
1703 let workspace = GuardedPath::tempdir().expect("tempdir");
1707 for flag in ["--version", "-V", "-v"] {
1708 let mut args = vec![flag.to_string()].into_iter();
1709 let err = Options::parse(&mut args, workspace.as_guarded_path())
1710 .expect_err("version flag must not parse as options");
1711 assert_eq!(err.to_string(), version());
1712 }
1713 }
1714
1715 #[cfg_attr(
1716 miri,
1717 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1718 )]
1719 #[test]
1720 fn options_parse_help_returns_usage_error_without_exiting() {
1721 let workspace = GuardedPath::tempdir().expect("tempdir");
1724 for flag in ["--help", "-h"] {
1725 let mut args = vec![flag.to_string()].into_iter();
1726 let err = Options::parse(&mut args, workspace.as_guarded_path())
1727 .expect_err("help flag must not parse as options");
1728 assert_eq!(err.to_string(), usage());
1729 }
1730 }
1731
1732 #[cfg_attr(
1733 miri,
1734 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1735 )]
1736 #[test]
1737 fn options_parse_rejects_remote_script_with_input_intact() {
1738 let workspace = GuardedPath::tempdir().expect("tempdir");
1739 for args in [
1740 vec!["https://example.com/process.oxfile".to_string()],
1741 vec![
1742 "--script".to_string(),
1743 "https://example.com/process.oxfile".to_string(),
1744 ],
1745 ] {
1746 let err = Options::parse(&mut args.into_iter(), workspace.as_guarded_path())
1747 .expect_err("remote script must not parse as a path");
1748 let rendered = format!("{err:#}");
1749 assert!(
1750 rendered.contains("not a local path")
1751 && rendered.contains("https://example.com/process.oxfile"),
1752 "rejection names the intact input: {rendered}"
1753 );
1754 assert!(
1755 !rendered.contains("https:/example.com"),
1756 "scheme must never come out mangled: {rendered}"
1757 );
1758 }
1759 }
1760
1761 #[test]
1762 fn execute_with_result_runs_script() {
1763 let workspace = GuardedPath::tempdir().expect("tempdir");
1764 let workspace_root = workspace.as_guarded_path().clone();
1765 let script_path = workspace_root.join("script.txt").expect("script path");
1766 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1767 .expect("resolver");
1768 resolver
1769 .write_file(&script_path, b"WRITE out.txt hi")
1770 .expect("write script");
1771 let opts = Options {
1772 script: ScriptSource::Path(script_path),
1773 shell: false,
1774 dry_run: false,
1775 endpoints: EndpointFlags::default(),
1776 remote_serve: false,
1777 mcp: false,
1778 remotes: Vec::new(),
1779 script_args: Vec::new(),
1780 };
1781 let result = execute_with_result(opts, workspace_root).expect("execute");
1782 let snapshot = result
1783 .snapshot_path()
1784 .expect("default WRITE materializes the snapshot");
1785 assert_eq!(snapshot, &result.final_cwd);
1786 let temp_resolver = PathResolver::new(snapshot.root(), snapshot.root()).expect("resolver");
1787 let out = snapshot.join("out.txt").expect("out path");
1788 let contents = temp_resolver.read_to_string(&out).expect("read out");
1789 assert_eq!(contents.trim(), "hi");
1790 }
1791
1792 #[cfg_attr(
1793 miri,
1794 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1795 )]
1796 #[test]
1797 fn execute_with_result_routes_script_args_to_argv() {
1798 let workspace = GuardedPath::tempdir().expect("tempdir");
1801 let workspace_root = workspace.as_guarded_path().clone();
1802 let script_path = workspace_root.join("script.txt").expect("script path");
1803 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1804 .expect("resolver");
1805 let script = indoc! {r#"
1806 IMPORT [STD]
1807 LET $args: LIST<STRING> = ARGV()
1808 LET $n: INT = LEN($args)
1809 ASSERT_EQ $n 2
1810 ASSERT_EQ $args.0 "--dry-run"
1811 ASSERT_EQ $args.1 "serve"
1812 WRITE out.txt "ok"
1813 "#};
1814 resolver
1815 .write_file(&script_path, script.as_bytes())
1816 .expect("write script");
1817 let mut args = vec![
1820 "script.txt".to_string(),
1821 "--".to_string(),
1822 "--dry-run".to_string(),
1823 "serve".to_string(),
1824 ]
1825 .into_iter();
1826 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1827 assert_eq!(opts.script_args, vec!["--dry-run", "serve"]);
1828 let result = execute_with_result(opts, workspace_root).expect("execute");
1829 let snapshot = result
1830 .snapshot_path()
1831 .expect("WRITE materializes the snapshot");
1832 let temp_resolver = PathResolver::new(snapshot.root(), snapshot.root()).expect("resolver");
1833 let out = snapshot.join("out.txt").expect("out path");
1834 assert_eq!(
1835 temp_resolver.read_to_string(&out).expect("read").trim(),
1836 "ok"
1837 );
1838 }
1839
1840 #[cfg_attr(
1841 miri,
1842 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1843 )]
1844 #[test]
1845 fn execute_with_result_local_only_creates_no_snapshot() {
1846 let workspace = GuardedPath::tempdir().expect("tempdir");
1847 let workspace_root = workspace.as_guarded_path().clone();
1848 let script_path = workspace_root.join("script.txt").expect("script path");
1849 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1850 .expect("resolver");
1851 resolver
1852 .write_file(&script_path, b"WORKSPACE LOCAL\nWRITE out.txt hi")
1853 .expect("write script");
1854 let opts = Options {
1855 script: ScriptSource::Path(script_path),
1856 shell: false,
1857 dry_run: false,
1858 endpoints: EndpointFlags::default(),
1859 remote_serve: false,
1860 mcp: false,
1861 remotes: Vec::new(),
1862 script_args: Vec::new(),
1863 };
1864 let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1865 assert!(
1866 !result.has_snapshot(),
1867 "WORKSPACE LOCAL-only script must not create a snapshot tempdir"
1868 );
1869 assert!(result.snapshot_path().is_none());
1870 let out = workspace_root.join("out.txt").expect("out path");
1872 let contents = resolver.read_to_string(&out).expect("read out");
1873 assert_eq!(contents.trim(), "hi");
1874 assert_eq!(result.final_cwd.root(), workspace_root.as_path());
1876 }
1877
1878 #[cfg_attr(
1879 miri,
1880 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1881 )]
1882 #[test]
1883 fn execute_with_result_empty_script_creates_no_snapshot() {
1884 let workspace = GuardedPath::tempdir().expect("tempdir");
1885 let workspace_root = workspace.as_guarded_path().clone();
1886 let script_path = workspace_root.join("empty.txt").expect("script path");
1887 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1888 .expect("resolver");
1889 resolver
1890 .write_file(&script_path, b"")
1891 .expect("write script");
1892 let opts = Options {
1893 script: ScriptSource::Path(script_path),
1894 shell: false,
1895 dry_run: false,
1896 endpoints: EndpointFlags::default(),
1897 remote_serve: false,
1898 mcp: false,
1899 remotes: Vec::new(),
1900 script_args: Vec::new(),
1901 };
1902 let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1903 assert!(
1904 !result.has_snapshot(),
1905 "empty script must not create a snapshot tempdir"
1906 );
1907 assert_eq!(result.final_cwd, workspace_root);
1908 }
1909
1910 #[cfg_attr(
1911 miri,
1912 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1913 )]
1914 #[test]
1915 fn execute_for_test_invokes_shell_runner() -> Result<()> {
1916 let workspace = GuardedPath::tempdir()?;
1917 let workspace_root = workspace.as_guarded_path().clone();
1918 let script_path = workspace_root.join("empty.txt")?;
1919 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1920 resolver.write_file(&script_path, b"")?;
1921 let opts = Options {
1922 script: ScriptSource::Path(script_path),
1923 shell: true,
1924 dry_run: false,
1925 endpoints: EndpointFlags::default(),
1926 remote_serve: false,
1927 mcp: false,
1928 remotes: Vec::new(),
1929 script_args: Vec::new(),
1930 };
1931 let called = RefCell::new(None::<(String, String)>);
1932 execute_for_test(opts, workspace_root.clone(), |cwd, workspace| {
1933 called.replace(Some((cwd.display(), workspace.display())));
1934 assert!(
1937 cwd.exists(),
1938 "shell cwd must exist on disk, got {}",
1939 cwd.display()
1940 );
1941 Ok(())
1942 })?;
1943 let seen = called.borrow().clone().expect("shell runner called");
1944 assert_eq!(seen.1, workspace_root.display());
1945 Ok(())
1946 }
1947
1948 #[cfg(feature = "ssh")]
1952 #[cfg_attr(
1953 miri,
1954 ignore = "loopback TCP plus threads plus a Tokio runtime; also GuardedPath::tempdir"
1955 )]
1956 #[test]
1957 fn ssh_feature_serves_and_closes() -> Result<()> {
1958 let workspace = GuardedPath::tempdir()?;
1959 let workspace_root = workspace.as_guarded_path().clone();
1960 let script_path = workspace_root.join("ssh-serve.ox")?;
1961 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1962 let script = indoc! {"
1963 IMPORT [STD, SSH]
1964 LET $m: SSH_SERVE_INFO = SSH_SERVE(\"cli-ssh-svc\", {username: \"test\", password: \"test123\"})
1965 SSH_CLOSE($m.server)
1966 "};
1967 resolver.write_file(&script_path, script.as_bytes())?;
1968 let opts = Options {
1969 script: ScriptSource::Path(script_path),
1970 shell: false,
1971 dry_run: false,
1972 endpoints: EndpointFlags {
1973 publishes: vec![(
1974 std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
1975 "cli-ssh-svc".to_string(),
1976 )],
1977 ..EndpointFlags::default()
1978 },
1979 remote_serve: false,
1980 mcp: false,
1981 remotes: Vec::new(),
1982 script_args: Vec::new(),
1983 };
1984 execute_with_result(opts, workspace_root)?;
1985 Ok(())
1986 }
1987
1988 #[cfg(feature = "net")]
1992 #[cfg_attr(
1993 miri,
1994 ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
1995 )]
1996 #[test]
1997 fn net_module_listens_and_closes() -> Result<()> {
1998 let workspace = GuardedPath::tempdir()?;
1999 let workspace_root = workspace.as_guarded_path().clone();
2000 let script_path = workspace_root.join("net-listen.ox")?;
2001 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
2002 let script = indoc! {"
2003 IMPORT [STD, NET]
2004 LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
2005 NET_CLOSE($l.listener)
2006 "};
2007 resolver.write_file(&script_path, script.as_bytes())?;
2008 let opts = Options {
2009 script: ScriptSource::Path(script_path),
2010 shell: false,
2011 dry_run: false,
2012 endpoints: EndpointFlags {
2015 publishes: vec![(
2016 std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
2017 "23501".to_string(),
2018 )],
2019 ..EndpointFlags::default()
2020 },
2021 remote_serve: false,
2022 mcp: false,
2023 remotes: Vec::new(),
2024 script_args: Vec::new(),
2025 };
2026 execute_with_result(opts, workspace_root)?;
2027 Ok(())
2028 }
2029
2030 #[cfg(feature = "net")]
2034 #[cfg_attr(
2035 miri,
2036 ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
2037 )]
2038 #[test]
2039 fn net_port_addr_observe_publish_mapping() -> Result<()> {
2040 let workspace = GuardedPath::tempdir()?;
2041 let workspace_root = workspace.as_guarded_path().clone();
2042 let script_path = workspace_root.join("net-port.ox")?;
2043 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
2044 let script = indoc! {"
2045 IMPORT [STD, NET]
2046 LET $port: INT = NET_PORT(\"routed-svc\")
2047 WRITE port.txt \"{{ $port }}\"
2048 LET $addr: STRING = NET_ADDR(\"routed-svc\")
2049 WRITE addr.txt \"{{ $addr }}\"
2050 "};
2051 resolver.write_file(&script_path, script.as_bytes())?;
2052 let opts = Options {
2053 script: ScriptSource::Path(script_path),
2054 shell: false,
2055 dry_run: false,
2056 endpoints: EndpointFlags {
2057 publishes: vec![(
2058 std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
2059 "routed-svc".to_string(),
2060 )],
2061 ..EndpointFlags::default()
2062 },
2063 remote_serve: false,
2064 mcp: false,
2065 remotes: Vec::new(),
2066 script_args: Vec::new(),
2067 };
2068 let result = execute_with_result(opts, workspace_root)?;
2069 let snapshot = result
2070 .snapshot_path()
2071 .expect("WRITE materializes the snapshot");
2072 let snapshot_resolver = PathResolver::new(snapshot.root(), snapshot.root())?;
2073 let port_path = snapshot.join("port.txt")?;
2074 let port_text = snapshot_resolver.read_to_string(&port_path)?;
2075 let port: u16 = port_text
2076 .trim()
2077 .parse()
2078 .map_err(|_| anyhow::anyhow!("expected a resolved port, got {port_text:?}"))?;
2079 assert_ne!(port, 0, "ephemeral outer port must resolve");
2080 let addr_path = snapshot.join("addr.txt")?;
2081 let addr_text = snapshot_resolver.read_to_string(&addr_path)?;
2082 assert!(
2083 addr_text.trim().ends_with(&format!(":{port}")),
2084 "dial string must carry the resolved port, got {addr_text:?}"
2085 );
2086 Ok(())
2087 }
2088
2089 #[cfg(not(feature = "ssh"))]
2092 #[cfg_attr(
2093 miri,
2094 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
2095 )]
2096 #[test]
2097 fn ssh_scripts_rejected_without_feature() -> Result<()> {
2098 let workspace = GuardedPath::tempdir()?;
2099 let workspace_root = workspace.as_guarded_path().clone();
2100 let script_path = workspace_root.join("ssh-serve.ox")?;
2101 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
2102 let script = indoc! {"
2103 IMPORT [STD, SSH]
2104 LET $m: SSH_SERVE_INFO = SSH_SERVE(\"23301\", {username: \"test\", password: \"test123\"})
2105 SSH_CLOSE($m.server)
2106 "};
2107 resolver.write_file(&script_path, script.as_bytes())?;
2108 let opts = Options {
2109 script: ScriptSource::Path(script_path),
2110 shell: false,
2111 dry_run: false,
2112 endpoints: EndpointFlags::default(),
2113 remote_serve: false,
2114 mcp: false,
2115 remotes: Vec::new(),
2116 script_args: Vec::new(),
2117 };
2118 let err = match execute_with_result(opts, workspace_root) {
2119 Ok(_) => panic!("SSH names must be unknown without the feature"),
2120 Err(err) => err,
2121 };
2122 assert!(err.to_string().contains("SSH"), "{err}");
2123 let diag = err
2124 .downcast_ref::<oxdock_diagnostics::Diagnostic>()
2125 .expect("CLI errors stay typed");
2126 assert_eq!(diag.key(), "cli.module_unlinked", "{diag}");
2127 Ok(())
2128 }
2129
2130 #[cfg(not(feature = "net"))]
2134 #[cfg_attr(
2135 miri,
2136 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
2137 )]
2138 #[test]
2139 fn net_flags_rejected_without_feature() {
2140 let workspace = GuardedPath::tempdir().expect("tempdir");
2141 for args in [
2142 vec!["--listen", "0.0.0.0:2251", "-"],
2143 vec!["-p", "2222:2251", "-"],
2144 vec!["--listen=0.0.0.0:2251", "-"],
2145 ] {
2146 let mut args = args.into_iter().map(str::to_string);
2147 let err = Options::parse(&mut args, workspace.as_guarded_path())
2148 .expect_err("endpoint flag must fail without net");
2149 assert!(err.to_string().contains("`net` feature"), "{err:?}");
2150 let diag = err
2152 .downcast_ref::<oxdock_diagnostics::Diagnostic>()
2153 .expect("CLI errors stay typed");
2154 assert_eq!(diag.key(), "cli.feature_required");
2155 }
2156 let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
2157 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
2158 assert!(opts.endpoints.offline);
2159 }
2160
2161 #[cfg(not(feature = "net"))]
2164 #[cfg_attr(
2165 miri,
2166 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
2167 )]
2168 #[test]
2169 fn net_scripts_rejected_without_feature() -> Result<()> {
2170 let workspace = GuardedPath::tempdir()?;
2171 let workspace_root = workspace.as_guarded_path().clone();
2172 let script_path = workspace_root.join("net-listen.ox")?;
2173 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
2174 let script = indoc! {"
2175 IMPORT [STD, NET]
2176 LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
2177 LET $body: STRING = NET_FETCH(\"https://example.com/x\")
2178 NET_CLOSE($l.listener)
2179 "};
2180 resolver.write_file(&script_path, script.as_bytes())?;
2181 let opts = Options {
2182 script: ScriptSource::Path(script_path),
2183 shell: false,
2184 dry_run: false,
2185 endpoints: EndpointFlags::default(),
2186 remote_serve: false,
2187 mcp: false,
2188 remotes: Vec::new(),
2189 script_args: Vec::new(),
2190 };
2191 let err = match execute_with_result(opts, workspace_root) {
2192 Ok(_) => panic!("NET names must be unknown without the feature"),
2193 Err(err) => err,
2194 };
2195 assert!(err.to_string().contains("NET"), "{err}");
2196 let diag = err
2198 .downcast_ref::<oxdock_diagnostics::Diagnostic>()
2199 .expect("CLI errors stay typed");
2200 assert_eq!(diag.key(), "cli.module_unlinked", "{diag}");
2201 Ok(())
2202 }
2203
2204 #[test]
2208 fn imports_module_ignores_comments_strings_and_other_brackets() {
2209 use oxdock_parser::lex_str;
2210 let toks = lex_str("IMPORT [STD, NET]\n").expect("lex");
2211 assert!(super::imports_module(&toks, "NET"));
2212 assert!(!super::imports_module(&toks, "SSH"));
2213 let toks = lex_str("IF true {\nIMPORT [SSH]\n}\n").expect("lex");
2214 assert!(super::imports_module(&toks, "SSH"));
2215 let toks = lex_str("IMPORT [\"./a.oxdock\" AS LIB]\n").expect("lex");
2216 assert!(!super::imports_module(&toks, "NET"));
2217 let toks = lex_str("IMPORT [\"./NET.oxdock\" AS LIB]\n").expect("lex");
2219 assert!(!super::imports_module(&toks, "NET"));
2220 let toks = lex_str("// IMPORT [NET]\nECHO hi\n").expect("lex");
2221 assert!(!super::imports_module(&toks, "NET"));
2222 let toks = lex_str("ECHO \"IMPORT [NET]\"\n").expect("lex");
2223 assert!(!super::imports_module(&toks, "NET"));
2224 let toks = lex_str("WITH_IO [stdout=$p] ECHO hi\n").expect("lex");
2225 assert!(!super::imports_module(&toks, "NET"));
2226 }
2227
2228 #[cfg(not(feature = "net"))]
2232 #[test]
2233 fn unlinked_module_error_needs_a_real_import() {
2234 let err =
2235 super::unlinked_module_error("IMPORT [STD, NET]\n").expect("real import must map");
2236 assert_eq!(
2237 err.downcast_ref::<oxdock_diagnostics::Diagnostic>()
2238 .expect("typed")
2239 .key(),
2240 "cli.module_unlinked"
2241 );
2242 assert!(super::unlinked_module_error("// IMPORT [NET]\nECHO hi\n").is_none());
2243 assert!(super::unlinked_module_error("ECHO \"IMPORT [NET]\"\n").is_none());
2244 assert!(super::unlinked_module_error("ECHO hi\n").is_none());
2245 }
2246
2247 #[test]
2248 fn process_exit_code_relays_exit_requests() {
2249 let exit = anyhow::Error::new(ExitRequest(3));
2250 assert_eq!(process_exit_code(&exit), 3);
2251 let relayed =
2252 anyhow::Error::new(ExitRequest(3)).context("REMOTE 'prod' exited with code 3");
2253 assert_eq!(process_exit_code(&relayed), 3);
2254 assert_eq!(process_exit_code(&anyhow::anyhow!("boom")), 1);
2255 assert_eq!(
2256 process_exit_code(&anyhow::Error::new(ExitRequest(300))),
2257 255,
2258 "codes clamp to the portable range"
2259 );
2260 assert_eq!(
2261 process_exit_code(&anyhow::Error::new(ExitRequest(-1))),
2262 0,
2263 "negative codes clamp to zero"
2264 );
2265 }
2266}
2267
2268#[cfg(all(test, windows))]
2269mod windows_shell_tests {
2270 use super::*;
2271
2272 #[test]
2273 fn command_path_strips_verbatim_prefix() -> Result<()> {
2274 let temp = GuardedPath::tempdir()?;
2275 let converted = oxdock_fs::command_path(temp.as_guarded_path());
2276 let as_str = converted.as_ref().display().to_string();
2277 assert!(
2278 !as_str.starts_with(r"\\?\"),
2279 "expected non-verbatim path, got {as_str}"
2280 );
2281 Ok(())
2282 }
2283}