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, StepKind, all_metadata,
8 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::Cwd => exec::dispatch_cwd,
30 StepKind::Read(..) => exec::dispatch_read,
31 StepKind::ReadLine { .. } => exec::dispatch_read_line,
32 StepKind::Prompt { .. } => exec::dispatch_prompt,
33 StepKind::Write { .. } => exec::dispatch_write,
34 StepKind::Append { .. } => exec::dispatch_append,
35 StepKind::Remove { .. } => exec::dispatch_remove,
36 StepKind::Expand { .. } => exec::dispatch_expand,
37 StepKind::AssertEq { .. } => exec::dispatch_assert_eq,
38 StepKind::AssertContains { .. } => exec::dispatch_assert_contains,
39 StepKind::HashSha256 { .. } => exec::dispatch_hash_sha256,
40 StepKind::Exit(..) => exec::dispatch_exit,
41 StepKind::AssignAsync { .. } => exec::dispatch_assign_async_step,
42 StepKind::Set { .. } => exec::dispatch_set,
43 StepKind::Await { .. } => exec::dispatch_await_step,
44 StepKind::AssignCapture { .. } => exec::dispatch_assign_capture_step,
45 StepKind::AwaitCapture { .. } => exec::dispatch_await_capture_step,
46 StepKind::Cancel { .. } => exec::dispatch_cancel_step,
47 StepKind::Timeout { .. } => exec::dispatch_timeout_step,
48 StepKind::Isolated { .. } => exec::dispatch_isolated_step,
49 StepKind::IsolatedInheritEnv { .. } => exec::dispatch_isolated_inherit_env,
50 StepKind::Sleep { .. } => exec::dispatch_sleep_step,
51 StepKind::ListAppend { .. } => exec::dispatch_push_into_step,
52 StepKind::FuncDef { .. } => exec::dispatch_func_def,
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;
334 let script = format!(
335 indoc!(
336 r#"
337 [env:{guard}] WRITE "skipped.txt" "hi"
338 WRITE "kept.txt" "ok"
339 "#
340 ),
341 guard = guard_var
342 );
343 let steps = crate::parse_script(&script).unwrap();
344
345 run_steps(&root, &steps).unwrap();
346
347 assert!(
348 !exists(&root, "skipped.txt"),
349 "guarded WRITE should be skipped"
350 );
351 assert!(exists(&root, "kept.txt"), "unguarded WRITE should run");
352 }
353
354 #[test]
355 fn guard_sees_env_set_by_env_step() {
356 let temp = GuardedPath::tempdir().unwrap();
357 let root = guard_root(&temp);
358
359 let script = indoc!(
360 r#"
361 ENV FOO="1"
362 [env:FOO] WRITE "hit.txt" "yes"
363 WRITE "always.txt" "ok"
364 "#
365 );
366 let steps = crate::parse_script(script).unwrap();
367
368 run_steps(&root, &steps).unwrap();
369
370 assert!(
371 exists(&root, "hit.txt"),
372 "guarded WRITE should run after ENV sets variable"
373 );
374 assert!(exists(&root, "always.txt"), "unguarded WRITE should run");
375 }
376
377 #[test]
378 fn echo_runs_and_allows_subsequent_steps() {
379 let temp = GuardedPath::tempdir().unwrap();
380 let root = guard_root(&temp);
381
382 let script = indoc!(
383 r#"
384 ECHO "Hello, world"
385 WRITE "always.txt" "ok"
386 "#
387 );
388 let steps = crate::parse_script(script).unwrap();
389
390 run_steps(&root, &steps).unwrap();
391
392 assert!(exists(&root, "always.txt"), "WRITE after ECHO should run");
393 }
394
395 #[test]
396 fn guard_on_previous_line_applies_to_next_command() {
397 let temp = GuardedPath::tempdir().unwrap();
398 let root = guard_root(&temp);
399
400 let script = indoc!(
401 r#"
402 ENV FOO="1"
403 [env:FOO]
404 WRITE "hit.txt" "yes"
405 WRITE "always.txt" "ok"
406 "#
407 );
408 let steps = crate::parse_script(script).unwrap();
409
410 run_steps(&root, &steps).unwrap();
411
412 assert!(
413 exists(&root, "hit.txt"),
414 "guarded WRITE on next line should run"
415 );
416 assert!(exists(&root, "always.txt"), "unguarded WRITE should run");
417 }
418
419 #[test]
420 fn guard_respects_platform_negation() {
421 let temp = GuardedPath::tempdir().unwrap();
422 let root = guard_root(&temp);
423
424 let script = indoc!(
425 r#"
426 [not(family:unix)] WRITE "platform.txt" "hi"
427 WRITE "always.txt" "ok"
428 "#
429 );
430 let steps = crate::parse_script(script).unwrap();
431
432 run_steps(&root, &steps).unwrap();
433
434 #[allow(clippy::disallowed_macros)]
435 let expect_skipped = cfg!(unix);
436 assert_eq!(
437 exists(&root, "platform.txt"),
438 !expect_skipped,
439 "platform guard should skip on Unix and run elsewhere"
440 );
441 assert!(exists(&root, "always.txt"), "unguarded WRITE should run");
442 }
443
444 #[test]
445 fn guard_block_env_scope_restores_after_exit() {
446 let temp = GuardedPath::tempdir().unwrap();
447 let root = guard_root(&temp);
448
449 let script = indoc!(
450 r#"
451 ENV RUN="1"
452 [env:RUN] {
453 ENV INNER="1"
454 WRITE "scoped.txt" "hit"
455 }
456 [env:INNER] WRITE "leak.txt" "nope"
457 "#
458 );
459 let steps = crate::parse_script(script).unwrap();
460
461 run_steps(&root, &steps).unwrap();
462
463 assert!(exists(&root, "scoped.txt"), "block should run");
464 assert!(
465 !exists(&root, "leak.txt"),
466 "env set inside block must not leak outward"
467 );
468 }
469
470 #[test]
471 fn guard_block_workdir_scope_restores_after_exit() {
472 let temp = GuardedPath::tempdir().unwrap();
473 let root = guard_root(&temp);
474
475 let script = indoc!(
476 r#"
477 MKDIR "nested"
478 ENV RUN="1"
479 [env:RUN] {
480 WORKDIR "nested"
481 WRITE "inside.txt" "ok"
482 }
483 WRITE "outside.txt" "root"
484 "#
485 );
486 let steps = crate::parse_script(script).unwrap();
487
488 run_steps(&root, &steps).unwrap();
489
490 assert!(
491 exists(&root, "nested/inside.txt"),
492 "inside write should land in nested dir"
493 );
494 assert!(
495 exists(&root, "outside.txt"),
496 "workdir should reset after block exits"
497 );
498 assert!(
499 !exists(&root, "nested/outside.txt"),
500 "writes after block should not stay scoped"
501 );
502 }
503
504 #[test]
505 fn workspace_scope_restores_after_guard_block() {
506 let snapshot = GuardedPath::tempdir().unwrap();
507 let local = GuardedPath::tempdir().unwrap();
508 let snapshot_root = guard_root(&snapshot);
509 let local_root = guard_root(&local);
510
511 let script = indoc!(
512 r#"
513 ENV RUN="1"
514 [env:RUN] {
515 WORKSPACE LOCAL
516 WRITE "local_only.txt" "inside"
517 }
518 WRITE "snapshot_only.txt" "outside"
519 "#
520 );
521 let steps = crate::parse_script(script).unwrap();
522
523 run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
524
525 assert!(
526 local_root.join("local_only.txt").unwrap().exists(),
527 "workspace switch inside block should affect local root"
528 );
529 assert!(
530 snapshot_root.join("snapshot_only.txt").unwrap().exists(),
531 "writes after block must target snapshot again"
532 );
533 assert!(
534 !local_root.join("snapshot_only.txt").unwrap().exists(),
535 "workspace should reset after guard block exits"
536 );
537 }
538
539 #[test]
540 fn guard_matches_profile_env() {
541 let temp = GuardedPath::tempdir().unwrap();
543 let root = guard_root(&temp);
544
545 let profile = std::env::var(oxdock_env::cargo::build::PROFILE)
546 .unwrap_or_else(|_| "debug".to_string());
547 let script = format!(
548 indoc!(
549 r#"
550 ENV PROFILE={0}
551 [eq(env:PROFILE, {0})] WRITE "hit.txt" "yes"
552 [ne(env:PROFILE, {0})] WRITE "miss.txt" "no"
553 "#
554 ),
555 profile
556 );
557
558 let steps = crate::parse_script(&script).unwrap();
559 run_steps(&root, &steps).unwrap();
560
561 assert!(
562 exists(&root, "hit.txt"),
563 "PROFILE-matching guard should run"
564 );
565 assert!(
566 !exists(&root, "miss.txt"),
567 "PROFILE inequality guard should skip for current profile"
568 );
569 }
570
571 #[test]
572 fn multiple_guards_all_must_pass() {
573 let temp = GuardedPath::tempdir().unwrap();
574 let root = guard_root(&temp);
575
576 let key = oxdock_env::oxdock::MULTI_GUARD_TEST_PASS;
577
578 let script = format!(
579 indoc!(
580 r#"
581 ENV {k}=ok
582 [env:{k},eq(env:{k}, ok)] WRITE "hit.txt" "yes"
583 WRITE "always.txt" "ok"
584 "#
585 ),
586 k = key
587 );
588 let steps = crate::parse_script(&script).unwrap();
589 run_steps(&root, &steps).unwrap();
590
591 assert!(
592 exists(&root, "hit.txt"),
593 "guarded step should run when all guards pass"
594 );
595 assert!(exists(&root, "always.txt"), "unguarded step should run");
596 }
597
598 #[test]
599 fn multiple_guards_skip_when_one_fails() {
600 let temp = GuardedPath::tempdir().unwrap();
601 let root = guard_root(&temp);
602
603 let key = oxdock_env::oxdock::MULTI_GUARD_TEST_FAIL;
604
605 let script = format!(
606 indoc!(
607 r#"
608 ENV {k}=ok
609 [env:{k},ne(env:{k}, ok)] WRITE "miss.txt" "yes"
610 WRITE "always.txt" "ok"
611 "#
612 ),
613 k = key
614 );
615 let steps = crate::parse_script(&script).unwrap();
616 run_steps(&root, &steps).unwrap();
617
618 assert!(
619 !exists(&root, "miss.txt"),
620 "guarded step should skip when any guard fails"
621 );
622 assert!(exists(&root, "always.txt"), "unguarded step should run");
623 }
624
625 #[cfg_attr(
626 miri,
627 ignore = "stdout streaming not supported for background command under Miri"
628 )]
629 #[test]
630 fn async_exits_success_and_stops_pipeline() {
631 let temp = GuardedPath::tempdir().unwrap();
632 let root = guard_root(&temp);
633
634 let script = indoc! {
636 r#"
637 [family:unix] ASYNC RUN "sleep 0.05"
638 [family:windows] ASYNC RUN "ping -n 1 127.0.0.1"
639 "#
640 };
641 let steps = crate::parse_script(script).unwrap();
642 let res = run_steps(&root, &steps);
643 assert!(res.is_ok(), "ASYNC success should allow clean exit");
644 }
645
646 #[cfg_attr(
647 miri,
648 ignore = "stdout streaming not supported for background command under Miri"
649 )]
650 #[test]
651 fn async_failure_bubbles_status() {
652 let temp = GuardedPath::tempdir().unwrap();
653 let root = guard_root(&temp);
654
655 let script = indoc! {
656 r#"
657 [family:unix] ASYNC RUN "sleep 0.05; exit 7"
658 [family:windows] ASYNC RUN "exit 7"
659 "#
660 };
661 let steps = crate::parse_script(script).unwrap();
662 let err = run_steps(&root, &steps).unwrap_err();
663 let msg = err.to_string();
664 assert!(
665 msg.contains("ASYNC process exited with status")
666 || msg.contains("exit status: 7")
667 || msg.contains("exit code: 7"),
668 "should surface failing ASYNC exit code"
669 );
670 }
671
672 #[cfg_attr(
673 miri,
674 ignore = "timing-sensitive background process test is unreliable under Miri"
675 )]
676 #[test]
677 fn async_multiple_stops_on_first_exit_and_does_not_block_steps() {
678 let temp = GuardedPath::tempdir().unwrap();
679 let root = guard_root(&temp);
680
681 let script = indoc! {
682 r#"
683 [family:unix] ASYNC RUN "sleep 0.2; echo one > one.txt"
684 [family:windows] ASYNC RUN "ping -n 2 127.0.0.1 > NUL & echo one > one.txt"
685 [family:unix] ASYNC RUN "sleep 0.5; echo two > two.txt"
686 [family:windows] ASYNC RUN "ping -n 3 127.0.0.1 > NUL & echo two > two.txt"
687 WRITE "done.txt" "ok"
688 "#
689 };
690
691 let steps = crate::parse_script(script).unwrap();
692 let start = Instant::now();
693 let res = run_steps(&root, &steps);
694 let elapsed = start.elapsed();
695
696 assert!(res.is_ok(), "ASYNC success should allow clean exit");
697 assert!(
698 exists(&root, "done.txt"),
699 "foreground step should run after spawning backgrounds"
700 );
701 assert!(
702 exists(&root, "one.txt"),
703 "first background should finish and emit output"
704 );
705 assert!(
708 exists(&root, "two.txt"),
709 "second background should finish (poll-all waits for all)"
710 );
711
712 #[allow(clippy::disallowed_macros)]
715 let (lower, upper) = if cfg!(windows) {
716 (0.9, 3.0)
717 } else {
718 (0.15, 0.8)
719 };
720 assert!(
721 elapsed.as_secs_f32() < upper && elapsed.as_secs_f32() > lower,
722 "should wait for both backgrounds; got {elapsed:?}"
723 );
724 }
725
726 #[cfg_attr(
727 miri,
728 ignore = "timing-sensitive background process test is unreliable under Miri"
729 )]
730 #[test]
731 fn background_killed_when_unrelated_step_fails() {
732 let temp = GuardedPath::tempdir().unwrap();
733 let root = guard_root(&temp);
734
735 let script = indoc! {
736 r#"
737 [family:unix] ASYNC RUN "sleep 30; echo late > late.txt"
738 [family:windows] ASYNC RUN "ping -n 31 127.0.0.1 > NUL & echo late > late.txt"
739 RUN "__oxdock_missing_command_xyz__"
740 "#
741 };
742
743 let steps = crate::parse_script(script).unwrap();
744 let start = Instant::now();
745 assert!(
746 run_steps(&root, &steps).is_err(),
747 "pipeline should fail on the missing command"
748 );
749 assert!(
763 !exists(&root, "late.txt"),
764 "abandoned background writer must be killed by Drop teardown"
765 );
766 assert!(
770 start.elapsed() < std::time::Duration::from_secs(25),
771 "teardown must end the tree promptly, took {:?}",
772 start.elapsed()
773 );
774 }
775
776 #[cfg_attr(
777 miri,
778 ignore = "stdout streaming not supported for background command under Miri"
779 )]
780 #[test]
781 fn exit_terminates_backgrounds_and_returns_code() {
782 let temp = GuardedPath::tempdir().unwrap();
783 let root = guard_root(&temp);
784
785 let script = indoc! {
786 r#"
787 [family:unix] ASYNC RUN "sleep 30; echo late > late.txt"
788 [family:windows] ASYNC RUN "ping -n 31 127.0.0.1 > NUL & echo late > late.txt"
789 EXIT 5
790 "#
791 };
792
793 let steps = crate::parse_script(script).unwrap();
794 let err = run_steps(&root, &steps).unwrap_err();
795 let msg = err.to_string();
796 assert!(msg.contains("EXIT requested with code 5"));
797 assert!(
798 !exists(&root, "late.txt"),
799 "background process should be killed when EXIT is hit"
800 );
801 }
802
803 #[test]
804 #[cfg_attr(
805 miri,
806 ignore = "EXIT joins real background threads; timing-sensitive under Miri"
807 )]
808 fn exit_inside_nested_block_reports_code_and_kills_backgrounds() {
809 let temp = GuardedPath::tempdir().unwrap();
810 let root = guard_root(&temp);
811
812 let script = indoc! {
813 r#"
814 ASYNC {
815 SLEEP 30s
816 }
817 [bool:true] {
818 EXIT 5
819 }
820 "#
821 };
822
823 let steps = crate::parse_script(script).unwrap();
824 let start = std::time::Instant::now();
825 let err = run_steps(&root, &steps).unwrap_err();
826 assert!(
827 err.to_string().contains("EXIT requested with code 5"),
828 "nested EXIT must report its code: {err}"
829 );
830 assert!(
831 start.elapsed() < std::time::Duration::from_secs(10),
832 "nested EXIT must kill the background SLEEP promptly"
833 );
834 }
835
836 #[cfg_attr(
837 miri,
838 ignore = "stdout streaming not supported for background command under Miri"
839 )]
840 #[test]
841 fn env_applies_to_run_and_background() {
842 let temp = GuardedPath::tempdir().unwrap();
843 let root = guard_root(&temp);
844
845 let script = indoc! {
846 r#"
847 ENV FOO="bar"
848 [family:windows] RUN "echo %FOO% > run.txt"
849 [family:unix] RUN "printf %s \"$FOO\" > run.txt"
850 [family:windows] ASYNC RUN "echo %FOO% > bg.txt"
851 [family:unix] ASYNC RUN "printf %s \"$FOO\" > bg.txt"
852 "#
853 };
854
855 let steps = crate::parse_script(script).unwrap();
856 run_steps(&root, &steps).unwrap();
857
858 assert_eq!(read_trimmed(&root.join("run.txt").unwrap()), "bar");
859 assert_eq!(read_trimmed(&root.join("bg.txt").unwrap()), "bar");
860 }
861
862 #[test]
863 fn workspace_switches_between_snapshot_and_local() {
864 let snapshot = GuardedPath::tempdir().unwrap();
865 let local = GuardedPath::tempdir().unwrap();
866 let snapshot_root = guard_root(&snapshot);
867 let local_root = guard_root(&local);
868
869 let script = indoc! {
870 r#"
871 WRITE "snap.txt" "snap"
872 WORKSPACE LOCAL
873 WRITE "local.txt" "local"
874 WORKSPACE SNAPSHOT
875 WRITE "snap2.txt" "again"
876 "#
877 };
878
879 let steps = crate::parse_script(script).unwrap();
880 run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
881
882 assert!(snapshot_root.join("snap.txt").unwrap().exists());
883 assert!(snapshot_root.join("snap2.txt").unwrap().exists());
884 assert!(local_root.join("local.txt").unwrap().exists());
885 }
886
887 #[test]
888 fn workspace_root_changes_where_slash_points() {
889 let snapshot = GuardedPath::tempdir().unwrap();
890 let local = GuardedPath::tempdir().unwrap();
891 let snapshot_root = guard_root(&snapshot);
892 let local_root = guard_root(&local);
893 let local_client = local_root.join("client").unwrap();
894 create_dirs(&local_client);
895
896 let script = indoc! {
897 r#"
898 WORKSPACE LOCAL
899 WORKDIR "/"
900 WRITE "localroot.txt" "one"
901 WORKDIR "client"
902 WRITE "client.txt" "two"
903 WORKSPACE SNAPSHOT
904 WORKDIR "/"
905 WRITE "snaproot.txt" "three"
906 "#
907 };
908
909 let steps = crate::parse_script(script).unwrap();
910 run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
911
912 assert!(local_root.join("localroot.txt").unwrap().exists());
913 assert!(local_client.join("client.txt").unwrap().exists());
914 assert!(snapshot_root.join("snaproot.txt").unwrap().exists());
915 }
916
917 struct SerialCacheDir {
921 _lock: std::sync::MutexGuard<'static, ()>,
922 prev: Option<String>,
923 }
924
925 static CACHE_DIR_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
926
927 impl SerialCacheDir {
928 fn pin(dir: &GuardedPath) -> Self {
929 let lock = CACHE_DIR_LOCK
930 .lock()
931 .unwrap_or_else(|poisoned| poisoned.into_inner());
932 let prev = std::env::var(oxdock_env::oxdock::CACHE_DIR).ok();
933 unsafe {
935 std::env::set_var(
936 oxdock_env::oxdock::CACHE_DIR,
937 dir.as_path().to_string_lossy().into_owned(),
938 );
939 }
940 Self { _lock: lock, prev }
941 }
942 }
943
944 impl Drop for SerialCacheDir {
945 fn drop(&mut self) {
946 unsafe {
947 match &self.prev {
948 Some(v) => std::env::set_var(oxdock_env::oxdock::CACHE_DIR, v),
949 None => std::env::remove_var(oxdock_env::oxdock::CACHE_DIR),
950 }
951 }
952 }
953 }
954
955 #[test]
956 fn workspace_cache_persists_across_runs() {
957 let pin = GuardedPath::tempdir().unwrap();
958 let pin_root = guard_root(&pin);
959 let _env = SerialCacheDir::pin(&pin_root);
960
961 let snapshot = GuardedPath::tempdir().unwrap();
962 let local = GuardedPath::tempdir().unwrap();
963 let snapshot_root = guard_root(&snapshot);
964 let local_root = guard_root(&local);
965
966 let first = indoc! {
969 r#"
970 WRITE "snap.txt" "snap"
971 WORKSPACE LOCAL
972 WRITE "local.txt" "local"
973 WORKSPACE CACHE
974 WRITE "cached.txt" "persistent"
975 WORKSPACE SNAPSHOT
976 "#
977 };
978 let steps = crate::parse_script(first).unwrap();
979 run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
980
981 #[cfg(not(miri))]
985 assert!(!exists(&snapshot_root, "cached.txt"));
986 #[cfg(not(miri))]
987 assert!(!exists(&local_root, "cached.txt"));
988
989 let fresh_snapshot = GuardedPath::tempdir().unwrap();
995 let fresh_snapshot_root = guard_root(&fresh_snapshot);
996 #[cfg(not(miri))]
997 let fresh_local = GuardedPath::tempdir().unwrap();
998 #[cfg(not(miri))]
999 let fresh_local_root = guard_root(&fresh_local);
1000 #[cfg(miri)]
1001 let fresh_local_root = local_root.clone();
1002
1003 let second = indoc! {
1004 r#"
1005 WORKSPACE CACHE
1006 LET $v: STRING = READ cached.txt
1007 ASSERT_EQ $v "persistent"
1008 "#
1009 };
1010 let steps = crate::parse_script(second).unwrap();
1011 run_steps_with_context(&fresh_snapshot_root, &fresh_local_root, &steps).unwrap();
1012 }
1013
1014 #[test]
1015 fn workspace_cache_local_stays_in_project_tree() {
1016 let pin = GuardedPath::tempdir().unwrap();
1018 let pin_root = guard_root(&pin);
1019 let _env = SerialCacheDir::pin(&pin_root);
1020
1021 let snapshot = GuardedPath::tempdir().unwrap();
1022 let local = GuardedPath::tempdir().unwrap();
1023 let snapshot_root = guard_root(&snapshot);
1024 let local_root = guard_root(&local);
1025
1026 let first = indoc! {
1027 r#"
1028 WORKSPACE CACHE --local
1029 WRITE "local-cached.txt" "persistent"
1030 LET $v: STRING = READ local-cached.txt
1031 ASSERT_EQ $v "persistent"
1032 "#
1033 };
1034 let steps = crate::parse_script(first).unwrap();
1035 run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
1036
1037 #[cfg(not(miri))]
1040 assert!(exists(&local_root, ".cache/workspace/local-cached.txt"));
1041 #[cfg(not(miri))]
1042 assert!(!exists(&pin_root, "workspace/local-cached.txt"));
1043
1044 let fresh_snapshot = GuardedPath::tempdir().unwrap();
1047 let fresh_snapshot_root = guard_root(&fresh_snapshot);
1048 let second = indoc! {
1049 r#"
1050 WORKSPACE CACHE --local
1051 LET $v: STRING = READ local-cached.txt
1052 ASSERT_EQ $v "persistent"
1053 "#
1054 };
1055 let steps = crate::parse_script(second).unwrap();
1056 run_steps_with_context(&fresh_snapshot_root, &local_root, &steps).unwrap();
1057
1058 let other_local = GuardedPath::tempdir().unwrap();
1061 let other_local_root = guard_root(&other_local);
1062 let steps = crate::parse_script(second).unwrap();
1063 assert!(
1064 run_steps_with_context(&fresh_snapshot_root, &other_local_root, &steps).is_err(),
1065 "local cache must not leak across project trees"
1066 );
1067 }
1068
1069 #[test]
1070 fn workspace_system_reaches_outside_roots() {
1071 let snapshot = GuardedPath::tempdir().unwrap();
1072 let local = GuardedPath::tempdir().unwrap();
1073 let snapshot_root = guard_root(&snapshot);
1074 let local_root = guard_root(&local);
1075 let outside = GuardedPath::tempdir().unwrap();
1076 let outside_root = guard_root(&outside);
1077
1078 let script = format!(
1086 indoc! {r#"
1087 WORKSPACE SYSTEM
1088 WRITE "{secret}" outside
1089 LET $v: STRING = READ "{secret}"
1090 ASSERT_EQ $v outside
1091 WRITE "{sibling}" done
1092 WORKSPACE SNAPSHOT
1093 "#},
1094 secret = to_forward_slashes(
1095 &outside_root
1096 .join("secret.txt")
1097 .unwrap()
1098 .as_path()
1099 .to_string_lossy()
1100 ),
1101 sibling = to_forward_slashes(
1102 &outside_root
1103 .join("sibling.txt")
1104 .unwrap()
1105 .as_path()
1106 .to_string_lossy()
1107 ),
1108 );
1109 let steps = crate::parse_script(&script).unwrap();
1110 run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
1111
1112 #[cfg(not(miri))]
1115 assert!(exists(&outside_root, "sibling.txt"));
1116 #[cfg(not(miri))]
1118 assert!(!exists(&snapshot_root, "sibling.txt"));
1119 #[cfg(not(miri))]
1120 assert!(!exists(&local_root, "sibling.txt"));
1121 }
1122
1123 #[test]
1124 fn copy_from_workspace_targets() {
1125 let pin = GuardedPath::tempdir().unwrap();
1126 let pin_root = guard_root(&pin);
1127 let _env = SerialCacheDir::pin(&pin_root);
1128
1129 let snapshot = GuardedPath::tempdir().unwrap();
1130 let local = GuardedPath::tempdir().unwrap();
1131 let snapshot_root = guard_root(&snapshot);
1132 let local_root = guard_root(&local);
1133 let outside = GuardedPath::tempdir().unwrap();
1134 let outside_root = guard_root(&outside);
1135
1136 let script = format!(
1142 indoc! {r#"
1143 WRITE snap-src.txt from-snap
1144 WORKSPACE CACHE
1145 WRITE cache-src.txt from-cache
1146 WORKSPACE SYSTEM
1147 WRITE "{secret}" outside
1148 WORKSPACE SNAPSHOT
1149 COPY --from-workspace SNAPSHOT snap-src.txt snap-copy.txt
1150 COPY --from-workspace CACHE cache-src.txt cache-copy.txt
1151 COPY --from-workspace SYSTEM "{secret}" sys-copy.txt
1152 COPY --from-workspace LOCAL "{local_src}" local-copy.txt
1153 "#},
1154 secret = to_forward_slashes(
1155 &outside_root
1156 .join("secret.txt")
1157 .unwrap()
1158 .as_path()
1159 .to_string_lossy()
1160 ),
1161 local_src = to_forward_slashes(
1162 &local_root
1163 .join("local-src.txt")
1164 .unwrap()
1165 .as_path()
1166 .to_string_lossy()
1167 ),
1168 );
1169 let local_seeder = PathResolver::new(local_root.as_path(), local_root.as_path()).unwrap();
1171 local_seeder
1172 .write_file(&local_root.join("local-src.txt").unwrap(), b"from-local")
1173 .unwrap();
1174
1175 let steps = crate::parse_script(&script).unwrap();
1176 run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
1177
1178 assert!(exists(&snapshot_root, "snap-copy.txt"));
1179 assert!(exists(&snapshot_root, "cache-copy.txt"));
1180 assert!(exists(&snapshot_root, "sys-copy.txt"));
1181 assert!(exists(&snapshot_root, "local-copy.txt"));
1182
1183 let pending = indoc! {r#"
1185 COPY --from-workspace SNAPSHOT missing.txt out.txt
1186 "#};
1187 let steps = crate::parse_script(pending).unwrap();
1188 let fresh_snapshot = GuardedPath::tempdir().unwrap();
1189 let fresh_local = GuardedPath::tempdir().unwrap();
1190 assert!(
1191 run_steps_with_context(
1192 &guard_root(&fresh_snapshot),
1193 &guard_root(&fresh_local),
1194 &steps
1195 )
1196 .is_err(),
1197 "COPY from a pending snapshot must fail"
1198 );
1199 }
1200
1201 #[test]
1202 fn copy_destinations_mirror_docker() {
1203 let pin = GuardedPath::tempdir().unwrap();
1208 let pin_root = guard_root(&pin);
1209 let _env = SerialCacheDir::pin(&pin_root);
1210
1211 let snapshot = GuardedPath::tempdir().unwrap();
1212 let local = GuardedPath::tempdir().unwrap();
1213 let snapshot_root = guard_root(&snapshot);
1214 let local_root = guard_root(&local);
1215
1216 let seeder = PathResolver::new(local_root.as_path(), local_root.as_path()).unwrap();
1217 seeder
1218 .write_file(&local_root.join("cargo.toml").unwrap(), b"manifest")
1219 .unwrap();
1220 seeder
1221 .create_dir_all(&local_root.join("sub").unwrap())
1222 .unwrap();
1223 seeder
1224 .write_file(&local_root.join("sub/a.txt").unwrap(), b"a")
1225 .unwrap();
1226
1227 let script = indoc! {r#"
1228 WORKSPACE CACHE --local
1229 COPY --from-workspace LOCAL cargo.toml .
1230 LET $a: STRING = READ cargo.toml
1231 ASSERT_EQ $a manifest
1232 COPY --from-workspace LOCAL cargo.toml renamed.txt
1233 LET $b: STRING = READ renamed.txt
1234 ASSERT_EQ $b manifest
1235 MKDIR subdir
1236 COPY --from-workspace LOCAL cargo.toml subdir
1237 COPY --from-workspace LOCAL cargo.toml subdir/
1238 LET $c: STRING = READ subdir/cargo.toml
1239 ASSERT_EQ $c manifest
1240 COPY --from-workspace LOCAL sub .
1241 LET $d: STRING = READ a.txt
1242 ASSERT_EQ $d a
1243 WORKSPACE SNAPSHOT
1244 COPY --from-workspace LOCAL cargo.toml .
1245 LET $e: STRING = READ cargo.toml
1246 ASSERT_EQ $e manifest
1247 "#};
1248 let steps = crate::parse_script(script).unwrap();
1249 run_steps_with_context(&snapshot_root, &local_root, &steps).unwrap();
1250
1251 #[cfg(not(miri))]
1256 assert!(exists(&local_root, ".cache/workspace/cargo.toml"));
1257 #[cfg(not(miri))]
1258 assert!(exists(&local_root, ".cache/workspace/renamed.txt"));
1259 #[cfg(not(miri))]
1260 assert!(exists(&local_root, ".cache/workspace/subdir/cargo.toml"));
1261 #[cfg(not(miri))]
1262 assert!(exists(&local_root, ".cache/workspace/a.txt"));
1263 #[cfg(not(miri))]
1264 assert!(exists(&snapshot_root, "cargo.toml"));
1265 }
1266
1267 #[test]
1276 #[cfg_attr(
1277 miri,
1278 ignore = "spawns real child processes; Miri does not support process execution"
1279 )]
1280 fn isolated_hides_outer_env_from_real_children() {
1281 let temp = GuardedPath::tempdir().unwrap();
1282 let root = guard_root(&temp);
1283
1284 let script = indoc!(
1290 r#"
1291 ENV OUTER=outer-val
1292 [family:unix] LET $plain: STRING = RUN ["sh", "-c", "printenv OUTER || echo absent"]
1293 [family:windows] LET $plain: STRING = RUN ["cmd", "/c", "if defined OUTER (echo outer-val) else (echo absent)"]
1294 WRITE plain.txt "{{ $plain }}"
1295 ISOLATED {
1296 [family:unix] LET $boxed: STRING = RUN ["sh", "-c", "printenv OUTER || echo absent"]
1297 [family:windows] LET $boxed: STRING = RUN ["cmd", "/c", "if defined OUTER (echo outer-val) else (echo absent)"]
1298 WRITE boxed.txt "{{ $boxed }}"
1299 }
1300 "#
1301 );
1302 let steps = crate::parse_script(script).unwrap();
1303 run_steps(&root, &steps).unwrap();
1304
1305 assert_eq!(
1306 read_trimmed(&root.join("plain.txt").unwrap()),
1307 "outer-val",
1308 "plain RUN must see the outer var"
1309 );
1310 assert_eq!(
1311 read_trimmed(&root.join("boxed.txt").unwrap()),
1312 "absent",
1313 "ISOLATED RUN must not see the outer var"
1314 );
1315 }
1316
1317 #[test]
1323 #[cfg_attr(
1324 miri,
1325 ignore = "spawns real child processes; Miri does not support process execution"
1326 )]
1327 fn child_env_matches_allowlist_at_every_depth() {
1328 fn env_map(text: &str) -> std::collections::BTreeMap<String, String> {
1329 text.lines()
1330 .filter_map(|line| {
1331 line.split_once('=')
1332 .map(|(k, v)| (k.to_string(), v.to_string()))
1333 })
1334 .collect()
1335 }
1336
1337 let _probe_guard = oxdock_process::TestEnvGuard::set("OXDOCK_ENV_AUDIT_PROBE", "host-only");
1340 let temp = GuardedPath::tempdir().unwrap();
1341 let root = guard_root(&temp);
1342
1343 let script = indoc!(
1347 r#"
1348 ENV OUTER=outer-val
1349 FUNC DUMPENV() {
1350 [family:unix] LET $o: STRING = RUN ["sh", "-c", "env"]
1351 [family:windows] LET $o: STRING = RUN ["cmd", "/c", "set"]
1352 RETURN $o
1353 }
1354 LET $top: STRING = DUMPENV()
1355 WRITE top.txt "{{ $top }}"
1356 ISOLATED {
1357 INHERIT_ENV [OUTER]
1358 LET $mid: STRING = DUMPENV()
1359 WRITE mid.txt "{{ $mid }}"
1360 ISOLATED {
1361 LET $deep: STRING = DUMPENV()
1362 WRITE deep.txt "{{ $deep }}"
1363 }
1364 }
1365 "#
1366 );
1367 let steps = crate::parse_script(script).unwrap();
1368 run_steps(&root, &steps).unwrap();
1369
1370 let read_env = |name: &str| {
1371 let body = read_trimmed(&root.join(name).unwrap());
1372 env_map(&body)
1373 };
1374 let top = read_env("top.txt");
1375 let mid = read_env("mid.txt");
1376 let deep = read_env("deep.txt");
1377
1378 #[allow(clippy::disallowed_macros)]
1387 let shell_added: &[&str] = if cfg!(windows) {
1388 &["PROMPT"]
1391 } else {
1392 &["PWD", "SHLVL", "_"]
1393 };
1394 let mut seed_names: Vec<&str> = Vec::new();
1399 for entry in oxdock_process::env_policy::current_platform_seed() {
1400 if entry.name == oxdock_env::cargo::TARGET_DIR || std::env::var(entry.name).is_ok() {
1401 seed_names.push(entry.name);
1402 }
1403 }
1404 let mut expect_top: Vec<&str> = vec!["OUTER"];
1405 expect_top.extend(seed_names.iter().copied());
1406 let expect_mid = expect_top.clone();
1407 let expect_deep: Vec<&str> = seed_names;
1408 for (label, got, mut want) in [
1409 ("top", &top, expect_top),
1410 ("mid", &mid, expect_mid),
1411 ("deep", &deep, expect_deep),
1412 ] {
1413 want.extend(shell_added);
1414 for name in &want {
1418 if shell_added.contains(name) {
1419 continue;
1420 }
1421 assert!(
1422 got.contains_key(*name),
1423 "{label} dump lacks routed name {name}: {got:?}"
1424 );
1425 }
1426 for key in got.keys() {
1427 assert!(
1428 want.contains(&key.as_str()),
1429 "{label} dump carries unexpected name {key}: {got:?}"
1430 );
1431 }
1432 }
1433 assert_eq!(top.get("OUTER").map(String::as_str), Some("outer-val"));
1434 assert_eq!(mid.get("OUTER").map(String::as_str), Some("outer-val"));
1435 assert!(
1436 !deep.contains_key("OUTER"),
1437 "narrowed level must drop OUTER: {deep:?}"
1438 );
1439 for (label, got) in [("top", &top), ("mid", &mid), ("deep", &deep)] {
1440 assert!(
1441 !got.contains_key("OXDOCK_ENV_AUDIT_PROBE"),
1442 "{label} dump leaked a host-only var: {got:?}"
1443 );
1444 }
1445 }
1446}