1use std::collections::HashMap;
2use std::process::ExitStatus;
3use std::sync::Arc;
4use std::sync::Mutex;
5use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
6
7use anyhow::{Result, bail};
8use oxdock_fs::GuardedPath;
9use oxdock_parser::{Arg, AssertTarget, Step, StepKind, Value, guard_option_allows};
10use oxdock_process::{BackgroundHandle, CommandStdin, ProcessManager, SharedInput, SharedOutput};
11
12fn exit_status_from_code(code: i32) -> ExitStatus {
14 #[cfg(unix)]
15 {
16 use std::os::unix::process::ExitStatusExt;
17 ExitStatus::from_raw(code << 8)
18 }
19 #[cfg(windows)]
20 {
21 use std::os::windows::process::ExitStatusExt;
22 ExitStatus::from_raw(code as u32)
23 }
24}
25
26use super::handlers;
27use super::io::{ExactCapture, SlidingWindow, StreamHandle};
28use super::native::PureTable;
29use super::state::{ExecState, TaskEntry, TaskPhase};
30use oxdock_pipe::PipeInner;
31
32pub(super) struct ThreadJoinHandle {
35 join: Option<std::thread::JoinHandle<Result<()>>>,
36 cancel_token: Arc<AtomicBool>,
37 cancel_hub: Arc<oxdock_process::CancelHub>,
38 active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
39 worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
47 thread_error: Option<anyhow::Error>,
49 thread_exit_code: Option<i64>,
53}
54
55impl ThreadJoinHandle {
56 pub(super) fn new(
57 join: std::thread::JoinHandle<Result<()>>,
58 cancel_token: Arc<AtomicBool>,
59 cancel_hub: Arc<oxdock_process::CancelHub>,
60 active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
61 worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
62 ) -> Self {
63 Self {
64 join: Some(join),
65 cancel_token,
66 cancel_hub,
67 active_process,
68 worker,
69 thread_error: None,
70 thread_exit_code: None,
71 }
72 }
73
74 fn reemit_error(&self) -> anyhow::Error {
80 let msg = self
81 .thread_error
82 .as_ref()
83 .map(|err| format!("{err:#}"))
84 .unwrap_or_else(|| "background thread failed without an error".to_string());
85 match self.thread_exit_code {
86 Some(code) => anyhow::Error::new(super::exit::ExitRequest(code)).context(msg),
87 None => anyhow::anyhow!("{msg}"),
88 }
89 }
90
91 fn is_self(&self) -> bool {
93 let guard = self.worker.lock().unwrap_or_else(|e| e.into_inner());
94 guard.is_some_and(|id| id == std::thread::current().id())
95 }
96
97 fn reap(&mut self) {
99 if self.join.is_none() {
100 return;
101 }
102 if self.is_self() {
103 let _ = self.join.take();
107 return;
108 }
109 let handle = self.join.take().unwrap();
110 match handle.join() {
111 Ok(Ok(())) => {}
112 Ok(Err(e)) => {
113 self.thread_exit_code = super::exit::exit_code_of(&e);
114 self.thread_error = Some(e);
115 }
116 Err(panic) => {
117 let msg = if let Some(s) = panic.downcast_ref::<&str>() {
118 s.to_string()
119 } else if let Some(s) = panic.downcast_ref::<String>() {
120 s.clone()
121 } else {
122 "thread panicked".to_string()
123 };
124 self.thread_error = Some(anyhow::anyhow!("{msg}"));
125 }
126 }
127 }
128}
129
130impl BackgroundHandle for ThreadJoinHandle {
131 fn try_wait(&mut self) -> Result<Option<ExitStatus>> {
132 if let Some(join) = &self.join {
133 if join.is_finished() {
134 self.reap();
135 } else {
136 return Ok(None);
137 }
138 }
139 if self.thread_error.is_some() {
145 Err(self.reemit_error())
146 } else {
147 Ok(Some(exit_status_from_code(0)))
148 }
149 }
150
151 fn kill(&mut self) -> Result<()> {
152 self.cancel_token.store(true, Ordering::SeqCst);
154 self.cancel_hub.mark_cancelled();
157 if let Ok(mut guard) = self.active_process.lock()
159 && let Some(ref mut proc) = *guard
160 {
161 let _ = proc.kill();
162 }
163 self.reap();
165 Ok(())
166 }
167
168 fn wait(&mut self) -> Result<ExitStatus> {
169 self.reap();
170 if self.thread_error.is_some() {
172 Err(self.reemit_error())
173 } else {
174 Ok(exit_status_from_code(0))
175 }
176 }
177}
178
179impl Drop for ThreadJoinHandle {
180 fn drop(&mut self) {
181 let _ = self.kill();
182 }
183}
184
185static ASSERT_GENERATION: AtomicUsize = AtomicUsize::new(0);
189
190#[derive(Debug)]
197pub(super) enum Flow {
198 Done,
199 Break { idx: usize },
200 Continue { idx: usize },
201 Return { idx: usize, value: Value },
202}
203
204pub(super) fn allocate_assert_generation() -> usize {
205 ASSERT_GENERATION.fetch_add(1, Ordering::Relaxed)
206}
207
208#[derive(Clone, Copy, PartialEq, Eq)]
210pub(super) enum AssertStream {
211 Stdout,
212 Stderr,
213}
214
215fn extract_stream_needle(kind: &StepKind) -> Option<(AssertStream, &Arg)> {
219 let step = match kind {
220 StepKind::WithIo { cmd, .. } => cmd.as_ref(),
221 other => other,
222 };
223 match step {
224 StepKind::AssertContains { haystack, needle } => match haystack {
225 AssertTarget::Stdout => Some((AssertStream::Stdout, needle)),
226 AssertTarget::Stderr => Some((AssertStream::Stderr, needle)),
227 _ => None,
228 },
229 _ => None,
230 }
231}
232
233fn needs_exact_stdout(kind: &StepKind) -> bool {
236 let step = match kind {
237 StepKind::WithIo { cmd, .. } => cmd.as_ref(),
238 other => other,
239 };
240 matches!(
241 step,
242 StepKind::AssertEq {
243 actual: AssertTarget::Stdout,
244 ..
245 }
246 )
247}
248
249pub(super) enum ResolvedAssertTarget {
252 Value(Value),
253 Stdout,
254 Stderr,
255 Pipe(Vec<u8>),
256}
257
258pub(super) fn resolve_assert_target<P: ProcessManager>(
264 target: &AssertTarget,
265 cx: &mut StepCtx<'_, P>,
266) -> Result<ResolvedAssertTarget> {
267 match target {
268 AssertTarget::Value(arg) => {
269 let value = super::args::evaluate_assert_operand(arg, cx)?;
270 if let Some(handle) = value.as_pipe_handle() {
271 let bytes =
272 cx.state.io.peek_pipe_content(&handle).map_err(|e| {
273 anyhow::anyhow!("step pipe assertion cannot read pipe: {e}")
274 })?;
275 return Ok(ResolvedAssertTarget::Pipe(bytes));
276 }
277 Ok(ResolvedAssertTarget::Value(value))
278 }
279 AssertTarget::Stdout => Ok(ResolvedAssertTarget::Stdout),
280 AssertTarget::Stderr => Ok(ResolvedAssertTarget::Stderr),
281 }
282}
283
284pub(super) fn pre_register_assertions<P: ProcessManager>(
291 state: &mut ExecState<P>,
292 steps: &[Step],
293 generation: usize,
294) -> Result<()> {
295 let mut windows = match state.assert_windows.lock() {
296 Ok(guard) => guard,
297 Err(_) => bail!("assert_windows poisoned"),
298 };
299 let mut stderr_windows = match state.assert_windows_stderr.lock() {
300 Ok(guard) => guard,
301 Err(_) => bail!("assert_windows_stderr poisoned"),
302 };
303 let mut exact = match state.exact_stdout.lock() {
304 Ok(guard) => guard,
305 Err(_) => bail!("exact_stdout poisoned"),
306 };
307 for (idx, step) in steps.iter().enumerate() {
308 if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
309 let resolved = super::args::resolve_arg_state(arg, state)?;
310 let map = match stream {
311 AssertStream::Stdout => &mut windows,
312 AssertStream::Stderr => &mut stderr_windows,
313 };
314 map.insert((generation, idx), SlidingWindow::new(resolved.into_bytes()));
315 }
316 if needs_exact_stdout(&step.kind) {
317 exact.entry(generation).or_insert_with(ExactCapture::new);
318 }
319 }
320 Ok(())
321}
322
323#[allow(clippy::collapsible_if)]
329pub(super) fn sync_iteration_assert_needles<P: ProcessManager>(
330 state: &ExecState<P>,
331 steps: &[Step],
332 generation: usize,
333) -> Result<()> {
334 let mut windows = match state.assert_windows.lock() {
335 Ok(guard) => guard,
336 Err(_) => bail!("assert_windows poisoned"),
337 };
338 let mut stderr_windows = match state.assert_windows_stderr.lock() {
339 Ok(guard) => guard,
340 Err(_) => bail!("assert_windows_stderr poisoned"),
341 };
342 for (idx, step) in steps.iter().enumerate() {
343 if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
344 let map = match stream {
345 AssertStream::Stdout => &mut windows,
346 AssertStream::Stderr => &mut stderr_windows,
347 };
348 if let Some(w) = map.get_mut(&(generation, idx)) {
349 let resolved = super::args::resolve_arg_state(arg, state)?;
350 w.update_needle(resolved.into_bytes());
351 }
352 }
353 }
354 Ok(())
355}
356
357pub struct StepCtx<'a, P: ProcessManager> {
370 pub(super) state: &'a mut ExecState<P>,
371 pub(super) process: &'a mut P,
372 pub(super) stdin: CommandStdin,
373 pub(super) expose_stdin: bool,
374 pub(super) out: Option<StreamHandle>,
375 pub(super) err: Option<StreamHandle>,
376 pub(super) out_pipe: Option<Arc<PipeInner>>,
382 pub(super) stdin_pipe: Option<Arc<PipeInner>>,
387}
388
389impl<'a, P: ProcessManager> StepCtx<'a, P> {
390 pub(super) fn err_shared(&self) -> Option<SharedOutput> {
394 match self.err.clone() {
395 Some(StreamHandle::Stream(writer)) => Some(writer),
396 _ => None,
397 }
398 }
399
400 pub fn get_var(&self, key: &str) -> Option<Value> {
402 self.state.get_var(key)
403 }
404
405 pub fn get_env(&self, key: &str) -> Option<String> {
409 self.state.get_env(key).map(str::to_string)
410 }
411
412 pub fn env_snapshot(&self) -> HashMap<String, String> {
419 self.state.envs.as_ref().clone()
420 }
421
422 pub fn ensure_scratch_materialized(&self) -> Result<()> {
427 self.state.cargo_scratch.ensure_materialized()
428 }
429
430 pub fn cwd(&self) -> &GuardedPath {
432 &self.state.cwd
433 }
434
435 pub fn pure_functions(&self) -> std::sync::Arc<PureTable> {
443 self.state.pure_function_table()
444 }
445
446 pub fn new_pipe(&self) -> Value {
451 Value::pipe_fresh_in_task(self.state.task_id)
452 }
453
454 pub fn pipe_reader(&self, value: &Value) -> Result<SharedInput> {
463 use oxdock_pipe::{Materialized, materialize};
464 let Some(handle) = value.as_pipe_handle() else {
465 anyhow::bail!(
466 "host pipe_reader needs a PIPE value, got {}",
467 value.type_name()
468 );
469 };
470 match materialize(&handle, false)? {
471 Materialized::Script(backend) => Ok(backend.reader_handle()),
472 #[cfg(not(miri))]
473 Materialized::Os(entry) => {
474 let owned = entry.reader.take().map_err(|_| {
475 anyhow::anyhow!(
476 "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
477 )
478 })?;
479 Ok(Arc::new(Mutex::new(owned)))
480 }
481 }
482 }
483
484 pub fn pipe_writer(&self, value: &Value) -> Result<SharedOutput> {
488 use oxdock_pipe::{Materialized, materialize};
489 let Some(handle) = value.as_pipe_handle() else {
490 anyhow::bail!(
491 "host pipe_writer needs a PIPE value, got {}",
492 value.type_name()
493 );
494 };
495 match materialize(&handle, false)? {
496 Materialized::Script(backend) => Ok(backend.writer_handle()),
497 #[cfg(not(miri))]
498 Materialized::Os(entry) => {
499 let owned = entry.writer.take().map_err(|_| {
500 anyhow::anyhow!(
501 "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
502 )
503 })?;
504 Ok(Arc::new(Mutex::new(owned)))
505 }
506 }
507 }
508
509 pub fn close_pipe(&self, value: &Value) -> Result<()> {
515 let Some(handle) = value.as_pipe_handle() else {
516 anyhow::bail!(
517 "host close_pipe needs a PIPE value, got {}",
518 value.type_name()
519 );
520 };
521 let Some(backend) = oxdock_pipe::script_backend(&handle) else {
522 anyhow::bail!(
523 "host close_pipe needs a script-materialized pipe (unbound and OS handles cannot be force-closed)"
524 );
525 };
526 backend.force_close();
527 Ok(())
528 }
529
530 pub fn is_cancelled(&self) -> bool {
534 self.state
535 .cancel_token
536 .load(std::sync::atomic::Ordering::SeqCst)
537 }
538
539 pub fn cancel_token(&self) -> Arc<AtomicBool> {
544 Arc::clone(&self.state.cancel_token)
545 }
546
547 pub fn cancel_hub(&self) -> Arc<oxdock_process::CancelHub> {
551 Arc::clone(&self.state.cancel_hub)
552 }
553
554 pub fn is_async_task(&self) -> bool {
557 self.state.inside_async
558 }
559
560 pub fn module_state<T: Send + Sync + 'static>(
566 &self,
567 module: &str,
568 ) -> Option<std::sync::Arc<T>> {
569 self.state
570 .module_states
571 .get(&(module.to_string(), std::any::TypeId::of::<T>()))?
572 .clone()
573 .downcast::<T>()
574 .ok()
575 }
576
577 pub fn pipe_backend(&self, value: &Value) -> Option<Arc<PipeInner>> {
584 let handle = value.as_pipe_handle()?;
585 oxdock_pipe::script_backend(&handle)
586 }
587}
588
589#[allow(clippy::too_many_arguments)]
590pub(super) fn execute_steps<P: ProcessManager>(
591 state: &mut ExecState<P>,
592 process: &mut P,
593 steps: &[Step],
594 stdin: CommandStdin,
595 expose_stdin: bool,
596 out: Option<StreamHandle>,
597 err: Option<StreamHandle>,
598 out_pipe: Option<Arc<PipeInner>>,
599 stdin_pipe: Option<Arc<PipeInner>>,
600 wait_at_end: bool,
601) -> Result<Flow> {
602 let generation = allocate_assert_generation();
603 let flow = match execute_steps_inner(
604 state,
605 process,
606 generation,
607 steps,
608 stdin,
609 expose_stdin,
610 out,
611 err,
612 out_pipe,
613 stdin_pipe,
614 wait_at_end,
615 ) {
616 Ok(flow) => flow,
617 Err(e) => {
618 teardown_tasks_on_error(state);
624 cleanup_assertion_generation(state, generation)?;
625 return Err(e);
626 }
627 };
628 cleanup_assertion_generation(state, generation)?;
630 Ok(flow)
631}
632
633fn cleanup_assertion_generation<P: ProcessManager>(
636 state: &mut ExecState<P>,
637 generation: usize,
638) -> Result<()> {
639 let mut windows = match state.assert_windows.lock() {
640 Ok(guard) => guard,
641 Err(_) => bail!("assert_windows poisoned"),
642 };
643 windows.retain(|(g, _), _| *g != generation);
644 let mut stderr_windows = match state.assert_windows_stderr.lock() {
645 Ok(guard) => guard,
646 Err(_) => bail!("assert_windows_stderr poisoned"),
647 };
648 stderr_windows.retain(|(g, _), _| *g != generation);
649 let mut exact = match state.exact_stdout.lock() {
650 Ok(guard) => guard,
651 Err(_) => bail!("exact_stdout poisoned"),
652 };
653 exact.retain(|g, _| *g != generation);
654 Ok(())
655}
656
657fn teardown_tasks_on_error<P: ProcessManager>(state: &mut ExecState<P>) {
662 for survivor in state.bg_children.iter_mut() {
663 let _ = survivor.kill();
664 }
665 state.bg_children.clear();
666 if state.inside_async {
667 return;
668 }
669 let entries: Vec<Arc<TaskEntry>> = {
670 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
671 named.values().cloned().collect()
672 };
673 let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
674 for entry in &entries {
675 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
676 match guard.phase {
677 TaskPhase::Running | TaskPhase::Awaiting => {
678 guard.phase = TaskPhase::Cancelled;
679 if let Some(handle) = guard.handle.take() {
680 to_kill.push((Arc::clone(entry), handle));
681 }
682 }
683 TaskPhase::Cancelled | TaskPhase::Completed => {}
684 }
685 }
686 for (entry, mut handle) in to_kill {
687 let _ = handle.kill();
688 entry.finish_teardown();
689 }
690}
691
692#[allow(clippy::too_many_arguments)]
695pub(super) fn execute_single_step_with_generation<P: ProcessManager>(
696 state: &mut ExecState<P>,
697 process: &mut P,
698 cmd: &StepKind,
699 generation: usize,
700 idx: usize,
701 stdin: CommandStdin,
702 expose_stdin: bool,
703 out: Option<StreamHandle>,
704 err: Option<StreamHandle>,
705 out_pipe: Option<Arc<PipeInner>>,
706 stdin_pipe: Option<Arc<PipeInner>>,
707) -> Result<Flow> {
708 let mut cx = StepCtx {
709 state,
710 process,
711 stdin,
712 expose_stdin,
713 out,
714 err,
715 out_pipe,
716 stdin_pipe,
717 };
718 match cmd {
722 StepKind::FuncDef { .. }
723 | StepKind::Call { .. }
724 | StepKind::Return { .. }
725 | StepKind::While { .. }
726 | StepKind::Break
727 | StepKind::Continue
728 | StepKind::For { .. }
729 | StepKind::If { .. }
730 | StepKind::Timeout { .. }
731 | StepKind::Isolated { .. }
732 | StepKind::WithIo { .. }
733 | StepKind::AssignCapture { .. } => {
734 return dispatch_flow_step(cmd, &mut cx, generation, idx);
735 }
736 _ => {}
737 }
738 match cmd {
739 StepKind::Run(arg) => {
740 let cmd = super::args::resolve_arg(arg, &mut cx)?;
741 let cmd = super::args::expand_dsl_vars(&cmd, cx.state);
742 handlers::run(&mut cx, idx, &cmd)
743 }
744 StepKind::RunExec { argv } => {
745 let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
746 handlers::run_argv(&mut cx, idx, &resolved)
747 }
748 StepKind::Echo(arg) => {
749 let msg = super::args::resolve_arg(arg, &mut cx)?;
750 handlers::echo(&mut cx, &msg)
751 }
752 StepKind::AsyncBlock { .. } => handlers::dispatch_async_block(cmd, &mut cx),
753 StepKind::Workdir(arg) => {
754 let path = super::args::resolve_arg(arg, &mut cx)?;
755 handlers::workdir(&mut cx, idx, &path)
756 }
757 StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
758 StepKind::RemoteBlock {
759 target,
760 vars,
761 env,
762 body,
763 } => super::remote::run_remote_block(&mut cx, target, vars, env, body, idx),
764 StepKind::Env { key, value } => {
765 let resolved = super::args::resolve_arg(value, &mut cx)?;
766 handlers::env(&mut cx, key, &resolved)
767 }
768 StepKind::InheritEnv { keys } => {
769 handlers::inherit_env(&mut cx, keys)?;
770 sync_iteration_assert_needles(
771 cx.state,
772 &[Step {
773 guard: None,
774 kind: cmd.clone(),
775 scope_enter: 0,
776 scope_exit: 0,
777 }],
778 generation,
779 )?;
780 Ok(())
781 }
782 StepKind::IsolatedInheritEnv { keys } => {
783 handlers::isolated_inherit_env(&mut cx, keys)?;
784 Ok(())
785 }
786 StepKind::Copy {
787 from_workspace,
788 from_host,
789 to_host,
790 from,
791 to,
792 } => {
793 if *from_host || *to_host {
794 super::remote::copy_transfer(&mut cx, *from_host, *to_host, from, to)
795 } else {
796 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
797 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
798 handlers::copy(
799 &mut cx,
800 idx,
801 from_workspace.clone(),
802 &from_resolved,
803 &to_resolved,
804 )
805 }
806 }
807 StepKind::CopyGit {
808 rev,
809 from,
810 to,
811 include_dirty,
812 } => {
813 let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
814 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
815 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
816 handlers::copy_git(
817 &mut cx,
818 idx,
819 &rev_resolved,
820 &from_resolved,
821 &to_resolved,
822 *include_dirty,
823 )
824 }
825 StepKind::HashSha256 { path } => {
826 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
827 handlers::hash_sha256(&mut cx, idx, &path_resolved)
828 }
829 StepKind::Archive { src, dst, raw } => {
830 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
831 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
832 handlers::archive(&mut cx, idx, &src_resolved, &dst_resolved, *raw)
833 }
834 StepKind::Unarchive {
835 src,
836 dst,
837 max_bytes,
838 } => {
839 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
840 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
841 let cap_resolved = super::args::resolve_arg_opt(max_bytes, &mut cx)?;
842 handlers::unarchive(
843 &mut cx,
844 idx,
845 &src_resolved,
846 &dst_resolved,
847 cap_resolved.as_deref(),
848 )
849 }
850 StepKind::Symlink {
851 from_workspace,
852 from,
853 to,
854 } => {
855 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
856 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
857 handlers::symlink(
858 &mut cx,
859 idx,
860 from_workspace.clone(),
861 &from_resolved,
862 &to_resolved,
863 )
864 }
865 StepKind::Mkdir(arg) => {
866 let path = super::args::resolve_arg(arg, &mut cx)?;
867 handlers::mkdir(&mut cx, idx, &path)
868 }
869 StepKind::Install { from, to } => {
870 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
871 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
872 handlers::install(&mut cx, idx, &from_resolved, &to_resolved)
873 }
874 StepKind::Ls(arg) => {
875 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
876 handlers::ls(&mut cx, idx, &resolved)
877 }
878 StepKind::Cwd => handlers::cwd(&mut cx, idx),
879 StepKind::Read(arg) => {
880 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
881 handlers::read(&mut cx, idx, &resolved)
882 }
883 StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
884 StepKind::Prompt {
885 var,
886 message,
887 default,
888 } => {
889 let message_resolved = super::args::resolve_arg(message, &mut cx)?;
890 let default_resolved = match default {
891 Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
892 None => None,
893 };
894 handlers::prompt(
895 &mut cx,
896 idx,
897 var,
898 &message_resolved,
899 default_resolved.as_deref(),
900 )
901 }
902 StepKind::ListAppend { list, item } => {
903 let value = super::args::evaluate_assert_operand(item, &mut cx)?;
904 handlers::push_into(&mut cx, idx, list, value)
905 }
906 StepKind::Write { path, contents } => {
907 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
908 let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
909 handlers::write(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
910 }
911 StepKind::Append { path, contents } => {
912 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
913 let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
914 handlers::append(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
915 }
916 StepKind::Remove { path, recursive } => {
917 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
918 handlers::remove(&mut cx, idx, &path_resolved, *recursive)
919 }
920 StepKind::Expand { path, overrides } => {
921 let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
922 let overrides_resolved = super::args::resolve_overrides(overrides, &mut cx)?;
923 handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
924 }
925 StepKind::AssertEq {
926 hash,
927 actual,
928 expected,
929 } => {
930 let target = resolve_assert_target(actual, &mut cx)?;
931 let expected_resolved = match expected {
932 Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
933 None => None,
934 };
935 handlers::assert_eq(
936 &mut cx,
937 idx,
938 generation,
939 idx,
940 hash,
941 &target,
942 expected_resolved.as_ref(),
943 )
944 }
945 StepKind::AssertContains { haystack, needle } => {
946 let target = resolve_assert_target(haystack, &mut cx)?;
947 handlers::assert_contains(&mut cx, idx, generation, idx, &target, needle)
948 }
949 StepKind::WithIoBlock { .. } => {
950 bail!("WITH_IO block should have been expanded during parsing")
951 }
952 StepKind::Exit(code) => {
953 let code = super::args::resolve_arg_as_int(code, &mut cx)?;
954 handlers::exit(&mut cx, code)
955 }
956 StepKind::Assign {
957 var,
958 decl_type,
959 expr,
960 } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
961 StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
962 StepKind::AssignAsync {
963 var,
964 decl_type,
965 body,
966 } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
967 StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
968 StepKind::AwaitCapture {
969 out_var,
970 out_type,
971 task_var,
972 } => handlers::dispatch_await_capture(out_var, out_type.clone(), task_var, &mut cx),
973 StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
974 StepKind::Sleep { duration } => {
975 let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
976 handlers::sleep(&mut cx, idx, &duration)
977 }
978 StepKind::TypeAlias { .. } => {
979 Ok(())
982 }
983 StepKind::FuncDef { .. }
984 | StepKind::Call { .. }
985 | StepKind::Return { .. }
986 | StepKind::While { .. }
987 | StepKind::Break
988 | StepKind::Continue
989 | StepKind::For { .. }
990 | StepKind::If { .. }
991 | StepKind::Timeout { .. }
992 | StepKind::Isolated { .. }
993 | StepKind::WithIo { .. }
994 | StepKind::AssignCapture { .. } => {
995 unreachable!("compound steps dispatch before this match")
996 }
997 }?;
998 Ok(Flow::Done)
999}
1000
1001#[allow(clippy::too_many_arguments)]
1002fn execute_steps_inner<P: ProcessManager>(
1003 state: &mut ExecState<P>,
1004 process: &mut P,
1005 generation: usize,
1006 steps: &[Step],
1007 stdin: CommandStdin,
1008 expose_stdin: bool,
1009 out: Option<StreamHandle>,
1010 err: Option<StreamHandle>,
1011 out_pipe: Option<Arc<PipeInner>>,
1012 stdin_pipe: Option<Arc<PipeInner>>,
1013 wait_at_end: bool,
1014) -> Result<Flow> {
1015 pre_register_assertions(state, steps, generation)?;
1017
1018 for (idx, step) in steps.iter().enumerate() {
1019 if state.cancel_token.load(Ordering::SeqCst) {
1021 bail!("ASYNC task cancelled");
1022 }
1023 if step.scope_enter > 0 {
1024 for _ in 0..step.scope_enter {
1025 state.push_scope();
1026 }
1027 }
1028
1029 let should_run = guard_option_allows(step.guard.as_ref(), &state.envs);
1030 let flow_result: Result<Flow> = if !should_run {
1031 Ok(Flow::Done)
1032 } else {
1033 let mut cx = StepCtx {
1034 state,
1035 process,
1036 stdin: stdin.clone(),
1037 expose_stdin,
1038 out: out.clone(),
1039 err: err.clone(),
1040 out_pipe: out_pipe.clone(),
1041 stdin_pipe: stdin_pipe.clone(),
1042 };
1043 let flow_result: Result<Flow> = match &step.kind {
1046 StepKind::FuncDef { .. }
1047 | StepKind::Call { .. }
1048 | StepKind::Return { .. }
1049 | StepKind::While { .. }
1050 | StepKind::Break
1051 | StepKind::Continue
1052 | StepKind::For { .. }
1053 | StepKind::If { .. }
1054 | StepKind::Timeout { .. }
1055 | StepKind::Isolated { .. }
1056 | StepKind::WithIo { .. }
1057 | StepKind::AssignCapture { .. } => {
1058 dispatch_flow_step(&step.kind, &mut cx, generation, idx)
1059 }
1060 _ => {
1061 match &step.kind {
1062 StepKind::InheritEnv { keys } => {
1063 handlers::inherit_env(&mut cx, keys)?;
1064 sync_iteration_assert_needles(cx.state, steps, generation)?;
1065 Ok(())
1066 }
1067 StepKind::IsolatedInheritEnv { keys } => {
1068 handlers::isolated_inherit_env(&mut cx, keys)?;
1069 Ok(())
1070 }
1071 StepKind::Workdir(arg) => {
1072 let path = super::args::resolve_arg(arg, &mut cx)?;
1073 handlers::workdir(&mut cx, idx, &path)
1074 }
1075 StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
1076 StepKind::RemoteBlock {
1077 target,
1078 vars,
1079 env,
1080 body,
1081 } => super::remote::run_remote_block(&mut cx, target, vars, env, body, idx),
1082 StepKind::Env { key, value } => {
1083 let resolved = super::args::resolve_arg(value, &mut cx)?;
1084 handlers::env(&mut cx, key, &resolved)?;
1085 sync_iteration_assert_needles(cx.state, steps, generation)?;
1086 Ok(())
1087 }
1088 StepKind::Run(arg) => {
1089 let cmd = super::args::resolve_arg(arg, &mut cx)?;
1090 let cmd = super::args::expand_dsl_vars(&cmd, cx.state);
1091 handlers::run(&mut cx, idx, &cmd)
1092 }
1093 StepKind::RunExec { argv } => {
1094 let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
1095 handlers::run_argv(&mut cx, idx, &resolved)
1096 }
1097 StepKind::Echo(arg) => {
1098 let msg = super::args::resolve_arg(arg, &mut cx)?;
1099 handlers::echo(&mut cx, &msg)
1100 }
1101 StepKind::AsyncBlock { .. } => {
1102 handlers::dispatch_async_block(&step.kind, &mut cx)
1103 }
1104 StepKind::Copy {
1105 from_workspace,
1106 from_host,
1107 to_host,
1108 from,
1109 to,
1110 } => {
1111 if *from_host || *to_host {
1112 super::remote::copy_transfer(
1113 &mut cx, *from_host, *to_host, from, to,
1114 )
1115 } else {
1116 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1117 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1118 handlers::copy(
1119 &mut cx,
1120 idx,
1121 from_workspace.clone(),
1122 &from_resolved,
1123 &to_resolved,
1124 )
1125 }
1126 }
1127 StepKind::CopyGit {
1128 rev,
1129 from,
1130 to,
1131 include_dirty,
1132 } => {
1133 let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
1134 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1135 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1136 handlers::copy_git(
1137 &mut cx,
1138 idx,
1139 &rev_resolved,
1140 &from_resolved,
1141 &to_resolved,
1142 *include_dirty,
1143 )
1144 }
1145 StepKind::HashSha256 { path } => {
1146 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1147 handlers::hash_sha256(&mut cx, idx, &path_resolved)
1148 }
1149 StepKind::Archive { src, dst, raw } => {
1150 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
1151 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
1152 handlers::archive(&mut cx, idx, &src_resolved, &dst_resolved, *raw)
1153 }
1154 StepKind::Unarchive {
1155 src,
1156 dst,
1157 max_bytes,
1158 } => {
1159 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
1160 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
1161 let cap_resolved = super::args::resolve_arg_opt(max_bytes, &mut cx)?;
1162 handlers::unarchive(
1163 &mut cx,
1164 idx,
1165 &src_resolved,
1166 &dst_resolved,
1167 cap_resolved.as_deref(),
1168 )
1169 }
1170 StepKind::Symlink {
1171 from_workspace,
1172 from,
1173 to,
1174 } => {
1175 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1176 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1177 handlers::symlink(
1178 &mut cx,
1179 idx,
1180 from_workspace.clone(),
1181 &from_resolved,
1182 &to_resolved,
1183 )
1184 }
1185 StepKind::Mkdir(arg) => {
1186 let path = super::args::resolve_arg(arg, &mut cx)?;
1187 handlers::mkdir(&mut cx, idx, &path)
1188 }
1189 StepKind::Install { from, to } => {
1190 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1191 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1192 handlers::install(&mut cx, idx, &from_resolved, &to_resolved)
1193 }
1194 StepKind::Ls(arg) => {
1195 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1196 handlers::ls(&mut cx, idx, &resolved)
1197 }
1198 StepKind::Cwd => handlers::cwd(&mut cx, idx),
1199 StepKind::Read(arg) => {
1200 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1201 handlers::read(&mut cx, idx, &resolved)
1202 }
1203 StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
1204 StepKind::Prompt {
1205 var,
1206 message,
1207 default,
1208 } => {
1209 let message_resolved = super::args::resolve_arg(message, &mut cx)?;
1210 let default_resolved = match default {
1211 Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
1212 None => None,
1213 };
1214 handlers::prompt(
1215 &mut cx,
1216 idx,
1217 var,
1218 &message_resolved,
1219 default_resolved.as_deref(),
1220 )
1221 }
1222 StepKind::ListAppend { list, item } => {
1223 let value = super::args::evaluate_assert_operand(item, &mut cx)?;
1224 handlers::push_into(&mut cx, idx, list, value)
1225 }
1226 StepKind::Write { path, contents } => {
1227 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1228 let contents_resolved =
1229 super::args::resolve_arg_opt(contents, &mut cx)?;
1230 handlers::write(
1231 &mut cx,
1232 idx,
1233 &path_resolved,
1234 contents_resolved.as_deref(),
1235 )
1236 }
1237 StepKind::Append { path, contents } => {
1238 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1239 let contents_resolved =
1240 super::args::resolve_arg_opt(contents, &mut cx)?;
1241 handlers::append(
1242 &mut cx,
1243 idx,
1244 &path_resolved,
1245 contents_resolved.as_deref(),
1246 )
1247 }
1248 StepKind::Remove { path, recursive } => {
1249 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1250 handlers::remove(&mut cx, idx, &path_resolved, *recursive)
1251 }
1252 StepKind::Expand { path, overrides } => {
1253 let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
1254 let overrides_resolved =
1255 super::args::resolve_overrides(overrides, &mut cx)?;
1256 handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
1257 }
1258 StepKind::AssertEq {
1259 hash,
1260 actual,
1261 expected,
1262 } => {
1263 let target = resolve_assert_target(actual, &mut cx)?;
1264 let expected_resolved = match expected {
1265 Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
1266 None => None,
1267 };
1268 handlers::assert_eq(
1269 &mut cx,
1270 idx,
1271 generation,
1272 idx,
1273 hash,
1274 &target,
1275 expected_resolved.as_ref(),
1276 )
1277 }
1278 StepKind::AssertContains { haystack, needle } => {
1279 let target = resolve_assert_target(haystack, &mut cx)?;
1280 handlers::assert_contains(
1281 &mut cx, idx, generation, idx, &target, needle,
1282 )
1283 }
1284 StepKind::WithIoBlock { .. } => {
1285 bail!("WITH_IO block should have been expanded during parsing")
1286 }
1287 StepKind::Exit(code) => {
1288 let code = super::args::resolve_arg_as_int(code, &mut cx)?;
1289 handlers::exit(&mut cx, code)
1290 }
1291 StepKind::Assign {
1292 var,
1293 decl_type,
1294 expr,
1295 } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
1296 StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
1297 StepKind::AssignAsync {
1298 var,
1299 decl_type,
1300 body,
1301 } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
1302 StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
1303 StepKind::AwaitCapture {
1304 out_var,
1305 out_type,
1306 task_var,
1307 } => handlers::dispatch_await_capture(
1308 out_var,
1309 out_type.clone(),
1310 task_var,
1311 &mut cx,
1312 ),
1313 StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
1314 StepKind::Sleep { duration } => {
1315 let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
1316 handlers::sleep(&mut cx, idx, &duration)
1317 }
1318 StepKind::TypeAlias { .. } => {
1319 Ok(())
1322 }
1323 StepKind::FuncDef { .. }
1324 | StepKind::Call { .. }
1325 | StepKind::Return { .. }
1326 | StepKind::While { .. }
1327 | StepKind::Break
1328 | StepKind::Continue
1329 | StepKind::For { .. }
1330 | StepKind::If { .. }
1331 | StepKind::Timeout { .. }
1332 | StepKind::Isolated { .. }
1333 | StepKind::WithIo { .. }
1334 | StepKind::AssignCapture { .. } => {
1335 unreachable!("compound steps dispatch in the outer match")
1336 }
1337 }?;
1338 Ok(Flow::Done)
1339 }
1340 };
1341 flow_result
1342 };
1343
1344 let restore_result = restore_scopes(state, step.scope_exit);
1345 let expiry_drained = if let Some(expiry) = state.keeper_expiry.as_mut() {
1350 expiry.expire_step(steps, idx)
1351 } else {
1352 false
1353 };
1354 if expiry_drained {
1355 state.keeper_expiry = None;
1356 }
1357 let flow = flow_result?;
1358 restore_result?;
1359 match flow {
1360 Flow::Done => {}
1361 Flow::Break { .. } | Flow::Continue { .. } | Flow::Return { .. } => {
1362 return Ok(flow);
1363 }
1364 }
1365 }
1366
1367 let reap_named = !state.inside_async;
1375 let has_bg = !state.bg_children.is_empty();
1376 let named_pending = |state: &ExecState<P>| {
1377 reap_named
1378 && state
1379 .named_tasks
1380 .lock()
1381 .unwrap_or_else(|e| e.into_inner())
1382 .values()
1383 .any(|entry| !entry.state.lock().unwrap_or_else(|e| e.into_inner()).reaped)
1384 };
1385 let has_named = named_pending(state);
1386 if wait_at_end && (has_bg || has_named) {
1387 loop {
1388 let mut failed_status: Option<anyhow::Error> = None;
1389
1390 if failed_status.is_none() && state.cancel_token.load(Ordering::SeqCst) {
1395 failed_status = Some(anyhow::anyhow!("ASYNC task cancelled"));
1396 }
1397
1398 let mut i = 0;
1400 while i < state.bg_children.len() {
1401 match state.bg_children[i].try_wait() {
1402 Ok(Some(status)) => {
1403 if !status.success() && failed_status.is_none() {
1404 failed_status =
1405 Some(anyhow::anyhow!("ASYNC process exited with status {status}"));
1406 break;
1407 }
1408 state.bg_children.swap_remove(i);
1409 }
1410 Ok(None) => {
1411 i += 1;
1412 }
1413 Err(e) => {
1414 if failed_status.is_none() {
1415 failed_status = Some(e);
1416 }
1417 break;
1418 }
1419 }
1420 }
1421
1422 if failed_status.is_none() && reap_named {
1426 let entries: Vec<(u64, Arc<TaskEntry>)> = {
1427 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1428 named
1429 .iter()
1430 .map(|(id, entry)| (*id, Arc::clone(entry)))
1431 .collect()
1432 };
1433 for (id, entry) in &entries {
1434 enum Poll {
1435 Pending,
1436 CompletedOk,
1437 CompletedErr(anyhow::Error),
1438 }
1439 let poll = {
1440 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1441 match guard.phase {
1442 TaskPhase::Running | TaskPhase::Awaiting => {
1443 match guard.handle.as_mut() {
1444 Some(handle) => match handle.try_wait() {
1445 Ok(Some(status)) => {
1446 let _ = guard.handle.take();
1447 guard.phase = TaskPhase::Completed;
1448 if status.success() {
1449 Poll::CompletedOk
1450 } else {
1451 Poll::CompletedErr(anyhow::anyhow!(
1452 "named ASYNC task {id} exited with status {status}"
1453 ))
1454 }
1455 }
1456 Ok(None) => Poll::Pending,
1457 Err(e) => {
1458 let _ = guard.handle.take();
1459 guard.phase = TaskPhase::Completed;
1460 Poll::CompletedErr(e)
1461 }
1462 },
1463 None => Poll::Pending,
1466 }
1467 }
1468 TaskPhase::Cancelled | TaskPhase::Completed => Poll::Pending,
1469 }
1470 };
1471 match poll {
1472 Poll::Pending => {}
1473 Poll::CompletedOk => {
1474 entry.finish_teardown();
1475 }
1476 Poll::CompletedErr(e) => {
1477 entry.finish_teardown();
1478 if failed_status.is_none() {
1479 failed_status = Some(e);
1480 }
1481 break;
1482 }
1483 }
1484 }
1485 }
1486
1487 if let Some(err) = failed_status {
1492 for survivor in state.bg_children.iter_mut() {
1493 let _ = survivor.kill();
1494 }
1495 if reap_named {
1496 let entries: Vec<Arc<TaskEntry>> = {
1497 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1498 named.values().cloned().collect()
1499 };
1500 let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
1501 for entry in &entries {
1502 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1503 match guard.phase {
1504 TaskPhase::Running | TaskPhase::Awaiting => {
1505 guard.phase = TaskPhase::Cancelled;
1506 if let Some(handle) = guard.handle.take() {
1507 to_kill.push((Arc::clone(entry), handle));
1508 }
1509 }
1510 TaskPhase::Cancelled | TaskPhase::Completed => {}
1511 }
1512 }
1513 for (entry, mut handle) in to_kill {
1514 let _ = handle.kill();
1515 entry.finish_teardown();
1516 }
1517 }
1518 state.bg_children.clear();
1519 return Err(err);
1520 }
1521
1522 let bg_empty = state.bg_children.is_empty();
1523 if bg_empty && !named_pending(state) {
1524 return Ok(Flow::Done);
1525 }
1526 if reap_named {
1530 let unreaped: Vec<Arc<TaskEntry>> = {
1531 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1532 named
1533 .values()
1534 .filter(|entry| {
1535 let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1536 matches!(guard.phase, TaskPhase::Cancelled) && !guard.reaped
1537 })
1538 .cloned()
1539 .collect()
1540 };
1541 for entry in &unreaped {
1542 entry.wait_reaped();
1543 }
1544 }
1545 std::thread::sleep(std::time::Duration::from_millis(10));
1546 }
1547 }
1548
1549 Ok(Flow::Done)
1550}
1551
1552fn restore_scopes<P: ProcessManager>(state: &mut ExecState<P>, count: usize) -> Result<()> {
1553 for _ in 0..count {
1554 state.pop_scope()?;
1555 }
1556 Ok(())
1557}
1558
1559#[allow(clippy::too_many_arguments)]
1566pub(super) fn execute_scoped_remote_body<P: ProcessManager>(
1567 state: &mut ExecState<P>,
1568 process: &mut P,
1569 steps: &[Step],
1570 stdin: CommandStdin,
1571 expose_stdin: bool,
1572 out: Option<StreamHandle>,
1573 err: Option<StreamHandle>,
1574 out_pipe: Option<Arc<PipeInner>>,
1575 stdin_pipe: Option<Arc<PipeInner>>,
1576) -> Result<()> {
1577 let flow = execute_scoped_steps(
1578 state,
1579 process,
1580 steps,
1581 stdin,
1582 expose_stdin,
1583 out,
1584 err,
1585 out_pipe,
1586 stdin_pipe,
1587 true,
1588 )?;
1589 match flow {
1590 Flow::Done => Ok(()),
1591 Flow::Break { idx } => {
1592 bail!("step {}: BREAK cannot cross a REMOTE boundary", idx + 1);
1593 }
1594 Flow::Continue { idx } => {
1595 bail!("step {}: CONTINUE cannot cross a REMOTE boundary", idx + 1);
1596 }
1597 Flow::Return { idx, .. } => {
1598 bail!("step {}: RETURN cannot cross a REMOTE boundary", idx + 1);
1599 }
1600 }
1601}
1602
1603#[allow(clippy::too_many_arguments)]
1608pub(super) fn execute_scoped_steps<P: ProcessManager>(
1609 state: &mut ExecState<P>,
1610 process: &mut P,
1611 steps: &[Step],
1612 stdin: CommandStdin,
1613 expose_stdin: bool,
1614 out: Option<StreamHandle>,
1615 err: Option<StreamHandle>,
1616 out_pipe: Option<Arc<PipeInner>>,
1617 stdin_pipe: Option<Arc<PipeInner>>,
1618 wait_at_end: bool,
1619) -> Result<Flow> {
1620 state.push_scope();
1621 let res = execute_steps(
1622 state,
1623 process,
1624 steps,
1625 stdin,
1626 expose_stdin,
1627 out,
1628 err,
1629 out_pipe,
1630 stdin_pipe,
1631 wait_at_end,
1632 );
1633 let pop_res = state.pop_scope();
1636 match (res, pop_res) {
1637 (Ok(flow), Ok(())) => Ok(flow),
1638 (Err(e), _) => Err(e),
1639 (Ok(_), Err(e)) => Err(e),
1640 }
1641}
1642
1643fn dispatch_flow_step<P: ProcessManager>(
1647 cmd: &StepKind,
1648 cx: &mut StepCtx<'_, P>,
1649 generation: usize,
1650 idx: usize,
1651) -> Result<Flow> {
1652 match cmd {
1653 StepKind::FuncDef { name, params, body } => {
1654 handlers::define_func(cx, name, params, body)?;
1655 Ok(Flow::Done)
1656 }
1657 StepKind::Call { name, args } => {
1658 let _ = handlers::call_func_value(cx, idx, name, args)?;
1659 Ok(Flow::Done)
1660 }
1661 StepKind::Return { expr } => handlers::handle_return(cx, idx, expr),
1662 StepKind::While { cond, body } => handlers::while_loop(cx, idx, cond, body),
1663 StepKind::Break => Ok(Flow::Break { idx }),
1664 StepKind::Continue => Ok(Flow::Continue { idx }),
1665 StepKind::For {
1666 key_var,
1667 key_type,
1668 var,
1669 var_type,
1670 in_expr,
1671 body,
1672 } => handlers::for_loop(
1673 cx,
1674 key_var.as_deref(),
1675 key_type.clone(),
1676 var,
1677 var_type.clone(),
1678 in_expr,
1679 body,
1680 ),
1681 StepKind::If {
1682 cond,
1683 then_body,
1684 else_ifs,
1685 else_body,
1686 } => handlers::if_then(cx, cond, then_body, else_ifs, else_body),
1687 StepKind::Timeout { duration, body } => {
1688 let duration = super::args::resolve_arg_as_duration(duration, cx)?;
1689 handlers::timeout(cx, idx, &duration, body)
1690 }
1691 StepKind::Isolated { body } => handlers::isolated(cx, body),
1692 StepKind::WithIo { bindings, cmd } => handlers::with_io(cx, generation, idx, bindings, cmd),
1693 StepKind::AssignCapture {
1694 var,
1695 decl_type,
1696 cmd,
1697 } => handlers::assign_capture(cx, generation, idx, var, decl_type.clone(), cmd),
1698 _ => {
1699 unreachable!("dispatch_flow_step handles only compound steps")
1700 }
1701 }
1702}