1mod args;
2mod capture;
3#[cfg(any(test, feature = "test-harness"))]
4pub mod conformance;
5mod engine;
6mod exit;
7mod fs_ops;
8mod handlers;
9mod io;
10mod native;
11pub mod remote;
12mod state;
13mod static_check;
14mod steps;
15#[cfg(test)]
16mod tests;
17mod typing;
18
19pub use self::remote::{
20 RemoteRequest, RemoteResponse, RemoteRunner, TransferStage, apply_push_dir, apply_push_file,
21 apply_push_symlink,
22};
23
24pub use self::args::{json_to_value, value_to_json};
25#[cfg(any(test, feature = "test-harness"))]
26pub use self::conformance::assert_module_returns_conformance;
27pub use self::engine::{Engine, EngineOutput};
28pub use self::exit::{ExitRequest, exit_code_of};
29pub(crate) use self::handlers::{
30 dispatch_append, dispatch_archive, dispatch_assert_contains, dispatch_assert_eq,
31 dispatch_assign, dispatch_assign_async_step, dispatch_assign_capture_step,
32 dispatch_async_block, dispatch_await_capture_step, dispatch_await_step, dispatch_break,
33 dispatch_call, dispatch_cancel_step, dispatch_continue, dispatch_copy, dispatch_copy_git,
34 dispatch_cwd, dispatch_echo, dispatch_env, dispatch_exit, dispatch_expand, dispatch_for_loop,
35 dispatch_func_def, dispatch_hash_sha256, dispatch_if_then, dispatch_inherit_env,
36 dispatch_install, dispatch_ls, dispatch_mkdir, dispatch_prompt, dispatch_push_into_step,
37 dispatch_read, dispatch_read_line, dispatch_remote, dispatch_remove, dispatch_return,
38 dispatch_run, dispatch_run_exec, dispatch_set, dispatch_sleep_step, dispatch_symlink,
39 dispatch_timeout_step, dispatch_unarchive, dispatch_while_loop, dispatch_with_io,
40 dispatch_with_io_block, dispatch_workdir, dispatch_workspace, dispatch_write,
41};
42pub use self::io::ExecIo;
43pub use self::io::PipeStream;
44pub use self::io::PushManifestSink;
45pub use self::native::{
46 FuncKind, FuncMeta, FuncParam, FunctionRegistry, HostModule, HostRegistration, NativeFn,
47 OxDockFn, ParamOption, PreRunCheck, PureFn, PureTable, RecordSchema, builtin_function_metas,
48 builtin_function_names, fill_optional_args, required_arity, std_module_table,
49};
50pub use self::state::ExecState;
51pub use self::steps::StepCtx;
52pub use self::typing::{
53 Field, LIST_TAG, MAP_TAG, OxDockType, TypeDescriptor, TypeTag, Value, ValuePayload,
54 check_options, check_value, check_value_at, clone_boxed, clone_copy, clone_shared, drop_boxed,
55 drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed, fmt_inline, fmt_shared,
56 load_inline, startup_descriptors, store_inline, type_anchor, unshare_boxed, unshare_inline,
57 unshare_shared,
58};
59
60use anyhow::Result;
61use oxdock_fs::{
62 GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, reserve_cargo_scratch,
63};
64use oxdock_parser::Step;
65use oxdock_process::{
66 BuiltinEnv, DefaultProcessManager, ProcessManager, SharedInput, SharedOutput,
67 default_process_manager,
68};
69
70use std::collections::BTreeMap;
71use std::sync::Arc;
72
73use self::fs_ops::describe_dir;
74use self::io::{StreamHandle, assemble_default_io, teed_stderr, teed_stdout};
75use self::steps::execute_steps;
76
77pub const SNAPSHOT_PENDING_DISPLAY: &str = "<snapshot:pending>";
82
83pub const SNAPSHOT_TREE_UNAVAILABLE: &str = "<unavailable>";
87
88pub fn run_steps(fs_root: &GuardedPath, steps: &[Step]) -> Result<()> {
89 run_steps_with_context(fs_root, fs_root, steps)
90}
91
92pub fn run_steps_with_context(
93 fs_root: &GuardedPath,
94 build_context: &GuardedPath,
95 steps: &[Step],
96) -> Result<()> {
97 run_steps_with_context_result(fs_root, build_context, steps, None, None).map(|_| ())
98}
99
100pub fn run_steps_with_context_result(
102 fs_root: &GuardedPath,
103 build_context: &GuardedPath,
104 steps: &[Step],
105 stdin: Option<SharedInput>,
106 stdout: Option<SharedOutput>,
107) -> Result<GuardedPath> {
108 let io = assemble_default_io(stdin, stdout);
109 run_steps_with_context_result_with_io(fs_root, build_context, steps, io)
110}
111
112pub fn run_steps_with_context_result_with_io(
113 fs_root: &GuardedPath,
114 build_context: &GuardedPath,
115 steps: &[Step],
116 io: ExecIo,
117) -> Result<GuardedPath> {
118 match run_steps_inner(fs_root, build_context, steps, io) {
119 Ok(final_cwd) => Ok(final_cwd),
120 Err(err) => {
121 let fs = PathResolver::new(fs_root.as_path(), build_context.as_path())?;
122 let tree = describe_dir(&fs, fs_root, 2, 24);
123 let snapshot = format!(
124 "filesystem snapshot (root {}):\n{}",
125 fs_root.display(),
126 tree
127 );
128 Err(compose_error_with_snapshot(err, snapshot))
129 }
130 }
131}
132
133fn compose_error_with_snapshot(err: anyhow::Error, snapshot_section: String) -> anyhow::Error {
137 let chain = err.chain().map(|e| e.to_string()).collect::<Vec<_>>();
139 let mut primary = chain
140 .first()
141 .cloned()
142 .unwrap_or_else(|| "unknown error".into());
143 let rest = if chain.len() > 1 {
144 let first_cause = chain[1].clone();
145 primary = format!("{primary} ({first_cause})");
146 if chain.len() > 2 {
147 let causes = chain
148 .iter()
149 .skip(2)
150 .map(|s| s.as_str())
151 .collect::<Vec<_>>()
152 .join("\n ");
153 format!("\ncauses:\n {}", causes)
154 } else {
155 String::new()
156 }
157 } else {
158 String::new()
159 };
160 let msg = format!("{}{}\n{}", primary, rest, snapshot_section);
161 match exit::exit_code_of(&err) {
167 Some(code) => anyhow::Error::new(exit::ExitRequest(code)).context(msg),
168 None => anyhow::anyhow!(msg),
169 }
170}
171
172fn run_steps_inner(
173 fs_root: &GuardedPath,
174 build_context: &GuardedPath,
175 steps: &[Step],
176 io: ExecIo,
177) -> Result<GuardedPath> {
178 let mut resolver = PathResolver::new_guarded(fs_root.clone(), build_context.clone())?;
179 resolver.set_workspace_root(build_context.clone());
180 run_steps_with_fs_with_io(Box::new(resolver), steps, io)
181}
182
183pub struct LazyRunOutput {
188 pub final_cwd: GuardedPath,
189 pub snapshot: Arc<LazyGuardedTempDir>,
190 pub fs: Box<dyn WorkspaceFs>,
191 pub bindings: BTreeMap<String, Value>,
196}
197
198pub fn run_steps_with_lazy_snapshot(
202 build_context: &GuardedPath,
203 steps: &[Step],
204 io: ExecIo,
205) -> Result<LazyRunOutput> {
206 run_steps_with_lazy_snapshot_and_modules(build_context, steps, io, Vec::new(), Vec::new())
207}
208
209pub fn run_steps_with_lazy_snapshot_and_modules(
214 build_context: &GuardedPath,
215 steps: &[Step],
216 io: ExecIo,
217 modules: Vec<HostModule<DefaultProcessManager>>,
218 types: Vec<&'static TypeDescriptor>,
219) -> Result<LazyRunOutput> {
220 let mut resolver = PathResolver::new_lazy(build_context.clone())?;
221 resolver.set_workspace_root(build_context.clone());
222 let snapshot = resolver.snapshot_handle();
223 let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
224 match run_steps_with_manager_with_modules(
225 fs,
226 steps,
227 default_process_manager(),
228 io,
229 modules,
230 types,
231 ) {
232 Ok((final_cwd, fs, bindings)) => Ok(LazyRunOutput {
233 final_cwd,
234 snapshot,
235 fs,
236 bindings,
237 }),
238 Err(err) => Err(enrich_lazy_error(&snapshot, build_context, err)),
239 }
240}
241
242pub fn enrich_lazy_error(
247 snapshot: &Arc<LazyGuardedTempDir>,
248 build_context: &GuardedPath,
249 err: anyhow::Error,
250) -> anyhow::Error {
251 match snapshot.get() {
252 Some(concrete) => {
253 let tree = match PathResolver::new(concrete.as_path(), build_context.as_path()) {
254 Ok(describe_fs) => describe_dir(&describe_fs, concrete, 2, 24),
255 Err(_) => String::from(SNAPSHOT_TREE_UNAVAILABLE),
256 };
257 let snapshot_msg = format!(
258 "filesystem snapshot (root {}):\n{}",
259 concrete.display(),
260 tree
261 );
262 compose_error_with_snapshot(err, snapshot_msg)
263 }
264 None => compose_error_with_snapshot(
265 err,
266 String::from(
267 "filesystem snapshot: never materialized (no snapshot directory was created)",
268 ),
269 ),
270 }
271}
272
273pub fn run_steps_with_fs(
274 fs: Box<dyn WorkspaceFs>,
275 steps: &[Step],
276 stdin: Option<SharedInput>,
277 stdout: Option<SharedOutput>,
278) -> Result<GuardedPath> {
279 let io = assemble_default_io(stdin, stdout);
280 run_steps_with_fs_with_io(fs, steps, io)
281}
282
283pub fn run_steps_with_fs_with_io(
284 fs: Box<dyn WorkspaceFs>,
285 steps: &[Step],
286 io: ExecIo,
287) -> Result<GuardedPath> {
288 run_steps_with_manager(fs, steps, default_process_manager(), io).map(|(cwd, _, _)| cwd)
289}
290
291pub(crate) use oxdock_parser::base_name;
296
297#[allow(clippy::type_complexity)]
305pub fn run_steps_with_manager<P: ProcessManager>(
306 fs: Box<dyn WorkspaceFs>,
307 steps: &[Step],
308 process: P,
309 io: ExecIo,
310) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
311 run_steps_with_manager_with_modules(fs, steps, process, io, Vec::new(), Vec::new())
312}
313
314#[allow(clippy::type_complexity)]
322pub fn run_steps_with_manager_with_modules<P: ProcessManager>(
323 fs: Box<dyn WorkspaceFs>,
324 steps: &[Step],
325 process: P,
326 io: ExecIo,
327 modules: Vec<HostModule<P>>,
328 types: Vec<&'static self::typing::TypeDescriptor>,
329) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
330 let mut state = new_state(fs, io)?;
331 for module in &modules {
332 module.check_pre_run(steps)?;
335 }
336 for module in modules {
337 state.register_module(module);
338 }
339 for descriptor in types {
340 state.register_type(descriptor);
341 }
342 finish_run(state, process, steps)
343}
344
345fn new_state<P: ProcessManager>(fs: Box<dyn WorkspaceFs>, io: ExecIo) -> Result<ExecState<P>> {
346 let cwd = fs.root().clone();
347 let build_context = fs.build_context().clone();
348 let mut envs = BuiltinEnv::collect(&build_context).into_envs();
349 for (key, value) in io.inherit_env_overrides() {
350 envs.insert(key.clone(), value.clone());
351 }
352 let envs = Arc::new(envs);
353 let assert_windows = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
354 let assert_windows_stderr = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
355 let exact_stdout = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
356 let mut state = ExecState {
357 fs,
358 cargo_scratch: reserve_cargo_scratch()?,
359 cwd,
360 envs,
361 bg_children: Vec::new(),
362 scope_stack: Vec::new(),
363 io,
364 assert_windows: assert_windows.clone(),
365 assert_windows_stderr: assert_windows_stderr.clone(),
366 exact_stdout: exact_stdout.clone(),
367 var_scopes: Vec::new(),
368 cancel_token: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
369 active_process: std::sync::Arc::new(std::sync::Mutex::new(None)),
370 named_tasks: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
371 next_task_id: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1)),
372 inside_async: false,
373 keeper_expiry: None,
374 cancellable: false,
375 functions: self::native::FunctionRegistry::with_builtins(),
376 types: self::typing::startup_type_map(),
377 record_schemas: std::collections::HashMap::new(),
378 module_states: std::collections::HashMap::new(),
379 type_aliases: std::collections::HashMap::new(),
380 call_depth: 0,
381 task_id: 0,
383 push_manifest: Vec::new(),
384 _marker: std::marker::PhantomData,
385 };
386
387 state.push_var_scope();
389
390 Ok(state)
391}
392
393#[allow(clippy::type_complexity)]
394fn finish_run<P: ProcessManager>(
395 mut state: ExecState<P>,
396 process: P,
397 steps: &[Step],
398) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
399 state.type_aliases = self::typing::collect_type_aliases(steps, &state)?;
403 state.validate_function_type_tags()?;
404 static_check::validate_script_types(steps, &state)?;
408 let assert_windows = Arc::clone(&state.assert_windows);
409 let assert_windows_stderr = Arc::clone(&state.assert_windows_stderr);
410 let exact_stdout = Arc::clone(&state.exact_stdout);
411 let _default_stdout = std::io::stdout();
412 let stdin = state.io.stdin().into();
413 let stdout = Some(StreamHandle::Stream(teed_stdout(
417 state.io.stdout(),
418 assert_windows,
419 exact_stdout,
420 )));
421 let stderr = state
422 .io
423 .stderr()
424 .map(|sink| StreamHandle::Stream(teed_stderr(Some(sink), assert_windows_stderr)));
425 let mut proc_mgr = process;
426 let flow = execute_steps(
427 &mut state,
428 &mut proc_mgr,
429 steps,
430 stdin,
431 false,
432 stdout,
433 stderr,
434 None,
435 None,
436 true,
437 )?;
438 match flow {
439 self::steps::Flow::Done => {
444 let bindings: BTreeMap<String, Value> = state
449 .var_scopes
450 .first()
451 .map(|scope| {
452 scope
453 .iter()
454 .map(|(k, (_, v))| (k.clone(), v.clone()))
455 .collect()
456 })
457 .unwrap_or_default();
458 Ok((state.fs.concretize_cwd(&state.cwd), state.fs, bindings))
459 }
460 self::steps::Flow::Break { idx } => {
461 anyhow::bail!("step {}: BREAK outside loop", idx + 1)
462 }
463 self::steps::Flow::Continue { idx } => {
464 anyhow::bail!("step {}: CONTINUE outside loop", idx + 1)
465 }
466 self::steps::Flow::Return { idx, .. } => {
467 anyhow::bail!(
471 "step {}: RETURN outside function, ASYNC task, or LET block",
472 idx + 1
473 )
474 }
475 }
476}