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