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_isolated_inherit_env, dispatch_isolated_step, dispatch_ls,
37 dispatch_mkdir, dispatch_prompt, dispatch_push_into_step, dispatch_read, dispatch_read_line,
38 dispatch_remote, dispatch_remove, dispatch_return, dispatch_run, dispatch_run_exec,
39 dispatch_set, dispatch_sleep_step, dispatch_symlink, dispatch_timeout_step, dispatch_unarchive,
40 dispatch_while_loop, dispatch_with_io, dispatch_with_io_block, dispatch_workdir,
41 dispatch_workspace, dispatch_write,
42};
43pub use self::io::ExecIo;
44pub use self::io::PipeStream;
45pub use self::io::PushManifestSink;
46pub use self::native::{
47 FuncKind, FuncMeta, FuncParam, FunctionRegistry, HostModule, HostRegistration, NativeFn,
48 OxDockFn, ParamOption, PreRunCheck, PureFn, PureTable, RecordSchema, builtin_function_metas,
49 builtin_function_names, fill_optional_args, required_arity, std_module_table,
50};
51pub use self::state::ExecState;
52pub use self::steps::StepCtx;
53pub use self::typing::{
54 Field, LIST_TAG, MAP_TAG, OxDockType, TypeDescriptor, TypeTag, Value, ValuePayload,
55 check_options, check_value, check_value_at, clone_boxed, clone_copy, clone_shared, drop_boxed,
56 drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed, fmt_inline, fmt_shared,
57 load_inline, startup_descriptors, store_inline, type_anchor, unshare_boxed, unshare_inline,
58 unshare_shared,
59};
60
61use anyhow::Result;
62use oxdock_fs::{
63 GuardedPath, LazyGuardedTempDir, PathResolver, WorkspaceFs, reserve_cargo_scratch,
64};
65use oxdock_parser::Step;
66use oxdock_process::{
67 BuiltinEnv, DefaultProcessManager, ProcessManager, SharedInput, SharedOutput,
68 default_process_manager,
69};
70
71use std::collections::BTreeMap;
72use std::sync::Arc;
73
74use self::fs_ops::describe_dir;
75use self::io::{StreamHandle, assemble_default_io, teed_stderr, teed_stdout};
76use self::steps::execute_steps;
77
78pub const SNAPSHOT_PENDING_DISPLAY: &str = "<snapshot:pending>";
83
84pub const SNAPSHOT_TREE_UNAVAILABLE: &str = "<unavailable>";
88
89pub fn run_steps(fs_root: &GuardedPath, steps: &[Step]) -> Result<()> {
90 run_steps_with_context(fs_root, fs_root, steps)
91}
92
93pub fn run_steps_with_context(
94 fs_root: &GuardedPath,
95 build_context: &GuardedPath,
96 steps: &[Step],
97) -> Result<()> {
98 run_steps_with_context_result(fs_root, build_context, steps, None, None).map(|_| ())
99}
100
101pub fn run_steps_with_context_result(
103 fs_root: &GuardedPath,
104 build_context: &GuardedPath,
105 steps: &[Step],
106 stdin: Option<SharedInput>,
107 stdout: Option<SharedOutput>,
108) -> Result<GuardedPath> {
109 let io = assemble_default_io(stdin, stdout);
110 run_steps_with_context_result_with_io(fs_root, build_context, steps, io)
111}
112
113pub fn run_steps_with_context_result_with_io(
114 fs_root: &GuardedPath,
115 build_context: &GuardedPath,
116 steps: &[Step],
117 io: ExecIo,
118) -> Result<GuardedPath> {
119 match run_steps_inner(fs_root, build_context, steps, io) {
120 Ok(final_cwd) => Ok(final_cwd),
121 Err(err) => {
122 let fs = PathResolver::new(fs_root.as_path(), build_context.as_path())?;
123 let tree = describe_dir(&fs, fs_root, 2, 24);
124 let snapshot = format!(
125 "filesystem snapshot (root {}):\n{}",
126 fs_root.display(),
127 tree
128 );
129 Err(compose_error_with_snapshot(err, snapshot))
130 }
131 }
132}
133
134fn compose_error_with_snapshot(err: anyhow::Error, snapshot_section: String) -> anyhow::Error {
138 let chain = err.chain().map(|e| e.to_string()).collect::<Vec<_>>();
140 let mut primary = chain
141 .first()
142 .cloned()
143 .unwrap_or_else(|| "unknown error".into());
144 let rest = if chain.len() > 1 {
145 let first_cause = chain[1].clone();
146 primary = format!("{primary} ({first_cause})");
147 if chain.len() > 2 {
148 let causes = chain
149 .iter()
150 .skip(2)
151 .map(|s| s.as_str())
152 .collect::<Vec<_>>()
153 .join("\n ");
154 format!("\ncauses:\n {}", causes)
155 } else {
156 String::new()
157 }
158 } else {
159 String::new()
160 };
161 let msg = format!("{}{}\n{}", primary, rest, snapshot_section);
162 match exit::exit_code_of(&err) {
168 Some(code) => anyhow::Error::new(exit::ExitRequest(code)).context(msg),
169 None => anyhow::anyhow!(msg),
170 }
171}
172
173fn run_steps_inner(
174 fs_root: &GuardedPath,
175 build_context: &GuardedPath,
176 steps: &[Step],
177 io: ExecIo,
178) -> Result<GuardedPath> {
179 let mut resolver = PathResolver::new_guarded(fs_root.clone(), build_context.clone())?;
180 resolver.set_workspace_root(build_context.clone());
181 run_steps_with_fs_with_io(Box::new(resolver), steps, io)
182}
183
184pub struct LazyRunOutput {
189 pub final_cwd: GuardedPath,
190 pub snapshot: Arc<LazyGuardedTempDir>,
191 pub fs: Box<dyn WorkspaceFs>,
192 pub bindings: BTreeMap<String, Value>,
197}
198
199pub fn run_steps_with_lazy_snapshot(
203 build_context: &GuardedPath,
204 steps: &[Step],
205 io: ExecIo,
206) -> Result<LazyRunOutput> {
207 run_steps_with_lazy_snapshot_and_modules(build_context, steps, io, Vec::new(), Vec::new())
208}
209
210pub fn run_steps_with_lazy_snapshot_and_modules(
215 build_context: &GuardedPath,
216 steps: &[Step],
217 io: ExecIo,
218 modules: Vec<HostModule<DefaultProcessManager>>,
219 types: Vec<&'static TypeDescriptor>,
220) -> Result<LazyRunOutput> {
221 let mut resolver = PathResolver::new_lazy(build_context.clone())?;
222 resolver.set_workspace_root(build_context.clone());
223 let snapshot = resolver.snapshot_handle();
224 let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
225 match run_steps_with_manager_with_modules(
226 fs,
227 steps,
228 default_process_manager(),
229 io,
230 modules,
231 types,
232 ) {
233 Ok((final_cwd, fs, bindings)) => Ok(LazyRunOutput {
234 final_cwd,
235 snapshot,
236 fs,
237 bindings,
238 }),
239 Err(err) => Err(enrich_lazy_error(&snapshot, build_context, err)),
240 }
241}
242
243pub fn enrich_lazy_error(
248 snapshot: &Arc<LazyGuardedTempDir>,
249 build_context: &GuardedPath,
250 err: anyhow::Error,
251) -> anyhow::Error {
252 match snapshot.get() {
253 Some(concrete) => {
254 let tree = match PathResolver::new(concrete.as_path(), build_context.as_path()) {
255 Ok(describe_fs) => describe_dir(&describe_fs, concrete, 2, 24),
256 Err(_) => String::from(SNAPSHOT_TREE_UNAVAILABLE),
257 };
258 let snapshot_msg = format!(
259 "filesystem snapshot (root {}):\n{}",
260 concrete.display(),
261 tree
262 );
263 compose_error_with_snapshot(err, snapshot_msg)
264 }
265 None => compose_error_with_snapshot(
266 err,
267 String::from(
268 "filesystem snapshot: never materialized (no snapshot directory was created)",
269 ),
270 ),
271 }
272}
273
274pub fn run_steps_with_fs(
275 fs: Box<dyn WorkspaceFs>,
276 steps: &[Step],
277 stdin: Option<SharedInput>,
278 stdout: Option<SharedOutput>,
279) -> Result<GuardedPath> {
280 let io = assemble_default_io(stdin, stdout);
281 run_steps_with_fs_with_io(fs, steps, io)
282}
283
284pub fn run_steps_with_fs_with_io(
285 fs: Box<dyn WorkspaceFs>,
286 steps: &[Step],
287 io: ExecIo,
288) -> Result<GuardedPath> {
289 run_steps_with_manager(fs, steps, default_process_manager(), io).map(|(cwd, _, _)| cwd)
290}
291
292pub(crate) use oxdock_parser::base_name;
297
298#[allow(clippy::type_complexity)]
306pub fn run_steps_with_manager<P: ProcessManager>(
307 fs: Box<dyn WorkspaceFs>,
308 steps: &[Step],
309 process: P,
310 io: ExecIo,
311) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
312 run_steps_with_manager_with_modules(fs, steps, process, io, Vec::new(), Vec::new())
313}
314
315#[allow(clippy::type_complexity)]
323pub fn run_steps_with_manager_with_modules<P: ProcessManager>(
324 fs: Box<dyn WorkspaceFs>,
325 steps: &[Step],
326 process: P,
327 io: ExecIo,
328 modules: Vec<HostModule<P>>,
329 types: Vec<&'static self::typing::TypeDescriptor>,
330) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
331 let mut state = new_state(fs, io)?;
332 for module in &modules {
333 module.check_pre_run(steps)?;
336 }
337 for module in modules {
338 state.register_module(module);
339 }
340 for descriptor in types {
341 state.register_type(descriptor);
342 }
343 finish_run(state, process, steps)
344}
345
346fn new_state<P: ProcessManager>(fs: Box<dyn WorkspaceFs>, io: ExecIo) -> Result<ExecState<P>> {
347 let cwd = fs.root().clone();
348 let build_context = fs.build_context().clone();
349 let cargo_scratch = reserve_cargo_scratch()?;
350 let seed = Arc::new(oxdock_process::seed_defaults(
355 &cargo_scratch.tmp_seed_display(),
356 &cargo_scratch.target_seed_display(),
357 ));
358 let mut envs = (*seed).clone();
359 envs.extend(BuiltinEnv::collect(&build_context).into_envs());
360 for (key, value) in io.inherit_env_overrides() {
361 envs.insert(key.clone(), value.clone());
362 }
363 let envs = Arc::new(envs);
364 let assert_windows = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
365 let assert_windows_stderr = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
366 let exact_stdout = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
367 let mut state = ExecState {
368 fs,
369 cargo_scratch,
370 seed,
371 cwd,
372 envs,
373 bg_children: Vec::new(),
374 scope_stack: Vec::new(),
375 isolated_stack: Vec::new(),
376 io,
377 assert_windows: assert_windows.clone(),
378 assert_windows_stderr: assert_windows_stderr.clone(),
379 exact_stdout: exact_stdout.clone(),
380 var_scopes: Vec::new(),
381 cancel_token: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
382 active_process: std::sync::Arc::new(std::sync::Mutex::new(None)),
383 named_tasks: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
384 next_task_id: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1)),
385 inside_async: false,
386 keeper_expiry: None,
387 cancellable: false,
388 functions: self::native::FunctionRegistry::with_builtins(),
389 types: self::typing::startup_type_map(),
390 record_schemas: std::collections::HashMap::new(),
391 module_states: std::collections::HashMap::new(),
392 type_aliases: std::collections::HashMap::new(),
393 call_depth: 0,
394 task_id: 0,
396 push_manifest: Vec::new(),
397 _marker: std::marker::PhantomData,
398 };
399
400 state.push_var_scope();
402
403 Ok(state)
404}
405
406#[allow(clippy::type_complexity)]
407fn finish_run<P: ProcessManager>(
408 mut state: ExecState<P>,
409 process: P,
410 steps: &[Step],
411) -> Result<(GuardedPath, Box<dyn WorkspaceFs>, BTreeMap<String, Value>)> {
412 state.type_aliases = self::typing::collect_type_aliases(steps, &state)?;
416 state.validate_function_type_tags()?;
417 static_check::validate_script_types(steps, &state)?;
421 let assert_windows = Arc::clone(&state.assert_windows);
422 let assert_windows_stderr = Arc::clone(&state.assert_windows_stderr);
423 let exact_stdout = Arc::clone(&state.exact_stdout);
424 let _default_stdout = std::io::stdout();
425 let stdin = state.io.stdin().into();
426 let stdout = Some(StreamHandle::Stream(teed_stdout(
430 state.io.stdout(),
431 assert_windows,
432 exact_stdout,
433 )));
434 let stderr = state
435 .io
436 .stderr()
437 .map(|sink| StreamHandle::Stream(teed_stderr(Some(sink), assert_windows_stderr)));
438 let mut proc_mgr = process;
439 let flow = execute_steps(
440 &mut state,
441 &mut proc_mgr,
442 steps,
443 stdin,
444 false,
445 stdout,
446 stderr,
447 None,
448 None,
449 true,
450 )?;
451 match flow {
452 self::steps::Flow::Done => {
457 let bindings: BTreeMap<String, Value> = state
462 .var_scopes
463 .first()
464 .map(|scope| {
465 scope
466 .iter()
467 .map(|(k, (_, v))| (k.clone(), v.clone()))
468 .collect()
469 })
470 .unwrap_or_default();
471 Ok((state.fs.concretize_cwd(&state.cwd), state.fs, bindings))
472 }
473 self::steps::Flow::Break { idx } => {
474 anyhow::bail!("step {}: BREAK outside loop", idx + 1)
475 }
476 self::steps::Flow::Continue { idx } => {
477 anyhow::bail!("step {}: CONTINUE outside loop", idx + 1)
478 }
479 self::steps::Flow::Return { idx, .. } => {
480 anyhow::bail!(
484 "step {}: RETURN outside function, ASYNC task, or LET block",
485 idx + 1
486 )
487 }
488 }
489}