1extern crate self as oxdock_core;
2
3pub mod exec;
4pub mod pipeline;
5pub use exec::*;
6pub use oxdock_parser::{
7 Arg, ArgType, CommandMeta, CommandSpec, Example, SCRIPT_MODULE_NAME, STD_MODULE_NAME, StepKind,
8 all_metadata, all_structural_metadata, lower_command,
9};
10pub use oxdock_process::ProcessManager;
11
12define_pipeline! {
13 StepKind::Run(..) => exec::dispatch_run,
14 StepKind::RunExec { .. } => exec::dispatch_run_exec,
15 StepKind::AsyncBlock { .. } => exec::dispatch_async_block,
16 StepKind::Echo(..) => exec::dispatch_echo,
17 StepKind::Workdir(..) => exec::dispatch_workdir,
18 StepKind::Workspace(..) => exec::dispatch_workspace,
19 StepKind::RemoteBlock { .. } => exec::dispatch_remote,
20 StepKind::Env { .. } => exec::dispatch_env,
21 StepKind::Copy { .. } => exec::dispatch_copy,
22 StepKind::CopyGit { .. } => exec::dispatch_copy_git,
23 StepKind::Archive { .. } => exec::dispatch_archive,
24 StepKind::Unarchive { .. } => exec::dispatch_unarchive,
25 StepKind::Symlink { .. } => exec::dispatch_symlink,
26 StepKind::Mkdir(..) => exec::dispatch_mkdir,
27 StepKind::Install { .. } => exec::dispatch_install,
28 StepKind::Ls(..) => exec::dispatch_ls,
29 StepKind::Read(..) => exec::dispatch_read,
30 StepKind::ReadLine { .. } => exec::dispatch_read_line,
31 StepKind::Prompt { .. } => exec::dispatch_prompt,
32 StepKind::Write { .. } => exec::dispatch_write,
33 StepKind::Append { .. } => exec::dispatch_append,
34 StepKind::Remove { .. } => exec::dispatch_remove,
35 StepKind::Expand { .. } => exec::dispatch_expand,
36 StepKind::AssertEq { .. } => exec::dispatch_assert_eq,
37 StepKind::AssertContains { .. } => exec::dispatch_assert_contains,
38 StepKind::Exit(..) => exec::dispatch_exit,
39 StepKind::AssignAsync { .. } => exec::dispatch_assign_async_step,
40 StepKind::Set { .. } => exec::dispatch_set,
41 StepKind::Await { .. } => exec::dispatch_await_step,
42 StepKind::AssignCapture { .. } => exec::dispatch_assign_capture_step,
43 StepKind::AwaitCapture { .. } => exec::dispatch_await_capture_step,
44 StepKind::Cancel { .. } => exec::dispatch_cancel_step,
45 StepKind::Timeout { .. } => exec::dispatch_timeout_step,
46 StepKind::Isolated { .. } => exec::dispatch_isolated_step,
47 StepKind::IsolatedInheritEnv { .. } => exec::dispatch_isolated_inherit_env,
48 StepKind::Sleep { .. } => exec::dispatch_sleep_step,
49 StepKind::ListAppend { .. } => exec::dispatch_push_into_step,
50 StepKind::FuncDef { .. } => exec::dispatch_func_def,
51 StepKind::ImportFile { .. } => exec::dispatch_import_file,
52 StepKind::ImportFuncs { .. } => exec::dispatch_import_funcs,
53 StepKind::Call { .. } => exec::dispatch_call,
54 StepKind::Return { .. } => exec::dispatch_return,
55 StepKind::While { .. } => exec::dispatch_while_loop,
56 StepKind::Break => exec::dispatch_break,
57 StepKind::Continue => exec::dispatch_continue,
58}
59
60pub fn parse_script(input: &str) -> anyhow::Result<Vec<oxdock_parser::Step>> {
67 parse_script_with_modules(input, std_module_table())
68}
69
70pub fn parse_script_with_modules(
77 input: &str,
78 modules: oxdock_parser::ModuleTable,
79) -> anyhow::Result<Vec<oxdock_parser::Step>> {
80 let mut reserved = builtin_function_names();
81 reserved.extend(modules.reserved_base_names());
82 Ok(oxdock_parser::parse_script_with_modules(
83 input,
84 lower_command,
85 reserved,
86 modules,
87 )?)
88}
89
90pub fn parse_script_with_modules_and_exports(
93 input: &str,
94 modules: oxdock_parser::ModuleTable,
95) -> anyhow::Result<oxdock_parser::ParsedScript> {
96 let mut reserved = builtin_function_names();
97 reserved.extend(modules.reserved_base_names());
98 Ok(oxdock_parser::parse_script_with_modules_and_exports(
99 input,
100 lower_command,
101 reserved,
102 modules,
103 )?)
104}
105
106#[cfg(test)]
107mod tests {
108 use super::*;
109 use indoc::indoc;
110 use oxdock_fs::{
111 GuardedPath, GuardedTempDir, PathResolver, env as oxdock_env, to_forward_slashes,
112 };
113 use std::time::Instant;
114
115 fn guard_root(temp: &GuardedTempDir) -> GuardedPath {
116 temp.as_guarded_path().clone()
117 }
118
119 fn read_trimmed(path: &GuardedPath) -> String {
120 let resolver = PathResolver::new(path.root(), path.root()).unwrap();
121 resolver
122 .read_to_string(path)
123 .unwrap_or_default()
124 .trim()
125 .to_string()
126 }
127
128 fn create_dirs(path: &GuardedPath) {
129 let resolver = PathResolver::new(path.root(), path.root()).unwrap();
130 resolver.create_dir_all(path).unwrap();
131 }
132
133 fn exists(root: &GuardedPath, rel: &str) -> bool {
134 root.join(rel).map(|p| p.exists()).unwrap_or(false)
135 }
136
137 #[test]
138 fn run_isolates_cargo_target_dir_from_workspace() {
139 let temp = GuardedPath::tempdir().unwrap();
140 let root = guard_root(&temp);
141
142 #[allow(clippy::disallowed_macros)]
143 let cmd = if cfg!(windows) {
144 "echo %CARGO_TARGET_DIR% > seen.txt"
145 } else {
146 "printf %s \"$CARGO_TARGET_DIR\" > seen.txt"
147 };
148
149 let steps = parse_script(&format!("RUN {cmd}")).unwrap();
150
151 run_steps(&root, &steps).unwrap();
152
153 let seen = read_trimmed(&root.join("seen.txt").unwrap());
154 let legacy = root.join(".cargo-target").unwrap();
155
156 assert_ne!(
157 seen.trim(),
158 legacy.display().to_string(),
159 "CARGO_TARGET_DIR must not target the workspace tree"
160 );
161 let normalized = seen.trim().replace('\\', "/");
162 assert!(
163 normalized.ends_with("/target") && normalized.contains("oxdock-"),
164 "CARGO_TARGET_DIR must point at the isolated scratch target dir, got {seen:?}"
165 );
166 }
167
168 #[test]
169 fn lazy_snapshot_run_materializes_but_local_run_does_not() {
170 let temp = GuardedPath::tempdir().unwrap();
171 let root = guard_root(&temp);
172
173 let steps = parse_script("RUN echo hi").unwrap();
176 let output = run_steps_with_lazy_snapshot(&root, &steps, ExecIo::new()).unwrap();
177 assert!(
178 output.snapshot.is_materialized(),
179 "snapshot-rooted RUN must materialize the snapshot"
180 );
181
182 let steps = parse_script(indoc! {r#"
184 WORKSPACE LOCAL
185 RUN echo hi
186 "#})
187 .unwrap();
188 let output = run_steps_with_lazy_snapshot(&root, &steps, ExecIo::new()).unwrap();
189 assert!(
190 !output.snapshot.is_materialized(),
191 "LOCAL-rooted RUN must never materialize the snapshot"
192 );
193 }
194
195 #[test]
196 fn lazy_empty_run_creates_nothing() {
197 let temp = GuardedPath::tempdir().unwrap();
198 let root = guard_root(&temp);
199
200 let output = run_steps_with_lazy_snapshot(&root, &[], ExecIo::new()).unwrap();
201 assert!(!output.snapshot.is_materialized());
202 assert!(output.snapshot.get().is_none());
203 }
204
205 #[test]
206 fn lazy_local_echo_assert_failure_never_materializes_snapshot() {
207 let temp = GuardedPath::tempdir().unwrap();
208 let root = guard_root(&temp);
209
210 let script = indoc!(
211 r#"
212 WORKSPACE LOCAL
213 ECHO playground pid is 41067
214 ASSERT_CONTAINS stdout "playground pid i!!"
215 "#
216 );
217 let steps = parse_script(script).unwrap();
218
219 let mut resolver = PathResolver::new_lazy(root.clone()).unwrap();
223 resolver.set_workspace_root(root.clone());
224 let snapshot = resolver.snapshot_handle();
225 let fs: Box<dyn oxdock_fs::WorkspaceFs> = Box::new(resolver);
226 let result = run_steps_with_manager(
227 fs,
228 &steps,
229 oxdock_process::default_process_manager(),
230 ExecIo::new(),
231 );
232 assert!(result.is_err(), "mismatched ASSERT_CONTAINS must fail");
233 let err = result.err().unwrap();
234 assert!(!snapshot.is_materialized());
235 assert!(snapshot.get().is_none());
236
237 let enriched = enrich_lazy_error(&snapshot, &root, err);
238 let msg = enriched.to_string();
239 assert!(
240 msg.contains("did not contain 'playground pid i!!'"),
241 "{msg}"
242 );
243 assert!(msg.contains("never materialized"), "{msg}");
244 assert!(!msg.contains("filesystem snapshot (root"), "{msg}");
245 }
246
247 #[test]
248 fn lazy_local_echo_assert_success_leaves_snapshot_pending() {
249 let temp = GuardedPath::tempdir().unwrap();
250 let root = guard_root(&temp);
251
252 let script = indoc!(
253 r#"
254 WORKSPACE LOCAL
255 ECHO playground pid is 41067
256 ASSERT_CONTAINS stdout "playground pid is 41067"
257 "#
258 );
259 let steps = parse_script(script).unwrap();
260
261 let output = run_steps_with_lazy_snapshot(&root, &steps, ExecIo::new()).unwrap();
262 assert!(!output.snapshot.is_materialized());
263 assert!(output.snapshot.get().is_none());
264 }
265
266 #[test]
267 fn lazy_default_mode_echo_assert_failure_keeps_snapshot_pending() {
268 let temp = GuardedPath::tempdir().unwrap();
269 let root = guard_root(&temp);
270
271 let script = indoc!(
275 r#"
276 ECHO playground pid is 41067
277 ASSERT_CONTAINS stdout "playground pid i!!"
278 "#
279 );
280 let steps = parse_script(script).unwrap();
281
282 let mut resolver = PathResolver::new_lazy(root.clone()).unwrap();
286 resolver.set_workspace_root(root.clone());
287 let snapshot = resolver.snapshot_handle();
288 let fs: Box<dyn oxdock_fs::WorkspaceFs> = Box::new(resolver);
289 let result = run_steps_with_manager(
290 fs,
291 &steps,
292 oxdock_process::default_process_manager(),
293 ExecIo::new(),
294 );
295 assert!(result.is_err(), "mismatched ASSERT_CONTAINS must fail");
296 let err = result.err().unwrap();
297 assert!(!snapshot.is_materialized());
298 assert!(snapshot.get().is_none());
299
300 let enriched = enrich_lazy_error(&snapshot, &root, err);
301 let msg = enriched.to_string();
302 assert!(
303 msg.contains("did not contain 'playground pid i!!'"),
304 "{msg}"
305 );
306 assert!(msg.contains("never materialized"), "{msg}");
307 assert!(!msg.contains("filesystem snapshot (root"), "{msg}");
308 }
309
310 #[test]
311 fn lazy_default_mode_write_materializes_snapshot() {
312 let temp = GuardedPath::tempdir().unwrap();
313 let root = guard_root(&temp);
314
315 let steps = parse_script("WRITE \"snap.txt\" \"snap\"").unwrap();
318
319 let output = run_steps_with_lazy_snapshot(&root, &steps, ExecIo::new()).unwrap();
320 assert!(output.snapshot.is_materialized());
321 let snapshot_root = output.snapshot.get().expect("snapshot must be published");
322 assert!(
323 exists(snapshot_root, "snap.txt"),
324 "WRITE must land inside the materialized snapshot"
325 );
326 }
327
328 #[test]
329 fn guard_skips_when_env_missing() {
330 let temp = GuardedPath::tempdir().unwrap();
331 let root = guard_root(&temp);
332
333 let guard_var = oxdock_env::oxdock::GUARD_TEST_TOKEN_UNSET;
337 let script = format!(
338 indoc!(
339 r#"
340 INHERIT_ENV [{guard}]
341 [env:{guard}] WRITE "skipped.txt" "hi"
342 WRITE "kept.txt" "ok"
343 "#
344 ),
345 guard = guard_var
346 );
347 let steps = crate::parse_script(&script).unwrap();
348
349 run_steps(&root, &steps).unwrap();
350
351 assert!(
352 !exists(&root, "skipped.txt"),
353 "guarded WRITE should be skipped"
354 );
355 assert!(exists(&root, "kept.txt"), "unguarded WRITE should run");
356 }
357
358 #[test]
359 fn guard_sees_env_set_by_env_step() {
360 let temp = GuardedPath::tempdir().unwrap();
361 let root = guard_root(&temp);
362
363 let script = indoc!(
364 r#"
365 ENV FOO="1"
366 [env:FOO] WRITE "hit.txt" "yes"
367 WRITE "always.txt" "ok"
368 "#
369 );
370 let steps = crate::parse_script(script).unwrap();
371
372 run_steps(&root, &steps).unwrap();
373
374 assert!(
375 exists(&root, "hit.txt"),
376 "guarded WRITE should run after ENV sets variable"
377 );
378 assert!(exists(&root, "always.txt"), "unguarded WRITE should run");
379 }
380
381 #[test]
382 fn echo_runs_and_allows_subsequent_steps() {
383 let temp = GuardedPath::tempdir().unwrap();
384 let root = guard_root(&temp);
385
386 let script = indoc!(
387 r#"
388 ECHO "Hello, world"
389 WRITE "always.txt" "ok"
390 "#
391 );
392 let steps = crate::parse_script(script).unwrap();
393
394 run_steps(&root, &steps).unwrap();
395
396 assert!(exists(&root, "always.txt"), "WRITE after ECHO should run");
397 }
398
399 #[test]
400 fn guard_on_previous_line_applies_to_next_command() {
401 let temp = GuardedPath::tempdir().unwrap();
402 let root = guard_root(&temp);
403
404 let script = indoc!(
405 r#"
406 ENV FOO="1"
407 [env:FOO]
408 WRITE "hit.txt" "yes"
409 WRITE "always.txt" "ok"
410 "#
411 );
412 let steps = crate::parse_script(script).unwrap();
413
414 run_steps(&root, &steps).unwrap();
415
416 assert!(
417 exists(&root, "hit.txt"),
418 "guarded WRITE on next line should run"
419 );
420 assert!(exists(&root, "always.txt"), "unguarded WRITE should run");
421 }
422
423 #[test]
424 fn guard_respects_platform_negation() {
425 let temp = GuardedPath::tempdir().unwrap();
426 let root = guard_root(&temp);
427
428 let script = indoc!(
429 r#"
430 [not(family:unix)] WRITE "platform.txt" "hi"
431 WRITE "always.txt" "ok"
432 "#
433 );
434 let steps = crate::parse_script(script).unwrap();
435
436 run_steps(&root, &steps).unwrap();
437
438 #[allow(clippy::disallowed_macros)]
439 let expect_skipped = cfg!(unix);
440 assert_eq!(
441 exists(&root, "platform.txt"),
442 !expect_skipped,
443 "platform guard should skip on Unix and run elsewhere"
444 );
445 assert!(exists(&root, "always.txt"), "unguarded WRITE should run");
446 }
447
448 #[test]
449 fn guard_block_env_scope_restores_after_exit() {
450 let temp = GuardedPath::tempdir().unwrap();
451 let root = guard_root(&temp);
452
453 let script = indoc!(
458 r#"
459 ENV RUN="1"
460 ENV INNER=""
461 [env:RUN] {
462 ENV INNER="1"
463 WRITE "scoped.txt" "hit"
464 }
465 [env:INNER] WRITE "leak.txt" "nope"
466 "#
467 );
468 let steps = crate::parse_script(script).unwrap();
469
470 run_steps(&root, &steps).unwrap();
471
472 assert!(exists(&root, "scoped.txt"), "block should run");
473 assert!(
474 !exists(&root, "leak.txt"),
475 "env set inside block must not leak outward"
476 );
477 }
478
479 #[test]
480 fn guard_block_workdir_scope_restores_after_exit() {
481 let temp = GuardedPath::tempdir().unwrap();
482 let root = guard_root(&temp);
483
484 let script = indoc!(
485 r#"
486 MKDIR "nested"
487 ENV RUN="1"
488 [env:RUN] {
489 WORKDIR "nested"
490 WRITE "inside.txt" "ok"
491 }
492 WRITE "outside.txt" "root"
493 "#
494 );
495 let steps = crate::parse_script(script).unwrap();
496
497 run_steps(&root, &steps).unwrap();
498
499 assert!(
500 exists(&root, "nested/inside.txt"),
501 "inside write should land in nested dir"
502 );
503 assert!(
504 exists(&root, "outside.txt"),
505 "workdir should reset after block exits"
506 );
507 assert!(
508 !exists(&root, "nested/outside.txt"),
509 "writes after block should not stay scoped"
510 );
511 }
512
513 #[test]
514 fn workspace_scope_restores_after_guard_block() {
515 let snapshot = GuardedPath::tempdir().unwrap();
516 let local = GuardedPath::tempdir().unwrap();
517 let snapshot_root = guard_root(&snapshot);
518 let local_root = guard_root(&local);
519
520 let script = indoc!(
521 r#"
522 ENV RUN="1"
523 [env:RUN] {
524 WORKSPACE LOCAL
525 WRITE "local_only.txt" "inside"
526 }
527 WRITE "snapshot_only.txt" "outside"
528 "#
529 );
530 let steps = crate::parse_script(script).unwrap();
531
532 run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
533
534 assert!(
535 local_root.join("local_only.txt").unwrap().exists(),
536 "workspace switch inside block should affect local root"
537 );
538 assert!(
539 snapshot_root.join("snapshot_only.txt").unwrap().exists(),
540 "writes after block must target snapshot again"
541 );
542 assert!(
543 !local_root.join("snapshot_only.txt").unwrap().exists(),
544 "workspace should reset after guard block exits"
545 );
546 }
547
548 #[test]
549 fn guard_matches_profile_env() {
550 let temp = GuardedPath::tempdir().unwrap();
552 let root = guard_root(&temp);
553
554 let profile = std::env::var(oxdock_env::cargo::build::PROFILE)
555 .unwrap_or_else(|_| "debug".to_string());
556 let script = format!(
557 indoc!(
558 r#"
559 ENV PROFILE={0}
560 [eq(env:PROFILE, {0})] WRITE "hit.txt" "yes"
561 [ne(env:PROFILE, {0})] WRITE "miss.txt" "no"
562 "#
563 ),
564 profile
565 );
566
567 let steps = crate::parse_script(&script).unwrap();
568 run_steps(&root, &steps).unwrap();
569
570 assert!(
571 exists(&root, "hit.txt"),
572 "PROFILE-matching guard should run"
573 );
574 assert!(
575 !exists(&root, "miss.txt"),
576 "PROFILE inequality guard should skip for current profile"
577 );
578 }
579
580 #[test]
581 fn multiple_guards_all_must_pass() {
582 let temp = GuardedPath::tempdir().unwrap();
583 let root = guard_root(&temp);
584
585 let key = oxdock_env::oxdock::MULTI_GUARD_TEST_PASS;
586
587 let script = format!(
588 indoc!(
589 r#"
590 ENV {k}=ok
591 [env:{k},eq(env:{k}, ok)] WRITE "hit.txt" "yes"
592 WRITE "always.txt" "ok"
593 "#
594 ),
595 k = key
596 );
597 let steps = crate::parse_script(&script).unwrap();
598 run_steps(&root, &steps).unwrap();
599
600 assert!(
601 exists(&root, "hit.txt"),
602 "guarded step should run when all guards pass"
603 );
604 assert!(exists(&root, "always.txt"), "unguarded step should run");
605 }
606
607 #[test]
608 fn multiple_guards_skip_when_one_fails() {
609 let temp = GuardedPath::tempdir().unwrap();
610 let root = guard_root(&temp);
611
612 let key = oxdock_env::oxdock::MULTI_GUARD_TEST_FAIL;
613
614 let script = format!(
615 indoc!(
616 r#"
617 ENV {k}=ok
618 [env:{k},ne(env:{k}, ok)] WRITE "miss.txt" "yes"
619 WRITE "always.txt" "ok"
620 "#
621 ),
622 k = key
623 );
624 let steps = crate::parse_script(&script).unwrap();
625 run_steps(&root, &steps).unwrap();
626
627 assert!(
628 !exists(&root, "miss.txt"),
629 "guarded step should skip when any guard fails"
630 );
631 assert!(exists(&root, "always.txt"), "unguarded step should run");
632 }
633
634 #[cfg_attr(
635 miri,
636 ignore = "stdout streaming not supported for background command under Miri"
637 )]
638 #[test]
639 fn async_exits_success_and_stops_pipeline() {
640 let temp = GuardedPath::tempdir().unwrap();
641 let root = guard_root(&temp);
642
643 let script = indoc! {
645 r#"
646 [family:unix] ASYNC RUN "sleep 0.05"
647 [family:windows] ASYNC RUN "ping -n 1 127.0.0.1"
648 "#
649 };
650 let steps = crate::parse_script(script).unwrap();
651 let res = run_steps(&root, &steps);
652 assert!(res.is_ok(), "ASYNC success should allow clean exit");
653 }
654
655 #[cfg_attr(
656 miri,
657 ignore = "stdout streaming not supported for background command under Miri"
658 )]
659 #[test]
660 fn async_failure_bubbles_status() {
661 let temp = GuardedPath::tempdir().unwrap();
662 let root = guard_root(&temp);
663
664 let script = indoc! {
665 r#"
666 [family:unix] ASYNC RUN "sleep 0.05; exit 7"
667 [family:windows] ASYNC RUN "exit 7"
668 "#
669 };
670 let steps = crate::parse_script(script).unwrap();
671 let err = run_steps(&root, &steps).unwrap_err();
672 let msg = err.to_string();
673 assert!(
674 msg.contains("ASYNC process exited with status")
675 || msg.contains("exit status: 7")
676 || msg.contains("exit code: 7"),
677 "should surface failing ASYNC exit code"
678 );
679 }
680
681 #[cfg_attr(
682 miri,
683 ignore = "timing-sensitive background process test is unreliable under Miri"
684 )]
685 #[test]
686 fn async_multiple_stops_on_first_exit_and_does_not_block_steps() {
687 let temp = GuardedPath::tempdir().unwrap();
688 let root = guard_root(&temp);
689
690 let script = indoc! {
691 r#"
692 [family:unix] ASYNC RUN "sleep 0.2; echo one > one.txt"
693 [family:windows] ASYNC RUN "ping -n 2 127.0.0.1 > NUL & echo one > one.txt"
694 [family:unix] ASYNC RUN "sleep 0.5; echo two > two.txt"
695 [family:windows] ASYNC RUN "ping -n 3 127.0.0.1 > NUL & echo two > two.txt"
696 WRITE "done.txt" "ok"
697 "#
698 };
699
700 let steps = crate::parse_script(script).unwrap();
701 let start = Instant::now();
702 let res = run_steps(&root, &steps);
703 let elapsed = start.elapsed();
704
705 assert!(res.is_ok(), "ASYNC success should allow clean exit");
706 assert!(
707 exists(&root, "done.txt"),
708 "foreground step should run after spawning backgrounds"
709 );
710 assert!(
711 exists(&root, "one.txt"),
712 "first background should finish and emit output"
713 );
714 assert!(
717 exists(&root, "two.txt"),
718 "second background should finish (poll-all waits for all)"
719 );
720
721 #[allow(clippy::disallowed_macros)]
724 let (lower, upper) = if cfg!(windows) {
725 (0.9, 3.0)
726 } else {
727 (0.15, 0.8)
728 };
729 assert!(
730 elapsed.as_secs_f32() < upper && elapsed.as_secs_f32() > lower,
731 "should wait for both backgrounds; got {elapsed:?}"
732 );
733 }
734
735 #[cfg_attr(
736 miri,
737 ignore = "timing-sensitive background process test is unreliable under Miri"
738 )]
739 #[test]
740 fn background_killed_when_unrelated_step_fails() {
741 let temp = GuardedPath::tempdir().unwrap();
742 let root = guard_root(&temp);
743
744 let script = indoc! {
745 r#"
746 [family:unix] ASYNC RUN "sleep 30; echo late > late.txt"
747 [family:windows] ASYNC RUN "ping -n 31 127.0.0.1 > NUL & echo late > late.txt"
748 RUN "__oxdock_missing_command_xyz__"
749 "#
750 };
751
752 let steps = crate::parse_script(script).unwrap();
753 let start = Instant::now();
754 assert!(
755 run_steps(&root, &steps).is_err(),
756 "pipeline should fail on the missing command"
757 );
758 assert!(
772 !exists(&root, "late.txt"),
773 "abandoned background writer must be killed by Drop teardown"
774 );
775 assert!(
779 start.elapsed() < std::time::Duration::from_secs(25),
780 "teardown must end the tree promptly, took {:?}",
781 start.elapsed()
782 );
783 }
784
785 #[cfg_attr(
786 miri,
787 ignore = "stdout streaming not supported for background command under Miri"
788 )]
789 #[test]
790 fn exit_terminates_backgrounds_and_returns_code() {
791 let temp = GuardedPath::tempdir().unwrap();
792 let root = guard_root(&temp);
793
794 let script = indoc! {
795 r#"
796 [family:unix] ASYNC RUN "sleep 30; echo late > late.txt"
797 [family:windows] ASYNC RUN "ping -n 31 127.0.0.1 > NUL & echo late > late.txt"
798 EXIT 5
799 "#
800 };
801
802 let steps = crate::parse_script(script).unwrap();
803 let err = run_steps(&root, &steps).unwrap_err();
804 let msg = err.to_string();
805 assert!(msg.contains("EXIT requested with code 5"));
806 assert!(
807 !exists(&root, "late.txt"),
808 "background process should be killed when EXIT is hit"
809 );
810 }
811
812 #[test]
813 #[cfg_attr(
814 miri,
815 ignore = "EXIT joins real background threads; timing-sensitive under Miri"
816 )]
817 fn exit_inside_nested_block_reports_code_and_kills_backgrounds() {
818 let temp = GuardedPath::tempdir().unwrap();
819 let root = guard_root(&temp);
820
821 let script = indoc! {
822 r#"
823 ASYNC {
824 SLEEP 30s
825 }
826 [bool:true] {
827 EXIT 5
828 }
829 "#
830 };
831
832 let steps = crate::parse_script(script).unwrap();
833 let start = std::time::Instant::now();
834 let err = run_steps(&root, &steps).unwrap_err();
835 assert!(
836 err.to_string().contains("EXIT requested with code 5"),
837 "nested EXIT must report its code: {err}"
838 );
839 assert!(
840 start.elapsed() < std::time::Duration::from_secs(10),
841 "nested EXIT must kill the background SLEEP promptly"
842 );
843 }
844
845 #[cfg_attr(
846 miri,
847 ignore = "stdout streaming not supported for background command under Miri"
848 )]
849 #[test]
850 fn env_applies_to_run_and_background() {
851 let temp = GuardedPath::tempdir().unwrap();
852 let root = guard_root(&temp);
853
854 let script = indoc! {
855 r#"
856 ENV FOO="bar"
857 [family:windows] RUN "echo %FOO% > run.txt"
858 [family:unix] RUN "printf %s \"$FOO\" > run.txt"
859 [family:windows] ASYNC RUN "echo %FOO% > bg.txt"
860 [family:unix] ASYNC RUN "printf %s \"$FOO\" > bg.txt"
861 "#
862 };
863
864 let steps = crate::parse_script(script).unwrap();
865 run_steps(&root, &steps).unwrap();
866
867 assert_eq!(read_trimmed(&root.join("run.txt").unwrap()), "bar");
868 assert_eq!(read_trimmed(&root.join("bg.txt").unwrap()), "bar");
869 }
870
871 #[test]
872 fn workspace_switches_between_snapshot_and_local() {
873 let snapshot = GuardedPath::tempdir().unwrap();
874 let local = GuardedPath::tempdir().unwrap();
875 let snapshot_root = guard_root(&snapshot);
876 let local_root = guard_root(&local);
877
878 let script = indoc! {
879 r#"
880 WRITE "snap.txt" "snap"
881 WORKSPACE LOCAL
882 WRITE "local.txt" "local"
883 WORKSPACE SNAPSHOT
884 WRITE "snap2.txt" "again"
885 "#
886 };
887
888 let steps = crate::parse_script(script).unwrap();
889 run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
890
891 assert!(snapshot_root.join("snap.txt").unwrap().exists());
892 assert!(snapshot_root.join("snap2.txt").unwrap().exists());
893 assert!(local_root.join("local.txt").unwrap().exists());
894 }
895
896 #[test]
897 fn workspace_root_changes_where_slash_points() {
898 let snapshot = GuardedPath::tempdir().unwrap();
899 let local = GuardedPath::tempdir().unwrap();
900 let snapshot_root = guard_root(&snapshot);
901 let local_root = guard_root(&local);
902 let local_client = local_root.join("client").unwrap();
903 create_dirs(&local_client);
904
905 let script = indoc! {
906 r#"
907 WORKSPACE LOCAL
908 WORKDIR "/"
909 WRITE "localroot.txt" "one"
910 WORKDIR "client"
911 WRITE "client.txt" "two"
912 WORKSPACE SNAPSHOT
913 WORKDIR "/"
914 WRITE "snaproot.txt" "three"
915 "#
916 };
917
918 let steps = crate::parse_script(script).unwrap();
919 run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
920
921 assert!(local_root.join("localroot.txt").unwrap().exists());
922 assert!(local_client.join("client.txt").unwrap().exists());
923 assert!(snapshot_root.join("snaproot.txt").unwrap().exists());
924 }
925
926 struct SerialCacheDir {
930 _lock: std::sync::MutexGuard<'static, ()>,
931 prev: Option<String>,
932 }
933
934 static CACHE_DIR_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
935
936 impl SerialCacheDir {
937 fn pin(dir: &GuardedPath) -> Self {
938 let lock = CACHE_DIR_LOCK
939 .lock()
940 .unwrap_or_else(|poisoned| poisoned.into_inner());
941 let prev = std::env::var(oxdock_env::oxdock::CACHE_DIR).ok();
942 unsafe {
944 std::env::set_var(
945 oxdock_env::oxdock::CACHE_DIR,
946 dir.as_path().to_string_lossy().into_owned(),
947 );
948 }
949 Self { _lock: lock, prev }
950 }
951 }
952
953 impl Drop for SerialCacheDir {
954 fn drop(&mut self) {
955 unsafe {
956 match &self.prev {
957 Some(v) => std::env::set_var(oxdock_env::oxdock::CACHE_DIR, v),
958 None => std::env::remove_var(oxdock_env::oxdock::CACHE_DIR),
959 }
960 }
961 }
962 }
963
964 #[test]
965 fn workspace_cache_persists_across_runs() {
966 let pin = GuardedPath::tempdir().unwrap();
967 let pin_root = guard_root(&pin);
968 let _env = SerialCacheDir::pin(&pin_root);
969
970 let snapshot = GuardedPath::tempdir().unwrap();
971 let local = GuardedPath::tempdir().unwrap();
972 let snapshot_root = guard_root(&snapshot);
973 let local_root = guard_root(&local);
974
975 let first = indoc! {
978 r#"
979 WRITE "snap.txt" "snap"
980 WORKSPACE LOCAL
981 WRITE "local.txt" "local"
982 WORKSPACE CACHE
983 WRITE "cached.txt" "persistent"
984 WORKSPACE SNAPSHOT
985 "#
986 };
987 let steps = crate::parse_script(first).unwrap();
988 run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
989
990 #[cfg(not(miri))]
994 assert!(!exists(&snapshot_root, "cached.txt"));
995 #[cfg(not(miri))]
996 assert!(!exists(&local_root, "cached.txt"));
997
998 let fresh_snapshot = GuardedPath::tempdir().unwrap();
1004 let fresh_snapshot_root = guard_root(&fresh_snapshot);
1005 #[cfg(not(miri))]
1006 let fresh_local = GuardedPath::tempdir().unwrap();
1007 #[cfg(not(miri))]
1008 let fresh_local_root = guard_root(&fresh_local);
1009 #[cfg(miri)]
1010 let fresh_local_root = local_root.clone();
1011
1012 let second = indoc! {
1013 r#"
1014 WORKSPACE CACHE
1015 LET $v: STRING = READ cached.txt
1016 ASSERT_EQ $v "persistent"
1017 "#
1018 };
1019 let steps = crate::parse_script(second).unwrap();
1020 run_steps_with_context(&fresh_snapshot_root, &fresh_local_root, &steps).unwrap();
1021 }
1022
1023 #[test]
1024 fn workspace_cache_local_stays_in_project_tree() {
1025 let pin = GuardedPath::tempdir().unwrap();
1027 let pin_root = guard_root(&pin);
1028 let _env = SerialCacheDir::pin(&pin_root);
1029
1030 let snapshot = GuardedPath::tempdir().unwrap();
1031 let local = GuardedPath::tempdir().unwrap();
1032 let snapshot_root = guard_root(&snapshot);
1033 let local_root = guard_root(&local);
1034
1035 let first = indoc! {
1036 r#"
1037 WORKSPACE CACHE --local
1038 WRITE "local-cached.txt" "persistent"
1039 LET $v: STRING = READ local-cached.txt
1040 ASSERT_EQ $v "persistent"
1041 "#
1042 };
1043 let steps = crate::parse_script(first).unwrap();
1044 run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
1045
1046 #[cfg(not(miri))]
1049 assert!(exists(&local_root, ".cache/workspace/local-cached.txt"));
1050 #[cfg(not(miri))]
1051 assert!(!exists(&pin_root, "workspace/local-cached.txt"));
1052
1053 let fresh_snapshot = GuardedPath::tempdir().unwrap();
1056 let fresh_snapshot_root = guard_root(&fresh_snapshot);
1057 let second = indoc! {
1058 r#"
1059 WORKSPACE CACHE --local
1060 LET $v: STRING = READ local-cached.txt
1061 ASSERT_EQ $v "persistent"
1062 "#
1063 };
1064 let steps = crate::parse_script(second).unwrap();
1065 run_steps_with_context(&fresh_snapshot_root, &local_root, &steps).unwrap();
1066
1067 let other_local = GuardedPath::tempdir().unwrap();
1070 let other_local_root = guard_root(&other_local);
1071 let steps = crate::parse_script(second).unwrap();
1072 assert!(
1073 run_steps_with_context(&fresh_snapshot_root, &other_local_root, &steps).is_err(),
1074 "local cache must not leak across project trees"
1075 );
1076 }
1077
1078 #[test]
1079 fn workspace_system_reaches_outside_roots() {
1080 let snapshot = GuardedPath::tempdir().unwrap();
1081 let local = GuardedPath::tempdir().unwrap();
1082 let snapshot_root = guard_root(&snapshot);
1083 let local_root = guard_root(&local);
1084 let outside = GuardedPath::tempdir().unwrap();
1085 let outside_root = guard_root(&outside);
1086
1087 let script = format!(
1095 indoc! {r#"
1096 WORKSPACE SYSTEM
1097 WRITE "{secret}" outside
1098 LET $v: STRING = READ "{secret}"
1099 ASSERT_EQ $v outside
1100 WRITE "{sibling}" done
1101 WORKSPACE SNAPSHOT
1102 "#},
1103 secret = to_forward_slashes(
1104 &outside_root
1105 .join("secret.txt")
1106 .unwrap()
1107 .as_path()
1108 .to_string_lossy()
1109 ),
1110 sibling = to_forward_slashes(
1111 &outside_root
1112 .join("sibling.txt")
1113 .unwrap()
1114 .as_path()
1115 .to_string_lossy()
1116 ),
1117 );
1118 let steps = crate::parse_script(&script).unwrap();
1119 run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
1120
1121 #[cfg(not(miri))]
1124 assert!(exists(&outside_root, "sibling.txt"));
1125 #[cfg(not(miri))]
1127 assert!(!exists(&snapshot_root, "sibling.txt"));
1128 #[cfg(not(miri))]
1129 assert!(!exists(&local_root, "sibling.txt"));
1130 }
1131
1132 #[test]
1133 fn copy_from_workspace_targets() {
1134 let pin = GuardedPath::tempdir().unwrap();
1135 let pin_root = guard_root(&pin);
1136 let _env = SerialCacheDir::pin(&pin_root);
1137
1138 let snapshot = GuardedPath::tempdir().unwrap();
1139 let local = GuardedPath::tempdir().unwrap();
1140 let snapshot_root = guard_root(&snapshot);
1141 let local_root = guard_root(&local);
1142 let outside = GuardedPath::tempdir().unwrap();
1143 let outside_root = guard_root(&outside);
1144
1145 let script = format!(
1151 indoc! {r#"
1152 WRITE snap-src.txt from-snap
1153 WORKSPACE CACHE
1154 WRITE cache-src.txt from-cache
1155 WORKSPACE SYSTEM
1156 WRITE "{secret}" outside
1157 WORKSPACE SNAPSHOT
1158 COPY --from-workspace SNAPSHOT snap-src.txt snap-copy.txt
1159 COPY --from-workspace CACHE cache-src.txt cache-copy.txt
1160 COPY --from-workspace SYSTEM "{secret}" sys-copy.txt
1161 COPY --from-workspace LOCAL "{local_src}" local-copy.txt
1162 "#},
1163 secret = to_forward_slashes(
1164 &outside_root
1165 .join("secret.txt")
1166 .unwrap()
1167 .as_path()
1168 .to_string_lossy()
1169 ),
1170 local_src = to_forward_slashes(
1171 &local_root
1172 .join("local-src.txt")
1173 .unwrap()
1174 .as_path()
1175 .to_string_lossy()
1176 ),
1177 );
1178 let local_seeder = PathResolver::new(local_root.as_path(), local_root.as_path()).unwrap();
1180 local_seeder
1181 .write_file(&local_root.join("local-src.txt").unwrap(), b"from-local")
1182 .unwrap();
1183
1184 let steps = crate::parse_script(&script).unwrap();
1185 run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
1186
1187 assert!(exists(&snapshot_root, "snap-copy.txt"));
1188 assert!(exists(&snapshot_root, "cache-copy.txt"));
1189 assert!(exists(&snapshot_root, "sys-copy.txt"));
1190 assert!(exists(&snapshot_root, "local-copy.txt"));
1191
1192 let pending = indoc! {r#"
1194 COPY --from-workspace SNAPSHOT missing.txt out.txt
1195 "#};
1196 let steps = crate::parse_script(pending).unwrap();
1197 let fresh_snapshot = GuardedPath::tempdir().unwrap();
1198 let fresh_local = GuardedPath::tempdir().unwrap();
1199 assert!(
1200 run_steps_with_context(
1201 &guard_root(&fresh_snapshot),
1202 &guard_root(&fresh_local),
1203 &steps
1204 )
1205 .is_err(),
1206 "COPY from a pending snapshot must fail"
1207 );
1208 }
1209
1210 #[test]
1211 fn copy_destinations_mirror_docker() {
1212 let pin = GuardedPath::tempdir().unwrap();
1217 let pin_root = guard_root(&pin);
1218 let _env = SerialCacheDir::pin(&pin_root);
1219
1220 let snapshot = GuardedPath::tempdir().unwrap();
1221 let local = GuardedPath::tempdir().unwrap();
1222 let snapshot_root = guard_root(&snapshot);
1223 let local_root = guard_root(&local);
1224
1225 let seeder = PathResolver::new(local_root.as_path(), local_root.as_path()).unwrap();
1226 seeder
1227 .write_file(&local_root.join("cargo.toml").unwrap(), b"manifest")
1228 .unwrap();
1229 seeder
1230 .create_dir_all(&local_root.join("sub").unwrap())
1231 .unwrap();
1232 seeder
1233 .write_file(&local_root.join("sub/a.txt").unwrap(), b"a")
1234 .unwrap();
1235
1236 let script = indoc! {r#"
1237 WORKSPACE CACHE --local
1238 COPY --from-workspace LOCAL cargo.toml .
1239 LET $a: STRING = READ cargo.toml
1240 ASSERT_EQ $a manifest
1241 COPY --from-workspace LOCAL cargo.toml renamed.txt
1242 LET $b: STRING = READ renamed.txt
1243 ASSERT_EQ $b manifest
1244 MKDIR subdir
1245 COPY --from-workspace LOCAL cargo.toml subdir
1246 COPY --from-workspace LOCAL cargo.toml subdir/
1247 LET $c: STRING = READ subdir/cargo.toml
1248 ASSERT_EQ $c manifest
1249 COPY --from-workspace LOCAL sub .
1250 LET $d: STRING = READ a.txt
1251 ASSERT_EQ $d a
1252 WORKSPACE SNAPSHOT
1253 COPY --from-workspace LOCAL cargo.toml .
1254 LET $e: STRING = READ cargo.toml
1255 ASSERT_EQ $e manifest
1256 "#};
1257 let steps = crate::parse_script(script).unwrap();
1258 run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
1259
1260 #[cfg(not(miri))]
1265 assert!(exists(&local_root, ".cache/workspace/cargo.toml"));
1266 #[cfg(not(miri))]
1267 assert!(exists(&local_root, ".cache/workspace/renamed.txt"));
1268 #[cfg(not(miri))]
1269 assert!(exists(&local_root, ".cache/workspace/subdir/cargo.toml"));
1270 #[cfg(not(miri))]
1271 assert!(exists(&local_root, ".cache/workspace/a.txt"));
1272 #[cfg(not(miri))]
1273 assert!(exists(&snapshot_root, "cargo.toml"));
1274 }
1275
1276 #[test]
1285 #[cfg_attr(
1286 miri,
1287 ignore = "spawns real child processes; Miri does not support process execution"
1288 )]
1289 fn isolated_hides_outer_env_from_real_children() {
1290 let temp = GuardedPath::tempdir().unwrap();
1291 let root = guard_root(&temp);
1292
1293 let script = indoc!(
1299 r#"
1300 ENV OUTER=outer-val
1301 [family:unix] LET $plain: STRING = RUN ["sh", "-c", "printenv OUTER || echo absent"]
1302 [family:windows] LET $plain: STRING = RUN ["cmd", "/c", "if defined OUTER (echo outer-val) else (echo absent)"]
1303 WRITE plain.txt "{{ $plain }}"
1304 ISOLATED {
1305 [family:unix] LET $boxed: STRING = RUN ["sh", "-c", "printenv OUTER || echo absent"]
1306 [family:windows] LET $boxed: STRING = RUN ["cmd", "/c", "if defined OUTER (echo outer-val) else (echo absent)"]
1307 WRITE boxed.txt "{{ $boxed }}"
1308 }
1309 "#
1310 );
1311 let steps = crate::parse_script(script).unwrap();
1312 run_steps(&root, &steps).unwrap();
1313
1314 assert_eq!(
1315 read_trimmed(&root.join("plain.txt").unwrap()),
1316 "outer-val",
1317 "plain RUN must see the outer var"
1318 );
1319 assert_eq!(
1320 read_trimmed(&root.join("boxed.txt").unwrap()),
1321 "absent",
1322 "ISOLATED RUN must not see the outer var"
1323 );
1324 }
1325
1326 #[test]
1332 #[cfg_attr(
1333 miri,
1334 ignore = "spawns real child processes; Miri does not support process execution"
1335 )]
1336 fn child_env_matches_allowlist_at_every_depth() {
1337 fn env_map(text: &str) -> std::collections::BTreeMap<String, String> {
1338 text.lines()
1339 .filter_map(|line| {
1340 line.split_once('=')
1341 .map(|(k, v)| (k.to_string(), v.to_string()))
1342 })
1343 .collect()
1344 }
1345
1346 let _probe_guard = oxdock_process::TestEnvGuard::set("OXDOCK_ENV_AUDIT_PROBE", "host-only");
1349 let temp = GuardedPath::tempdir().unwrap();
1350 let root = guard_root(&temp);
1351
1352 let script = indoc!(
1356 r#"
1357 ENV OUTER=outer-val
1358 FUNC DUMPENV() {
1359 [family:unix] LET $o: STRING = RUN ["sh", "-c", "env"]
1360 [family:windows] LET $o: STRING = RUN ["cmd", "/c", "set"]
1361 RETURN $o
1362 }
1363 LET $top: STRING = DUMPENV()
1364 WRITE top.txt "{{ $top }}"
1365 ISOLATED {
1366 INHERIT_ENV [OUTER]
1367 LET $mid: STRING = DUMPENV()
1368 WRITE mid.txt "{{ $mid }}"
1369 ISOLATED {
1370 LET $deep: STRING = DUMPENV()
1371 WRITE deep.txt "{{ $deep }}"
1372 }
1373 }
1374 "#
1375 );
1376 let steps = crate::parse_script(script).unwrap();
1377 run_steps(&root, &steps).unwrap();
1378
1379 let read_env = |name: &str| {
1380 let body = read_trimmed(&root.join(name).unwrap());
1381 env_map(&body)
1382 };
1383 let top = read_env("top.txt");
1384 let mid = read_env("mid.txt");
1385 let deep = read_env("deep.txt");
1386
1387 #[allow(clippy::disallowed_macros)]
1396 let shell_added: &[&str] = if cfg!(windows) {
1397 &["PROMPT"]
1400 } else {
1401 &["PWD", "SHLVL", "_"]
1402 };
1403 let mut seed_names: Vec<&str> = Vec::new();
1408 for entry in oxdock_process::env_policy::current_platform_seed() {
1409 if entry.name == oxdock_env::cargo::TARGET_DIR || std::env::var(entry.name).is_ok() {
1410 seed_names.push(entry.name);
1411 }
1412 }
1413 let mut expect_top: Vec<&str> = vec!["OUTER"];
1414 expect_top.extend(seed_names.iter().copied());
1415 let expect_mid = expect_top.clone();
1416 let expect_deep: Vec<&str> = seed_names;
1417 for (label, got, mut want) in [
1418 ("top", &top, expect_top),
1419 ("mid", &mid, expect_mid),
1420 ("deep", &deep, expect_deep),
1421 ] {
1422 want.extend(shell_added);
1423 for name in &want {
1427 if shell_added.contains(name) {
1428 continue;
1429 }
1430 assert!(
1431 got.contains_key(*name),
1432 "{label} dump lacks routed name {name}: {got:?}"
1433 );
1434 }
1435 for key in got.keys() {
1436 assert!(
1437 want.contains(&key.as_str()),
1438 "{label} dump carries unexpected name {key}: {got:?}"
1439 );
1440 }
1441 }
1442 assert_eq!(top.get("OUTER").map(String::as_str), Some("outer-val"));
1443 assert_eq!(mid.get("OUTER").map(String::as_str), Some("outer-val"));
1444 assert!(
1445 !deep.contains_key("OUTER"),
1446 "narrowed level must drop OUTER: {deep:?}"
1447 );
1448 for (label, got) in [("top", &top), ("mid", &mid), ("deep", &deep)] {
1449 assert!(
1450 !got.contains_key("OXDOCK_ENV_AUDIT_PROBE"),
1451 "{label} dump leaked a host-only var: {got:?}"
1452 );
1453 }
1454 }
1455}