1pub use oxdock_diagnostics::{Diagnostic, DiagnosticResult, flatten_chain};
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_diag, parse_script,
18 parse_script_with_modules, 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) -> DiagnosticResult<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) -> DiagnosticResult<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<oxdock_diagnostics::Diagnostic> {
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) -> DiagnosticResult<()> {
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() -> DiagnosticResult<()> {
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) {
310 Ok(opts) => opts,
311 Err(err) if err.key() == "cli.version_requested" => {
312 println!("{err}");
313 return Ok(());
314 }
315 Err(err) if err.key() == "cli.help_requested" => {
316 print!("{err}");
317 return Ok(());
318 }
319 Err(err) => return Err(err),
320 };
321 #[cfg(feature = "net")]
324 if opts.remote_serve {
325 if opts.shell
326 || !opts.remotes.is_empty()
327 || !matches!(opts.script, ScriptSource::Stdin)
328 || !opts.script_args.is_empty()
329 {
330 return Err(errors::remote_serve_runs_alone());
331 }
332 return serve::serve();
333 }
334 #[cfg(not(feature = "net"))]
335 if opts.remote_serve {
336 return Err(errors::feature_required("--remote-serve", "net"));
337 }
338 if opts.mcp {
341 #[cfg(feature = "mcp")]
342 {
343 if opts.shell || opts.remote_serve || !opts.remotes.is_empty() {
344 return Err(errors::mcp_runs_alone(&[
345 "--shell",
346 "--remote-serve",
347 "--remote",
348 ]));
349 }
350 if !opts.endpoints.listens.is_empty() || !opts.endpoints.publishes.is_empty() {
351 return Err(errors::mcp_runs_alone(&["--listen/-p"]));
352 }
353 if opts.dry_run {
354 return Err(errors::mcp_runs_alone(&["--dry-run"]));
355 }
356 if !opts.script_args.is_empty() {
357 return Err(errors::mcp_runs_alone(&["script args"]));
358 }
359 return mcp::serve_mcp(opts, workspace_root);
360 }
361 #[cfg(not(feature = "mcp"))]
362 {
363 return Err(errors::feature_required("--mcp", "mcp"));
364 }
365 }
366 execute(opts, workspace_root)
367}
368
369pub fn process_exit_code(err: &Diagnostic) -> i32 {
373 exit_code_of_diag(err)
374 .map(|code| code.clamp(0, 255) as i32)
375 .unwrap_or(1)
376}
377
378#[derive(Debug, Clone)]
379pub enum ScriptSource {
380 Path(GuardedPath),
381 Stdin,
382}
383
384fn reject_url_script(text: &str) -> DiagnosticResult<()> {
388 if text.contains("://") {
389 return Err(errors::script_not_local(text));
390 }
391 Ok(())
392}
393
394#[derive(Debug, Clone)]
395pub struct Options {
396 pub script: ScriptSource,
397 pub shell: bool,
398 pub dry_run: bool,
401 pub endpoints: EndpointFlags,
402 pub remote_serve: bool,
403 pub mcp: bool,
406 pub remotes: Vec<(String, String)>,
409 pub script_args: Vec<String>,
414}
415
416impl Options {
417 pub fn parse(
418 args: &mut impl Iterator<Item = String>,
419 workspace_root: &GuardedPath,
420 ) -> DiagnosticResult<Self> {
421 use lexopt::Arg::{Long, Short, Value};
422
423 let mut script: Option<ScriptSource> = None;
424 let mut shell = false;
425 let mut dry_run = false;
426 let mut endpoints = EndpointFlags::default();
427 let mut remote_serve = false;
428 let mut mcp = false;
429 #[cfg_attr(not(feature = "net"), allow(unused_mut))]
431 let mut remotes: Vec<(String, String)> = Vec::new();
432 let mut script_args: Vec<String> = Vec::new();
433 let drain_tail =
442 |parser: &mut lexopt::Parser, strip_leading: bool| -> DiagnosticResult<Vec<String>> {
443 let mut raw = parser.raw_args().map_err(|e| errors::arg_lex_error(&e))?;
444 let Some(first_os) = raw.next() else {
445 return Ok(Vec::new());
446 };
447 let first = value_string(first_os)?;
448 if strip_leading && first == "--" {
449 raw.map(value_string).collect()
450 } else {
451 std::iter::once(Ok(first))
452 .chain(raw.map(value_string))
453 .collect()
454 }
455 };
456 let mut parser = lexopt::Parser::from_args(args.by_ref());
461 while let Some(arg) = parser.next().map_err(|e| errors::arg_lex_error(&e))? {
462 match arg {
463 Long("script") => {
464 let path = value_string(
465 parser
466 .value()
467 .map_err(|_| errors::script_flag_needs_path())?,
468 )?;
469 if path.is_empty() {
470 return Err(errors::script_flag_needs_path());
471 }
472 if path == "-" {
473 script = Some(ScriptSource::Stdin);
474 } else {
475 reject_url_script(&path)?;
476 script = Some(ScriptSource::Path(
477 workspace_root
478 .join_script(&path)
479 .map_err(|e| errors::guard_script_path(&path, &e))?,
480 ));
481 }
482 script_args = drain_tail(&mut parser, true)?;
485 break;
486 }
487 Long("shell") => {
488 shell = true;
489 }
490 Long("dry-run") => {
491 dry_run = true;
492 }
493 Long("listen") => {
494 let raw = value_string(
495 parser
496 .value()
497 .map_err(|_| errors::listen_requires_address())?,
498 )?;
499 #[cfg(not(feature = "net"))]
500 {
501 let _ = endpoints::parse_listen_arg(&raw);
505 return Err(errors::feature_required("--listen/-p", "net"));
506 }
507 #[cfg(feature = "net")]
508 endpoints.listens.push(endpoints::parse_listen_arg(&raw)?);
509 }
510 Short('p') => {
511 let raw = value_string(
512 parser
513 .value()
514 .map_err(|_| errors::publish_requires_shape(""))?,
515 )?;
516 #[cfg(not(feature = "net"))]
517 {
518 let _ = endpoints::parse_publish_arg(&raw);
522 return Err(errors::feature_required("--listen/-p", "net"));
523 }
524 #[cfg(feature = "net")]
525 endpoints
526 .publishes
527 .push(endpoints::parse_publish_arg(&raw)?);
528 }
529 Long("offline") => {
530 endpoints.offline = true;
531 }
532 Long("remote-serve") => {
533 remote_serve = true;
534 }
535 Long("mcp") => {
536 mcp = true;
537 }
538 Long("remote") => {
539 let raw = value_string(
540 parser
541 .value()
542 .map_err(|_| errors::remote_requires_value())?,
543 )?;
544 #[cfg(not(feature = "net"))]
545 {
546 let _ = oxdock_net_plugin_stub_parse_remote(&raw);
549 return Err(errors::feature_required("--remote", "net"));
550 }
551 #[cfg(feature = "net")]
552 remotes.push(oxdock_net_plugin::parse_remote_arg(&raw)?);
553 }
554 Long("help") | Short('h') => {
555 return Err(errors::help_requested());
556 }
557 Long("version") | Short('V') | Short('v') => {
558 return Err(errors::version_requested());
559 }
560 Value(value) => {
561 let text = value_string(value)?;
562 if text.is_empty() {
563 continue;
564 }
565 if text == "--" {
566 script = Some(ScriptSource::Stdin);
570 script_args = drain_tail(&mut parser, false)?;
571 break;
572 }
573 if text == "-" {
574 script = Some(ScriptSource::Stdin);
575 script_args = drain_tail(&mut parser, true)?;
576 break;
577 }
578 if text.starts_with('-') {
579 script = Some(ScriptSource::Stdin);
586 let mut tail = drain_tail(&mut parser, false)?;
587 tail.insert(0, text);
588 script_args = tail;
589 break;
590 }
591 reject_url_script(&text)?;
592 script = Some(ScriptSource::Path(
593 workspace_root
594 .join_script(&text)
595 .map_err(|e| errors::guard_script_path(&text, &e))?,
596 ));
597 script_args = drain_tail(&mut parser, true)?;
598 break;
599 }
600 Long(other) => {
601 return Err(errors::unexpected_flag(other, true));
602 }
603 Short(other) => {
604 return Err(errors::unexpected_flag(&other.to_string(), false));
605 }
606 }
607 }
608
609 let script = script.unwrap_or(ScriptSource::Stdin);
610
611 Ok(Self {
612 script,
613 shell,
614 dry_run,
615 endpoints,
616 remote_serve,
617 mcp,
618 remotes,
619 script_args,
620 })
621 }
622}
623
624fn value_string(value: std::ffi::OsString) -> DiagnosticResult<String> {
627 value.into_string().map_err(|_| errors::arg_not_utf8())
628}
629
630pub fn version() -> String {
632 format!("oxdock {}", env!("CARGO_PKG_VERSION"))
633}
634
635pub fn execute(opts: Options, workspace_root: GuardedPath) -> DiagnosticResult<()> {
636 init_temp_gc();
637 execute_with_shell_runner(opts, workspace_root, run_shell, true)
638}
639
640pub struct ExecutionResult {
648 pub snapshot: Arc<LazyGuardedTempDir>,
652 pub final_cwd: GuardedPath,
655 pub bindings: BTreeMap<String, Value>,
659}
660
661impl ExecutionResult {
662 pub fn has_snapshot(&self) -> bool {
664 self.snapshot.is_materialized()
665 }
666
667 pub fn snapshot_path(&self) -> Option<&GuardedPath> {
669 self.snapshot.get()
670 }
671}
672
673pub fn execute_with_result(
674 opts: Options,
675 workspace_root: GuardedPath,
676) -> DiagnosticResult<ExecutionResult> {
677 if opts.shell {
678 return Err(errors::shell_unsupported_in_result());
679 }
680
681 let script = read_script(&opts.script)?;
684
685 let mut final_cwd = workspace_root.clone();
686 let snapshot = Arc::new(LazyGuardedTempDir::new());
687 if !script.trim().is_empty() {
688 let steps = parse_cli_script(&script)?;
689 if opts.dry_run {
692 print_dry_run(&steps, &opts.script, &workspace_root)?;
693 return Ok(ExecutionResult {
694 snapshot,
695 final_cwd,
696 bindings: BTreeMap::new(),
697 });
698 }
699 #[cfg(feature = "net")]
702 let registry = build_registry(&opts.endpoints)?;
703 #[cfg(not(feature = "net"))]
704 check_no_net_endpoints(&opts.endpoints)?;
705 #[cfg(not(feature = "net"))]
706 check_no_net_remotes(&opts.remotes)?;
707 #[cfg(feature = "net")]
711 let inventory = {
712 let pairs = opts.remotes.clone();
713 let inventory = oxdock_net_plugin::RemoteInventory::build(pairs)?;
714 inventory.log_resolutions();
715 inventory.validate_script(&steps)?;
716 inventory
717 };
718 let entry_file = entry_file_of(&opts.script);
719 #[cfg(feature = "net")]
720 let io_cfg = {
721 let mut io_cfg = ExecIo::new();
722 io_cfg.set_script_args(opts.script_args.clone());
723 register_remote_runners(&mut io_cfg, &inventory);
724 io_cfg
725 };
726 #[cfg(not(feature = "net"))]
727 let io_cfg = {
728 let mut io_cfg = ExecIo::new();
729 io_cfg.set_script_args(opts.script_args.clone());
730 io_cfg
731 };
732 #[cfg(feature = "net")]
733 let output = run_cli_steps(&workspace_root, &steps, io_cfg, Some(®istry), entry_file)?;
734 #[cfg(not(feature = "net"))]
735 let output = run_cli_steps(&workspace_root, &steps, io_cfg, None, entry_file)?;
736 final_cwd = output.final_cwd;
737 return Ok(ExecutionResult {
738 snapshot: output.snapshot,
739 final_cwd,
740 bindings: output.bindings,
741 });
742 }
743
744 Ok(ExecutionResult {
745 snapshot,
746 final_cwd,
747 bindings: BTreeMap::new(),
748 })
749}
750
751#[cfg(feature = "net")]
756fn register_remote_runners(io: &mut ExecIo, inventory: &oxdock_net_plugin::RemoteInventory) {
757 use std::sync::Arc;
758 let entries = surface_entries();
759 let module_hash = oxdock_net_plugin::module_hash(&entries);
760 let modules: Vec<String> = entries.iter().map(|(name, _)| name.clone()).collect();
761 for target in inventory.targets() {
762 let Some(argv) = inventory.argv(&target) else {
763 continue;
764 };
765 let config = oxdock_net_plugin::SessionConfig {
766 argv: argv.to_vec(),
767 oxdock_version: env!("CARGO_PKG_VERSION").to_string(),
768 modules: modules.clone(),
769 module_hash: module_hash.clone(),
770 };
771 io.set_remote_runner_for_target(
772 target,
773 Arc::new(oxdock_net_plugin::StdioSession::new(config)),
774 );
775 }
776}
777
778#[cfg(feature = "net")]
781fn surface_entries() -> Vec<(String, Vec<String>)> {
782 let mut engine = Engine::new();
783 for module in cli_host_modules() {
784 engine.register_module(module);
785 }
786 let table = engine.module_table();
787 let mut entries: Vec<(String, Vec<String>)> = table
788 .modules
789 .into_iter()
790 .map(|(name, module_funcs)| {
791 let mut func_names: Vec<String> = module_funcs
792 .map(|surface| surface.func_names.into_iter().collect())
793 .unwrap_or_default();
794 func_names.sort();
795 (name, func_names)
796 })
797 .collect();
798 entries.sort();
799 entries
800}
801#[cfg(feature = "net")]
802fn report_ephemeral_publishes(flags: &EndpointFlags, registry: &Arc<EndpointRegistry>) {
803 use oxdock_net_plugin::{EndpointKey, Protocol, parse_endpoint_ref};
804 for (outer, inner) in &flags.publishes {
805 if outer.port() != 0 {
806 continue;
807 }
808 let Ok((protocol, endpoint)) = parse_endpoint_ref(inner, "-p") else {
809 continue;
810 };
811 let key = EndpointKey {
812 protocol: protocol.unwrap_or(Protocol::Tcp),
813 endpoint,
814 };
815 match registry.resolve_endpoint(&key) {
816 Ok(addr) => eprintln!("oxdock: published {addr} -> {inner}"),
817 Err(_) => eprintln!("oxdock: published <unbound> -> {inner}"),
818 }
819 }
820}
821
822#[cfg(not(feature = "net"))]
825fn oxdock_net_plugin_stub_parse_remote(raw: &str) -> DiagnosticResult<(String, String)> {
826 match raw.split_once('=') {
829 Some((target, command)) if !target.trim().is_empty() && !command.trim().is_empty() => {
830 Ok((target.trim().to_string(), command.to_string()))
831 }
832 _ => Err(errors::remote_requires_shape(raw)),
833 }
834}
835
836#[cfg(not(feature = "net"))]
838fn check_no_net_remotes(remotes: &[(String, String)]) -> DiagnosticResult<()> {
839 if !remotes.is_empty() {
840 return Err(errors::feature_required("--remote", "net"));
841 }
842 Ok(())
843}
844
845#[cfg(not(feature = "net"))]
849fn check_no_net_endpoints(flags: &EndpointFlags) -> DiagnosticResult<()> {
850 if !flags.listens.is_empty() || !flags.publishes.is_empty() {
851 return Err(errors::feature_required("--listen/-p", "net"));
852 }
853 Ok(())
854}
855
856fn read_script(source: &ScriptSource) -> DiagnosticResult<String> {
860 match source {
861 ScriptSource::Path(path) => {
862 let resolver = PathResolver::new(path.root(), path.root())?;
863 resolver
864 .read_to_string(path)
865 .map_err(|e| errors::read_script_at(&path.display().to_string(), &e))
866 }
867 ScriptSource::Stdin => {
868 let mut buf = String::new();
869 io::stdin()
870 .lock()
871 .read_to_string(&mut buf)
872 .map_err(|e| errors::read_script_stdin(&e))?;
873 Ok(buf)
874 }
875 }
876}
877
878fn execute_with_shell_runner<F>(
879 opts: Options,
880 workspace_root: GuardedPath,
881 shell_runner: F,
882 require_tty: bool,
883) -> DiagnosticResult<()>
884where
885 F: FnOnce(&GuardedPath, &GuardedPath) -> DiagnosticResult<()>,
886{
887 #[cfg(windows)]
888 maybe_reexec_shell_to_temp(&opts)?;
889
890 let script = match &opts.script {
894 ScriptSource::Path(_) => read_script(&opts.script)?,
895 ScriptSource::Stdin => {
896 let stdin = io::stdin();
897 if stdin.is_terminal() {
898 if opts.shell {
903 String::new()
904 } else {
905 return Err(errors::script_stdin_missing());
906 }
907 } else {
908 let mut buf = String::new();
909 stdin
910 .lock()
911 .read_to_string(&mut buf)
912 .map_err(|e| errors::read_script_stdin(&e))?;
913 buf
914 }
915 }
916 };
917
918 let mut final_cwd = workspace_root.clone();
925 let mut snapshot = Arc::new(LazyGuardedTempDir::new());
926 let mut fs: Option<Box<dyn WorkspaceFs>> = None;
927 if !script.trim().is_empty() {
928 let steps = parse_cli_script(&script)?;
929 if opts.dry_run {
932 print_dry_run(&steps, &opts.script, &workspace_root)?;
933 return Ok(());
934 }
935 #[cfg(feature = "net")]
938 let registry = build_registry(&opts.endpoints)?;
939 #[cfg(not(feature = "net"))]
940 check_no_net_endpoints(&opts.endpoints)?;
941 #[cfg(not(feature = "net"))]
942 check_no_net_remotes(&opts.remotes)?;
943 #[cfg(feature = "net")]
944 report_ephemeral_publishes(&opts.endpoints, ®istry);
945 #[cfg(feature = "net")]
949 let inventory = {
950 let inventory = oxdock_net_plugin::RemoteInventory::build(opts.remotes.clone())?;
951 inventory.log_resolutions();
952 inventory.validate_script(&steps)?;
953 inventory
954 };
955 let mut stdin_handle: Option<SharedInput> = None;
960 if let ScriptSource::Path(_) = opts.script {
961 let stdin = io::stdin();
962 if !stdin.is_terminal() {
963 stdin_handle = Some(Arc::new(Mutex::new(stdin)));
969 }
970 }
971
972 let mut io_cfg = ExecIo::new();
973 io_cfg.set_stdin(stdin_handle);
974 io_cfg.set_script_args(opts.script_args.clone());
975 #[cfg(feature = "net")]
976 register_remote_runners(&mut io_cfg, &inventory);
977 let entry_file = entry_file_of(&opts.script);
978 #[cfg(feature = "net")]
979 let output = run_cli_steps(&workspace_root, &steps, io_cfg, Some(®istry), entry_file)?;
980 #[cfg(not(feature = "net"))]
981 let output = run_cli_steps(&workspace_root, &steps, io_cfg, None, entry_file)?;
982 final_cwd = output.final_cwd;
983 snapshot = output.snapshot;
984 fs = Some(output.fs);
985 }
986
987 if opts.shell {
989 if require_tty && !has_controlling_tty() {
990 return Err(errors::shell_needs_tty());
991 }
992 match fs.as_ref() {
997 Some(fs) => {
998 if fs.is_snapshot_pending() {
999 snapshot
1000 .materialize()
1001 .map_err(|e| errors::create_shell_temp_dir(&e))?;
1002 }
1003 final_cwd = fs.concretize_cwd(&final_cwd);
1004 }
1005 None => {
1006 snapshot
1007 .materialize()
1008 .map_err(|e| errors::create_shell_temp_dir(&e))?;
1009 final_cwd = snapshot
1010 .get()
1011 .cloned()
1012 .expect("shell snapshot materialized above");
1013 }
1014 }
1015 return shell_runner(&final_cwd, &workspace_root);
1016 }
1017
1018 Ok(())
1019}
1020
1021#[cfg(test)]
1022fn execute_for_test<F>(
1023 opts: Options,
1024 workspace_root: GuardedPath,
1025 shell_runner: F,
1026) -> DiagnosticResult<()>
1027where
1028 F: FnOnce(&GuardedPath, &GuardedPath) -> DiagnosticResult<()>,
1029{
1030 execute_with_shell_runner(opts, workspace_root, shell_runner, false)
1031}
1032
1033fn has_controlling_tty() -> bool {
1034 #[cfg(unix)]
1038 {
1039 io::stdin().is_terminal() || io::stderr().is_terminal()
1040 }
1041
1042 #[cfg(windows)]
1043 {
1044 io::stdin().is_terminal() || io::stderr().is_terminal()
1045 }
1046
1047 #[cfg(not(any(unix, windows)))]
1048 {
1049 false
1050 }
1051}
1052
1053#[cfg(windows)]
1054fn maybe_reexec_shell_to_temp(opts: &Options) -> DiagnosticResult<()> {
1055 if !opts.shell {
1058 return Ok(());
1059 }
1060 if std::env::var(oxdock_env::oxdock::SHELL_REEXEC)
1061 .ok()
1062 .as_deref()
1063 == Some("1")
1064 {
1065 return Ok(());
1066 }
1067
1068 let self_path = std::env::current_exe().map_err(|e| errors::determine_current_exe(&e))?;
1069 let base_temp = GuardedPath::new_root(std::env::temp_dir().as_path())
1070 .map_err(|e| errors::guard_system_temp_dir(&e))?;
1071 let ts = std::time::SystemTime::now()
1072 .duration_since(std::time::UNIX_EPOCH)
1073 .unwrap_or_default()
1074 .as_millis();
1075 let temp_file = base_temp
1076 .join(&format!("oxdock-shell-{ts}-{}.exe", std::process::id()))
1077 .map_err(|e| errors::construct_temp_shell_path(&e))?;
1078
1079 let temp_root_guard = temp_file
1083 .parent()
1084 .ok_or_else(errors::shell_temp_missing_parent)?;
1085 let resolver_temp = PathResolver::new(temp_root_guard.as_path(), temp_root_guard.as_path())?;
1086 let dest = temp_file;
1087 #[allow(clippy::disallowed_types)]
1088 let source = oxdock_fs::UnguardedPath::external(self_path);
1089 resolver_temp
1090 .copy_file_from_unguarded(&source, &dest)
1091 .map_err(|e| errors::copy_shell_runner(&dest.display().to_string(), &e))?;
1092
1093 let mut cmd = CommandBuilder::new(dest.as_path());
1094 cmd.args(std::env::args_os().skip(1));
1095 cmd.env(oxdock_env::oxdock::SHELL_REEXEC, "1");
1096 cmd.spawn()
1097 .map_err(|e| errors::spawn_shell_from(&dest.display().to_string(), &e))?;
1098
1099 std::process::exit(0);
1101}
1102
1103pub fn run_script(workspace_root: &GuardedPath, steps: &[Step]) -> DiagnosticResult<()> {
1104 run_steps_with_context(workspace_root, workspace_root, steps)
1105}
1106
1107fn shell_banner(cwd: &GuardedPath, workspace_root: &GuardedPath) -> String {
1108 #[cfg(windows)]
1109 let cwd_disp = oxdock_fs::command_path(cwd).as_ref().display().to_string();
1110 #[cfg(windows)]
1111 let workspace_disp = oxdock_fs::command_path(workspace_root)
1112 .as_ref()
1113 .display()
1114 .to_string();
1115
1116 #[cfg(not(windows))]
1117 let cwd_disp = cwd.display().to_string();
1118 #[cfg(not(windows))]
1119 let workspace_disp = workspace_root.display().to_string();
1120
1121 let pkg = env::var(oxdock_env::cargo::PKG_NAME)
1122 .unwrap_or_else(|_| oxdock_env::oxdock::FALLBACK_APP_NAME.to_string());
1123 indoc::formatdoc! {"
1124 {pkg} shell workspace
1125 cwd: {cwd_disp}
1126 source: workspace root at {workspace_disp}
1127 lifetime: temporary directory created for this shell session; it disappears when you exit
1128 creation: temp workspace starts empty unless your script copies files into it
1129
1130 WARNING: This shell still runs on your host filesystem and is **not** isolated!
1131 "}
1132}
1133
1134fn run_shell(cwd: &GuardedPath, workspace_root: &GuardedPath) -> DiagnosticResult<()> {
1135 oxdock_process::spawn_interactive_shell(cwd, workspace_root, &shell_banner(cwd, workspace_root))
1136}
1137
1138#[cfg(test)]
1141mod tests {
1142 use super::*;
1143 use anyhow::Result;
1144 use indoc::indoc;
1145 use oxdock_fs::PathResolver;
1146 use std::cell::{Cell, RefCell};
1147
1148 #[cfg_attr(
1149 miri,
1150 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1151 )]
1152 #[test]
1153 fn shell_runner_receives_final_workdir() -> Result<()> {
1154 let workspace = GuardedPath::tempdir()?;
1155 let workspace_root = workspace.as_guarded_path().clone();
1156 let script_path = workspace_root.join("script.ox")?;
1157 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1158 let script = indoc! {"
1159 WRITE temp.txt 123
1160 WORKDIR sub
1161 "};
1162 resolver.write_file(&script_path, script.as_bytes())?;
1163
1164 let opts = Options {
1165 script: ScriptSource::Path(script_path),
1166 shell: true,
1167 dry_run: false,
1168 endpoints: EndpointFlags::default(),
1169 remote_serve: false,
1170 mcp: false,
1171 remotes: Vec::new(),
1172 script_args: Vec::new(),
1173 };
1174
1175 let observed = Cell::new(false);
1176 execute_for_test(opts, workspace_root.clone(), |cwd, _| {
1177 assert!(
1178 cwd.as_path().ends_with("sub"),
1179 "final cwd should end in WORKDIR target, got {}",
1180 cwd.display()
1181 );
1182
1183 let temp_root = GuardedPath::new_root(cwd.root())?;
1184 let sub_dir = temp_root.join("sub")?;
1185 assert_eq!(
1186 cwd.as_path(),
1187 sub_dir.as_path(),
1188 "shell runner cwd should match guarded sub dir"
1189 );
1190 let temp_file = temp_root.join("temp.txt")?;
1191 let temp_resolver = PathResolver::new(temp_root.as_path(), temp_root.as_path())?;
1192 let contents = temp_resolver.read_to_string(&temp_file)?;
1193 assert!(
1194 contents.contains("123"),
1195 "expected WRITE command to materialize temp file"
1196 );
1197 observed.set(true);
1198 Ok(())
1199 })?;
1200
1201 assert!(
1202 observed.into_inner(),
1203 "shell runner closure should have been invoked"
1204 );
1205 Ok(())
1206 }
1207
1208 #[cfg_attr(
1209 miri,
1210 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1211 )]
1212 #[test]
1213 fn options_parse_requires_script_path_value() {
1214 let workspace = GuardedPath::tempdir().expect("tempdir");
1215 let mut args = vec!["--script".to_string()].into_iter();
1216 let err = Options::parse(&mut args, workspace.as_guarded_path())
1217 .expect_err("expected missing path error");
1218 assert!(err.to_string().contains("--script requires a path"));
1219 }
1220
1221 #[cfg_attr(
1222 miri,
1223 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1224 )]
1225 #[test]
1226 fn options_parse_script_flag_takes_dash_leading_path() {
1227 let workspace = GuardedPath::tempdir().expect("tempdir");
1230 let workspace_root = workspace.as_guarded_path().clone();
1231 let mut args = vec!["--script".to_string(), "--weird.ox".to_string()].into_iter();
1232 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1233 match opts.script {
1234 ScriptSource::Path(path) => assert_eq!(
1235 path,
1236 workspace_root.join("--weird.ox").expect("script path")
1237 ),
1238 ScriptSource::Stdin => panic!("expected path script"),
1239 }
1240 assert!(opts.script_args.is_empty());
1241 }
1242
1243 #[cfg_attr(
1244 miri,
1245 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1246 )]
1247 #[test]
1248 fn options_parse_script_path_and_shell() {
1249 let workspace = GuardedPath::tempdir().expect("tempdir");
1250 let workspace_root = workspace.as_guarded_path().clone();
1251 let script_path = workspace_root.join("script.txt").expect("script path");
1252 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1253 .expect("resolver");
1254 resolver
1255 .write_file(&script_path, b"WRITE out.txt hi")
1256 .expect("write script");
1257 let mut args = vec![
1260 "--shell".to_string(),
1261 "--script".to_string(),
1262 "script.txt".to_string(),
1263 ]
1264 .into_iter();
1265 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1266 assert!(opts.shell);
1267 match opts.script {
1268 ScriptSource::Path(path) => assert_eq!(path, script_path),
1269 ScriptSource::Stdin => panic!("expected path script"),
1270 }
1271 assert!(opts.script_args.is_empty());
1272
1273 let mut args = vec![
1274 "--script".to_string(),
1275 "script.txt".to_string(),
1276 "--shell".to_string(),
1277 ]
1278 .into_iter();
1279 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1280 assert!(
1281 !opts.shell,
1282 "--shell after the script is data, not the interpreter flag"
1283 );
1284 assert_eq!(opts.script_args, vec!["--shell"]);
1285 }
1286
1287 #[cfg_attr(
1288 miri,
1289 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1290 )]
1291 #[test]
1292 fn options_parse_mcp_flag() {
1293 let workspace = GuardedPath::tempdir().expect("tempdir");
1294 let workspace_root = workspace.as_guarded_path().clone();
1295 let mut args = vec!["--mcp".to_string(), "tools.oxdock".to_string()].into_iter();
1296 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1297 assert!(opts.mcp);
1298 match opts.script {
1299 ScriptSource::Path(path) => assert_eq!(
1300 path,
1301 workspace_root.join("tools.oxdock").expect("script path")
1302 ),
1303 ScriptSource::Stdin => panic!("expected path script"),
1304 }
1305 }
1306
1307 #[cfg_attr(
1308 miri,
1309 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1310 )]
1311 #[test]
1312 fn options_parse_mcp_defaults_off() {
1313 let workspace = GuardedPath::tempdir().expect("tempdir");
1314 let workspace_root = workspace.as_guarded_path().clone();
1315 let mut args = vec!["script.txt".to_string()].into_iter();
1316 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1317 assert!(!opts.mcp);
1318 }
1319
1320 #[cfg_attr(
1321 miri,
1322 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1323 )]
1324 #[test]
1325 fn options_parse_positional_script_path() {
1326 let workspace = GuardedPath::tempdir().expect("tempdir");
1327 let workspace_root = workspace.as_guarded_path().clone();
1328 let mut args = vec!["script.txt".to_string()].into_iter();
1329 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1330 assert!(!opts.shell);
1331 match opts.script {
1332 ScriptSource::Path(path) => assert_eq!(
1333 path,
1334 workspace_root.join("script.txt").expect("script path")
1335 ),
1336 ScriptSource::Stdin => panic!("expected path script"),
1337 }
1338 }
1339
1340 #[cfg_attr(
1341 miri,
1342 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1343 )]
1344 #[test]
1345 fn options_parse_positional_dash_reads_stdin() {
1346 let workspace = GuardedPath::tempdir().expect("tempdir");
1347 let mut args = vec!["-".to_string()].into_iter();
1348 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1349 assert!(matches!(opts.script, ScriptSource::Stdin));
1350 }
1351
1352 #[cfg_attr(
1353 miri,
1354 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1355 )]
1356 #[test]
1357 fn options_parse_second_positional_is_script_arg() {
1358 let workspace = GuardedPath::tempdir().expect("tempdir");
1362 let workspace_root = workspace.as_guarded_path().clone();
1363 let mut args = vec![
1364 "a.ox".to_string(),
1365 "--script".to_string(),
1366 "b.ox".to_string(),
1367 ]
1368 .into_iter();
1369 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1370 match &opts.script {
1371 ScriptSource::Path(path) => assert_eq!(
1372 path,
1373 &workspace_root.join("a.ox").expect("script path"),
1374 "first positional fixes the script"
1375 ),
1376 ScriptSource::Stdin => panic!("expected path script"),
1377 }
1378 assert_eq!(opts.script_args, vec!["--script", "b.ox"]);
1379
1380 let mut args = vec!["a.ox".to_string(), "b.ox".to_string()].into_iter();
1381 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1382 assert_eq!(opts.script_args, vec!["b.ox"]);
1383 }
1384
1385 #[cfg_attr(
1386 miri,
1387 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1388 )]
1389 #[test]
1390 fn options_parse_absolute_script_outside_execution_workspace_loads() {
1391 let workspace = GuardedPath::tempdir().expect("tempdir");
1394 let outside = GuardedPath::tempdir().expect("outside");
1395 let target = outside
1396 .as_guarded_path()
1397 .as_path()
1398 .join("step.ox")
1399 .to_string_lossy()
1400 .into_owned();
1401 let mut args = vec!["--script".to_string(), target.clone()].into_iter();
1402 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1403 match opts.script {
1404 ScriptSource::Path(path) => {
1405 assert_eq!(path.as_path().to_string_lossy(), target);
1406 assert_eq!(path.root(), outside.as_guarded_path().as_path());
1407 }
1408 ScriptSource::Stdin => panic!("absolute script must not parse as stdin"),
1409 }
1410 }
1411
1412 #[cfg_attr(
1413 miri,
1414 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1415 )]
1416 #[test]
1417 fn options_parse_relative_escape_stays_rejected() {
1418 let workspace = GuardedPath::tempdir().expect("tempdir");
1419 let mut args = vec!["--script".to_string(), "../escape.ox".to_string()].into_iter();
1420 let err =
1421 Options::parse(&mut args, workspace.as_guarded_path()).expect_err("escape must fail");
1422 assert!(err.to_string().contains("guard script path"), "{err:?}");
1423 }
1424
1425 #[cfg_attr(
1426 miri,
1427 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1428 )]
1429 #[test]
1430 fn options_parse_rejects_unknown_flags() {
1431 let workspace = GuardedPath::tempdir().expect("tempdir");
1432 let mut args = vec!["--frobnicate".to_string()].into_iter();
1433 let err = Options::parse(&mut args, workspace.as_guarded_path())
1434 .expect_err("expected unknown flag error");
1435 assert!(err.to_string().contains("unexpected flag"), "{err:?}");
1436 }
1437
1438 #[test]
1439 fn usage_describes_positional_script_and_help() {
1440 let text = usage();
1441 assert!(text.contains("Usage: oxdock"), "{text}");
1442 assert!(text.contains("SCRIPT"), "{text}");
1443 assert!(text.contains("--script"), "{text}");
1444 assert!(text.contains("--help"), "{text}");
1445 assert!(text.contains("--offline"), "{text}");
1446 #[cfg(feature = "net")]
1447 {
1448 assert!(text.contains("--listen"), "{text}");
1449 assert!(text.contains("-p <[host:]outer:inner>"), "{text}");
1450 }
1451 #[cfg(not(feature = "net"))]
1452 {
1453 assert!(!text.contains("--listen <addr>"), "{text}");
1454 assert!(!text.contains("-p <[host:]outer:inner>"), "{text}");
1455 assert!(text.contains("require the `net` feature"), "{text}");
1456 }
1457 assert!(text.contains(env!("CARGO_PKG_DESCRIPTION")), "{text}");
1459 }
1460
1461 #[cfg(feature = "net")]
1462 #[cfg_attr(
1463 miri,
1464 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1465 )]
1466 #[test]
1467 fn options_parse_endpoint_flags() {
1468 let workspace = GuardedPath::tempdir().expect("tempdir");
1471 let mut args = vec![
1472 "--listen".to_string(),
1473 "0.0.0.0:2251".to_string(),
1474 "-p".to_string(),
1475 "2222:demo-proxy".to_string(),
1476 "-p".to_string(),
1477 "0:2252".to_string(),
1478 "-".to_string(),
1479 ]
1480 .into_iter();
1481 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1482 assert_eq!(opts.endpoints.listens.len(), 1);
1483 assert_eq!(opts.endpoints.publishes.len(), 2);
1484 assert!(!opts.endpoints.offline);
1485 assert!(matches!(opts.script, ScriptSource::Stdin));
1486 }
1487
1488 #[cfg_attr(
1489 miri,
1490 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1491 )]
1492 #[test]
1493 fn options_parse_offline_flag() {
1494 let workspace = GuardedPath::tempdir().expect("tempdir");
1495 let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
1496 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1497 assert!(opts.endpoints.offline);
1498 }
1499
1500 #[cfg(feature = "net")]
1501 #[cfg_attr(
1502 miri,
1503 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1504 )]
1505 #[test]
1506 fn options_parse_rejects_bad_endpoint_flags() {
1507 let workspace = GuardedPath::tempdir().expect("tempdir");
1508 for args in [
1509 vec!["--listen"],
1510 vec!["--listen", "0.0.0.0:0"],
1511 vec!["-p"],
1512 vec!["-p", "2222"],
1513 vec!["-p", "2222:0"],
1514 ] {
1515 let mut args = args.into_iter().map(str::to_string);
1516 Options::parse(&mut args, workspace.as_guarded_path())
1517 .expect_err("bad endpoint flag must fail");
1518 }
1519 }
1520
1521 #[cfg_attr(
1522 miri,
1523 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1524 )]
1525 #[test]
1526 fn options_parse_empty_values_hold_token_boundaries() {
1527 let workspace = GuardedPath::tempdir().expect("tempdir");
1531 let mut args = vec![
1532 "--script".to_string(),
1533 "".to_string(),
1534 "--shell".to_string(),
1535 ]
1536 .into_iter();
1537 let err = Options::parse(&mut args, workspace.as_guarded_path())
1538 .expect_err("empty script path must fail");
1539 assert!(
1540 err.to_string().contains("--script requires a path"),
1541 "{err:?}"
1542 );
1543 let mut args = vec!["".to_string(), "-".to_string()].into_iter();
1544 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
1545 assert!(matches!(opts.script, ScriptSource::Stdin));
1546 }
1547
1548 #[cfg(feature = "net")]
1549 #[cfg_attr(
1550 miri,
1551 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1552 )]
1553 #[test]
1554 fn options_parse_accepts_equals_and_attached_forms() {
1555 let workspace = GuardedPath::tempdir().expect("tempdir");
1558 let workspace_root = workspace.as_guarded_path().clone();
1559 let mut args = vec![
1560 "--listen=0.0.0.0:2251".to_string(),
1561 "-p2222:demo-proxy".to_string(),
1562 "--".to_string(),
1563 "script.ox".to_string(),
1564 ]
1565 .into_iter();
1566 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1567 assert_eq!(opts.endpoints.listens.len(), 1);
1568 assert_eq!(opts.endpoints.publishes.len(), 1);
1569 match opts.script {
1570 ScriptSource::Path(path) => {
1571 assert_eq!(path, workspace_root.join("script.ox").expect("script path"))
1572 }
1573 ScriptSource::Stdin => panic!("expected path script after --"),
1574 }
1575 assert!(opts.script_args.is_empty());
1576 }
1577
1578 #[cfg_attr(
1579 miri,
1580 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1581 )]
1582 #[test]
1583 fn options_parse_routes_verbatim_tail_to_script_args() {
1584 let workspace = GuardedPath::tempdir().expect("tempdir");
1587 let workspace_root = workspace.as_guarded_path().clone();
1588 let mut args = vec![
1589 "my.ox".to_string(),
1590 "--dry-run".to_string(),
1591 "--listen".to_string(),
1592 "0.0.0.0:2251".to_string(),
1593 ]
1594 .into_iter();
1595 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1596 assert_eq!(
1597 opts.script_args,
1598 vec!["--dry-run", "--listen", "0.0.0.0:2251"]
1599 );
1600
1601 let mut args = vec![
1602 "my.ox".to_string(),
1603 "--".to_string(),
1604 "--dry-run".to_string(),
1605 ]
1606 .into_iter();
1607 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1608 assert_eq!(opts.script_args, vec!["--dry-run"]);
1609
1610 let mut args = vec![
1611 "--script".to_string(),
1612 "my.ox".to_string(),
1613 "--".to_string(),
1614 "a".to_string(),
1615 "--".to_string(),
1616 "b".to_string(),
1617 ]
1618 .into_iter();
1619 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1620 assert_eq!(opts.script_args, vec!["a", "--", "b"]);
1621 }
1622
1623 #[cfg_attr(
1624 miri,
1625 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1626 )]
1627 #[test]
1628 fn options_parse_help_after_script_is_data() {
1629 let workspace = GuardedPath::tempdir().expect("tempdir");
1631 let workspace_root = workspace.as_guarded_path().clone();
1632 let mut args = vec!["my.ox".to_string(), "--help".to_string()].into_iter();
1633 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1634 assert_eq!(opts.script_args, vec!["--help"]);
1635 let mut args = vec!["my.ox".to_string(), "--version".to_string()].into_iter();
1636 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1637 assert_eq!(opts.script_args, vec!["--version"]);
1638 }
1639
1640 #[cfg_attr(
1641 miri,
1642 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1643 )]
1644 #[test]
1645 fn options_parse_dash_leading_after_separator_is_stdin_args() {
1646 let workspace = GuardedPath::tempdir().expect("tempdir");
1649 let workspace_root = workspace.as_guarded_path().clone();
1650 let mut args = vec!["--".to_string(), "--foo".to_string()].into_iter();
1651 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1652 assert!(matches!(opts.script, ScriptSource::Stdin));
1653 assert_eq!(opts.script_args, vec!["--foo"]);
1654
1655 let mut args = vec!["--".to_string(), "script.ox".to_string()].into_iter();
1656 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1657 match opts.script {
1658 ScriptSource::Path(path) => {
1659 assert_eq!(path, workspace_root.join("script.ox").expect("script path"))
1660 }
1661 ScriptSource::Stdin => panic!("expected path script"),
1662 }
1663 assert!(opts.script_args.is_empty());
1664
1665 let mut args = vec!["--".to_string(), "--".to_string(), "a".to_string()].into_iter();
1666 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1667 assert!(matches!(opts.script, ScriptSource::Stdin));
1668 assert_eq!(opts.script_args, vec!["a"]);
1669 }
1670
1671 #[cfg_attr(
1672 miri,
1673 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1674 )]
1675 #[test]
1676 fn options_parse_preserves_inner_separators_in_tail() {
1677 let workspace = GuardedPath::tempdir().expect("tempdir");
1679 let workspace_root = workspace.as_guarded_path().clone();
1680 let mut args = vec![
1681 "--".to_string(),
1682 "--foo".to_string(),
1683 "--".to_string(),
1684 "--bar".to_string(),
1685 ]
1686 .into_iter();
1687 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1688 assert!(matches!(opts.script, ScriptSource::Stdin));
1689 assert_eq!(opts.script_args, vec!["--foo", "--", "--bar"]);
1690
1691 let mut args = vec![
1692 "my.ox".to_string(),
1693 "a".to_string(),
1694 "--".to_string(),
1695 "b".to_string(),
1696 ]
1697 .into_iter();
1698 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1699 assert_eq!(opts.script_args, vec!["a", "--", "b"]);
1700 }
1701
1702 #[cfg_attr(
1703 miri,
1704 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1705 )]
1706 #[test]
1707 fn options_parse_version_returns_version_without_exiting() {
1708 let workspace = GuardedPath::tempdir().expect("tempdir");
1712 for flag in ["--version", "-V", "-v"] {
1713 let mut args = vec![flag.to_string()].into_iter();
1714 let err = Options::parse(&mut args, workspace.as_guarded_path())
1715 .expect_err("version flag must not parse as options");
1716 assert_eq!(err.key(), "cli.version_requested");
1717 assert_eq!(err.to_string(), version());
1718 }
1719 }
1720
1721 #[cfg_attr(
1722 miri,
1723 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1724 )]
1725 #[test]
1726 fn options_parse_help_returns_usage_error_without_exiting() {
1727 let workspace = GuardedPath::tempdir().expect("tempdir");
1730 for flag in ["--help", "-h"] {
1731 let mut args = vec![flag.to_string()].into_iter();
1732 let err = Options::parse(&mut args, workspace.as_guarded_path())
1733 .expect_err("help flag must not parse as options");
1734 assert_eq!(err.key(), "cli.help_requested");
1735 assert_eq!(err.to_string(), usage());
1736 }
1737 }
1738
1739 #[cfg_attr(
1740 miri,
1741 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1742 )]
1743 #[test]
1744 fn options_parse_rejects_remote_script_with_input_intact() {
1745 let workspace = GuardedPath::tempdir().expect("tempdir");
1746 for args in [
1747 vec!["https://example.com/process.oxfile".to_string()],
1748 vec![
1749 "--script".to_string(),
1750 "https://example.com/process.oxfile".to_string(),
1751 ],
1752 ] {
1753 let err = Options::parse(&mut args.into_iter(), workspace.as_guarded_path())
1754 .expect_err("remote script must not parse as a path");
1755 let rendered = format!("{err:#}");
1756 assert!(
1757 rendered.contains("not a local path")
1758 && rendered.contains("https://example.com/process.oxfile"),
1759 "rejection names the intact input: {rendered}"
1760 );
1761 assert!(
1762 !rendered.contains("https:/example.com"),
1763 "scheme must never come out mangled: {rendered}"
1764 );
1765 }
1766 }
1767
1768 #[test]
1769 fn execute_with_result_runs_script() {
1770 let workspace = GuardedPath::tempdir().expect("tempdir");
1771 let workspace_root = workspace.as_guarded_path().clone();
1772 let script_path = workspace_root.join("script.txt").expect("script path");
1773 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1774 .expect("resolver");
1775 resolver
1776 .write_file(&script_path, b"WRITE out.txt hi")
1777 .expect("write script");
1778 let opts = Options {
1779 script: ScriptSource::Path(script_path),
1780 shell: false,
1781 dry_run: false,
1782 endpoints: EndpointFlags::default(),
1783 remote_serve: false,
1784 mcp: false,
1785 remotes: Vec::new(),
1786 script_args: Vec::new(),
1787 };
1788 let result = execute_with_result(opts, workspace_root).expect("execute");
1789 let snapshot = result
1790 .snapshot_path()
1791 .expect("default WRITE materializes the snapshot");
1792 assert_eq!(snapshot, &result.final_cwd);
1793 let temp_resolver = PathResolver::new(snapshot.root(), snapshot.root()).expect("resolver");
1794 let out = snapshot.join("out.txt").expect("out path");
1795 let contents = temp_resolver.read_to_string(&out).expect("read out");
1796 assert_eq!(contents.trim(), "hi");
1797 }
1798
1799 #[cfg_attr(
1800 miri,
1801 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1802 )]
1803 #[test]
1804 fn execute_with_result_routes_script_args_to_argv() {
1805 let workspace = GuardedPath::tempdir().expect("tempdir");
1808 let workspace_root = workspace.as_guarded_path().clone();
1809 let script_path = workspace_root.join("script.txt").expect("script path");
1810 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1811 .expect("resolver");
1812 let script = indoc! {r#"
1813 IMPORT [STD]
1814 LET $args: LIST<STRING> = ARGV()
1815 LET $n: INT = LEN($args)
1816 ASSERT_EQ $n 2
1817 ASSERT_EQ $args.0 "--dry-run"
1818 ASSERT_EQ $args.1 "serve"
1819 WRITE out.txt "ok"
1820 "#};
1821 resolver
1822 .write_file(&script_path, script.as_bytes())
1823 .expect("write script");
1824 let mut args = vec![
1827 "script.txt".to_string(),
1828 "--".to_string(),
1829 "--dry-run".to_string(),
1830 "serve".to_string(),
1831 ]
1832 .into_iter();
1833 let opts = Options::parse(&mut args, &workspace_root).expect("parse");
1834 assert_eq!(opts.script_args, vec!["--dry-run", "serve"]);
1835 let result = execute_with_result(opts, workspace_root).expect("execute");
1836 let snapshot = result
1837 .snapshot_path()
1838 .expect("WRITE materializes the snapshot");
1839 let temp_resolver = PathResolver::new(snapshot.root(), snapshot.root()).expect("resolver");
1840 let out = snapshot.join("out.txt").expect("out path");
1841 assert_eq!(
1842 temp_resolver.read_to_string(&out).expect("read").trim(),
1843 "ok"
1844 );
1845 }
1846
1847 #[cfg_attr(
1848 miri,
1849 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1850 )]
1851 #[test]
1852 fn execute_with_result_local_only_creates_no_snapshot() {
1853 let workspace = GuardedPath::tempdir().expect("tempdir");
1854 let workspace_root = workspace.as_guarded_path().clone();
1855 let script_path = workspace_root.join("script.txt").expect("script path");
1856 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1857 .expect("resolver");
1858 resolver
1859 .write_file(&script_path, b"WORKSPACE LOCAL\nWRITE out.txt hi")
1860 .expect("write script");
1861 let opts = Options {
1862 script: ScriptSource::Path(script_path),
1863 shell: false,
1864 dry_run: false,
1865 endpoints: EndpointFlags::default(),
1866 remote_serve: false,
1867 mcp: false,
1868 remotes: Vec::new(),
1869 script_args: Vec::new(),
1870 };
1871 let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1872 assert!(
1873 !result.has_snapshot(),
1874 "WORKSPACE LOCAL-only script must not create a snapshot tempdir"
1875 );
1876 assert!(result.snapshot_path().is_none());
1877 let out = workspace_root.join("out.txt").expect("out path");
1879 let contents = resolver.read_to_string(&out).expect("read out");
1880 assert_eq!(contents.trim(), "hi");
1881 assert_eq!(result.final_cwd.root(), workspace_root.as_path());
1883 }
1884
1885 #[cfg_attr(
1886 miri,
1887 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1888 )]
1889 #[test]
1890 fn execute_with_result_empty_script_creates_no_snapshot() {
1891 let workspace = GuardedPath::tempdir().expect("tempdir");
1892 let workspace_root = workspace.as_guarded_path().clone();
1893 let script_path = workspace_root.join("empty.txt").expect("script path");
1894 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
1895 .expect("resolver");
1896 resolver
1897 .write_file(&script_path, b"")
1898 .expect("write script");
1899 let opts = Options {
1900 script: ScriptSource::Path(script_path),
1901 shell: false,
1902 dry_run: false,
1903 endpoints: EndpointFlags::default(),
1904 remote_serve: false,
1905 mcp: false,
1906 remotes: Vec::new(),
1907 script_args: Vec::new(),
1908 };
1909 let result = execute_with_result(opts, workspace_root.clone()).expect("execute");
1910 assert!(
1911 !result.has_snapshot(),
1912 "empty script must not create a snapshot tempdir"
1913 );
1914 assert_eq!(result.final_cwd, workspace_root);
1915 }
1916
1917 #[cfg_attr(
1918 miri,
1919 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
1920 )]
1921 #[test]
1922 fn execute_for_test_invokes_shell_runner() -> Result<()> {
1923 let workspace = GuardedPath::tempdir()?;
1924 let workspace_root = workspace.as_guarded_path().clone();
1925 let script_path = workspace_root.join("empty.txt")?;
1926 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1927 resolver.write_file(&script_path, b"")?;
1928 let opts = Options {
1929 script: ScriptSource::Path(script_path),
1930 shell: true,
1931 dry_run: false,
1932 endpoints: EndpointFlags::default(),
1933 remote_serve: false,
1934 mcp: false,
1935 remotes: Vec::new(),
1936 script_args: Vec::new(),
1937 };
1938 let called = RefCell::new(None::<(String, String)>);
1939 execute_for_test(opts, workspace_root.clone(), |cwd, workspace| {
1940 called.replace(Some((cwd.display(), workspace.display())));
1941 assert!(
1944 cwd.exists(),
1945 "shell cwd must exist on disk, got {}",
1946 cwd.display()
1947 );
1948 Ok(())
1949 })?;
1950 let seen = called.borrow().clone().expect("shell runner called");
1951 assert_eq!(seen.1, workspace_root.display());
1952 Ok(())
1953 }
1954
1955 #[cfg(feature = "ssh")]
1959 #[cfg_attr(
1960 miri,
1961 ignore = "loopback TCP plus threads plus a Tokio runtime; also GuardedPath::tempdir"
1962 )]
1963 #[test]
1964 fn ssh_feature_serves_and_closes() -> Result<()> {
1965 let workspace = GuardedPath::tempdir()?;
1966 let workspace_root = workspace.as_guarded_path().clone();
1967 let script_path = workspace_root.join("ssh-serve.ox")?;
1968 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
1969 let script = indoc! {"
1970 IMPORT [STD, SSH]
1971 LET $m: SSH_SERVE_INFO = SSH_SERVE(\"cli-ssh-svc\", {username: \"test\", password: \"test123\"})
1972 SSH_CLOSE($m.server)
1973 "};
1974 resolver.write_file(&script_path, script.as_bytes())?;
1975 let opts = Options {
1976 script: ScriptSource::Path(script_path),
1977 shell: false,
1978 dry_run: false,
1979 endpoints: EndpointFlags {
1980 publishes: vec![(
1981 std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
1982 "cli-ssh-svc".to_string(),
1983 )],
1984 ..EndpointFlags::default()
1985 },
1986 remote_serve: false,
1987 mcp: false,
1988 remotes: Vec::new(),
1989 script_args: Vec::new(),
1990 };
1991 execute_with_result(opts, workspace_root)?;
1992 Ok(())
1993 }
1994
1995 #[cfg(feature = "net")]
1999 #[cfg_attr(
2000 miri,
2001 ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
2002 )]
2003 #[test]
2004 fn net_module_listens_and_closes() -> Result<()> {
2005 let workspace = GuardedPath::tempdir()?;
2006 let workspace_root = workspace.as_guarded_path().clone();
2007 let script_path = workspace_root.join("net-listen.ox")?;
2008 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
2009 let script = indoc! {"
2010 IMPORT [STD, NET]
2011 LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
2012 NET_CLOSE($l.listener)
2013 "};
2014 resolver.write_file(&script_path, script.as_bytes())?;
2015 let opts = Options {
2016 script: ScriptSource::Path(script_path),
2017 shell: false,
2018 dry_run: false,
2019 endpoints: EndpointFlags {
2022 publishes: vec![(
2023 std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
2024 "23501".to_string(),
2025 )],
2026 ..EndpointFlags::default()
2027 },
2028 remote_serve: false,
2029 mcp: false,
2030 remotes: Vec::new(),
2031 script_args: Vec::new(),
2032 };
2033 execute_with_result(opts, workspace_root)?;
2034 Ok(())
2035 }
2036
2037 #[cfg(feature = "net")]
2041 #[cfg_attr(
2042 miri,
2043 ignore = "loopback TCP plus GuardedPath::tempdir; blocked under Miri isolation"
2044 )]
2045 #[test]
2046 fn net_port_addr_observe_publish_mapping() -> Result<()> {
2047 let workspace = GuardedPath::tempdir()?;
2048 let workspace_root = workspace.as_guarded_path().clone();
2049 let script_path = workspace_root.join("net-port.ox")?;
2050 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
2051 let script = indoc! {"
2052 IMPORT [STD, NET]
2053 LET $port: INT = NET_PORT(\"routed-svc\")
2054 WRITE port.txt \"{{ $port }}\"
2055 LET $addr: STRING = NET_ADDR(\"routed-svc\")
2056 WRITE addr.txt \"{{ $addr }}\"
2057 "};
2058 resolver.write_file(&script_path, script.as_bytes())?;
2059 let opts = Options {
2060 script: ScriptSource::Path(script_path),
2061 shell: false,
2062 dry_run: false,
2063 endpoints: EndpointFlags {
2064 publishes: vec![(
2065 std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
2066 "routed-svc".to_string(),
2067 )],
2068 ..EndpointFlags::default()
2069 },
2070 remote_serve: false,
2071 mcp: false,
2072 remotes: Vec::new(),
2073 script_args: Vec::new(),
2074 };
2075 let result = execute_with_result(opts, workspace_root)?;
2076 let snapshot = result
2077 .snapshot_path()
2078 .expect("WRITE materializes the snapshot");
2079 let snapshot_resolver = PathResolver::new(snapshot.root(), snapshot.root())?;
2080 let port_path = snapshot.join("port.txt")?;
2081 let port_text = snapshot_resolver.read_to_string(&port_path)?;
2082 let port: u16 = port_text
2083 .trim()
2084 .parse()
2085 .map_err(|_| anyhow::anyhow!("expected a resolved port, got {port_text:?}"))?;
2086 assert_ne!(port, 0, "ephemeral outer port must resolve");
2087 let addr_path = snapshot.join("addr.txt")?;
2088 let addr_text = snapshot_resolver.read_to_string(&addr_path)?;
2089 assert!(
2090 addr_text.trim().ends_with(&format!(":{port}")),
2091 "dial string must carry the resolved port, got {addr_text:?}"
2092 );
2093 Ok(())
2094 }
2095
2096 #[cfg(not(feature = "ssh"))]
2099 #[cfg_attr(
2100 miri,
2101 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
2102 )]
2103 #[test]
2104 fn ssh_scripts_rejected_without_feature() -> Result<()> {
2105 let workspace = GuardedPath::tempdir()?;
2106 let workspace_root = workspace.as_guarded_path().clone();
2107 let script_path = workspace_root.join("ssh-serve.ox")?;
2108 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
2109 let script = indoc! {"
2110 IMPORT [STD, SSH]
2111 LET $m: SSH_SERVE_INFO = SSH_SERVE(\"23301\", {username: \"test\", password: \"test123\"})
2112 SSH_CLOSE($m.server)
2113 "};
2114 resolver.write_file(&script_path, script.as_bytes())?;
2115 let opts = Options {
2116 script: ScriptSource::Path(script_path),
2117 shell: false,
2118 dry_run: false,
2119 endpoints: EndpointFlags::default(),
2120 remote_serve: false,
2121 mcp: false,
2122 remotes: Vec::new(),
2123 script_args: Vec::new(),
2124 };
2125 let err = match execute_with_result(opts, workspace_root) {
2126 Ok(_) => panic!("SSH names must be unknown without the feature"),
2127 Err(err) => err,
2128 };
2129 assert!(err.to_string().contains("SSH"), "{err}");
2130 assert_eq!(err.key(), "cli.module_unlinked", "{err}");
2131 Ok(())
2132 }
2133
2134 #[cfg(not(feature = "net"))]
2138 #[cfg_attr(
2139 miri,
2140 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
2141 )]
2142 #[test]
2143 fn net_flags_rejected_without_feature() {
2144 let workspace = GuardedPath::tempdir().expect("tempdir");
2145 for args in [
2146 vec!["--listen", "0.0.0.0:2251", "-"],
2147 vec!["-p", "2222:2251", "-"],
2148 vec!["--listen=0.0.0.0:2251", "-"],
2149 ] {
2150 let mut args = args.into_iter().map(str::to_string);
2151 let err = Options::parse(&mut args, workspace.as_guarded_path())
2152 .expect_err("endpoint flag must fail without net");
2153 assert!(err.to_string().contains("`net` feature"), "{err:?}");
2154 assert_eq!(err.key(), "cli.feature_required");
2156 }
2157 let mut args = vec!["--offline".to_string(), "-".to_string()].into_iter();
2158 let opts = Options::parse(&mut args, workspace.as_guarded_path()).expect("parse");
2159 assert!(opts.endpoints.offline);
2160 }
2161
2162 #[cfg(not(feature = "net"))]
2165 #[cfg_attr(
2166 miri,
2167 ignore = "GuardedPath::tempdir relies on OS tempdirs; blocked under Miri isolation"
2168 )]
2169 #[test]
2170 fn net_scripts_rejected_without_feature() -> Result<()> {
2171 let workspace = GuardedPath::tempdir()?;
2172 let workspace_root = workspace.as_guarded_path().clone();
2173 let script_path = workspace_root.join("net-listen.ox")?;
2174 let resolver = PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
2175 let script = indoc! {"
2176 IMPORT [STD, NET]
2177 LET $l: NET_LISTEN_INFO = NET_LISTEN(\"23501\", {})
2178 LET $body: STRING = NET_FETCH(\"https://example.com/x\")
2179 NET_CLOSE($l.listener)
2180 "};
2181 resolver.write_file(&script_path, script.as_bytes())?;
2182 let opts = Options {
2183 script: ScriptSource::Path(script_path),
2184 shell: false,
2185 dry_run: false,
2186 endpoints: EndpointFlags::default(),
2187 remote_serve: false,
2188 mcp: false,
2189 remotes: Vec::new(),
2190 script_args: Vec::new(),
2191 };
2192 let err = match execute_with_result(opts, workspace_root) {
2193 Ok(_) => panic!("NET names must be unknown without the feature"),
2194 Err(err) => err,
2195 };
2196 assert!(err.to_string().contains("NET"), "{err}");
2197 assert_eq!(err.key(), "cli.module_unlinked", "{err}");
2199 Ok(())
2200 }
2201
2202 #[test]
2206 fn imports_module_ignores_comments_strings_and_other_brackets() {
2207 use oxdock_parser::lex_str;
2208 let toks = lex_str("IMPORT [STD, NET]\n").expect("lex");
2209 assert!(super::imports_module(&toks, "NET"));
2210 assert!(!super::imports_module(&toks, "SSH"));
2211 let toks = lex_str("IF true {\nIMPORT [SSH]\n}\n").expect("lex");
2212 assert!(super::imports_module(&toks, "SSH"));
2213 let toks = lex_str("IMPORT [\"./a.oxdock\" AS LIB]\n").expect("lex");
2214 assert!(!super::imports_module(&toks, "NET"));
2215 let toks = lex_str("IMPORT [\"./NET.oxdock\" AS LIB]\n").expect("lex");
2217 assert!(!super::imports_module(&toks, "NET"));
2218 let toks = lex_str("// IMPORT [NET]\nECHO hi\n").expect("lex");
2219 assert!(!super::imports_module(&toks, "NET"));
2220 let toks = lex_str("ECHO \"IMPORT [NET]\"\n").expect("lex");
2221 assert!(!super::imports_module(&toks, "NET"));
2222 let toks = lex_str("WITH_IO [stdout=$p] ECHO hi\n").expect("lex");
2223 assert!(!super::imports_module(&toks, "NET"));
2224 }
2225
2226 #[cfg(not(feature = "net"))]
2230 #[test]
2231 fn unlinked_module_error_needs_a_real_import() {
2232 let err =
2233 super::unlinked_module_error("IMPORT [STD, NET]\n").expect("real import must map");
2234 assert_eq!(err.key(), "cli.module_unlinked");
2235 assert!(super::unlinked_module_error("// IMPORT [NET]\nECHO hi\n").is_none());
2236 assert!(super::unlinked_module_error("ECHO \"IMPORT [NET]\"\n").is_none());
2237 assert!(super::unlinked_module_error("ECHO hi\n").is_none());
2238 }
2239
2240 #[test]
2241 fn process_exit_code_relays_exit_requests() {
2242 use std::sync::Arc as StdArc;
2243 let exit = oxdock_diagnostics::Diagnostic::new(
2244 "t.exit",
2245 "exit 3".to_string(),
2246 oxdock_diagnostics::Diagnostic::make_fields(&[]),
2247 )
2248 .with_source(StdArc::new(ExitRequest::new(3)));
2249 assert_eq!(process_exit_code(&exit), 3);
2250 let relayed = oxdock_diagnostics::Diagnostic::new(
2251 "t.exit",
2252 "exit 3".to_string(),
2253 oxdock_diagnostics::Diagnostic::make_fields(&[]),
2254 )
2255 .with_source(StdArc::new(ExitRequest::new(3)))
2256 .with_contexts(vec!["REMOTE 'prod' exited with code 3".to_string()]);
2257 assert_eq!(process_exit_code(&relayed), 3);
2258 let keyed = oxdock_core::exec::diagnostics::eval_exit_requested(3);
2259 assert_eq!(process_exit_code(&keyed), 3);
2260 let keyed_wrapped = oxdock_core::exec::diagnostics::eval_exit_requested(3)
2261 .with_contexts(vec!["step 1".to_string()]);
2262 assert_eq!(process_exit_code(&keyed_wrapped), 3);
2263 assert_eq!(process_exit_code(&errors::shell_needs_tty()), 1);
2264 assert_eq!(
2265 process_exit_code(
2266 &oxdock_diagnostics::Diagnostic::new(
2267 "t.exit",
2268 "exit 300".to_string(),
2269 oxdock_diagnostics::Diagnostic::make_fields(&[]),
2270 )
2271 .with_source(StdArc::new(ExitRequest::new(300)))
2272 ),
2273 255,
2274 "codes clamp to the portable range"
2275 );
2276 assert_eq!(
2277 process_exit_code(
2278 &oxdock_diagnostics::Diagnostic::new(
2279 "t.exit",
2280 "exit -1".to_string(),
2281 oxdock_diagnostics::Diagnostic::make_fields(&[]),
2282 )
2283 .with_source(StdArc::new(ExitRequest::new(-1)))
2284 ),
2285 0,
2286 "negative codes clamp to zero"
2287 );
2288 }
2289}
2290
2291#[cfg(all(test, windows))]
2292mod windows_shell_tests {
2293 use super::*;
2294
2295 #[test]
2296 fn command_path_strips_verbatim_prefix() -> DiagnosticResult<()> {
2297 let temp = GuardedPath::tempdir()?;
2298 let converted = oxdock_fs::command_path(temp.as_guarded_path());
2299 let as_str = converted.as_ref().display().to_string();
2300 assert!(
2301 !as_str.starts_with(r"\\?\"),
2302 "expected non-verbatim path, got {as_str}"
2303 );
2304 Ok(())
2305 }
2306}