use anyhow::{Context, Result, anyhow, bail};
use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex};
use flate2::Compression;
use flate2::write::GzEncoder;
use oxdock_fs::CopySourceRoot;
use oxdock_fs::EntryKind;
use oxdock_fs::GuardedPath;
use oxdock_fs::PathResolver;
use oxdock_fs::PolicyPath;
use oxdock_fs::command_path;
use oxdock_fs::to_forward_slashes;
use oxdock_parser::{
Arg, Expr, IoBinding, IoStream, PipeTarget, Step, StepKind, TypeTag, Value, WorkspaceTarget,
render_structural,
};
use oxdock_process::{
BackgroundHandle, CommandOptions, CommandResult, CommandStderr, CommandStdin, CommandStdout,
INHERIT_STDOUT_ENV_VAR, PROCESS_DEBUG_ENV_VAR, ProcessManager, SharedInput, batch_shell,
check_spawn_anchors, read_pump_chunk,
};
use oxdock_pty::{PtyInput, PtyOutcome, PtyRequest, WatchSize, run_pty_session};
use oxdock_remote_proto::tar::{StreamedEntry, sanitize_rel, unpack_auto_from};
use sha2::{Digest, Sha256};
use super::args::parse_bool_str;
use super::fs_ops::copy_entry;
use super::io::{StreamHandle, TaskTee, TeeStream, write_stdout};
use super::native::FuncBody;
use super::state::{ExecState, MAX_CALL_DEPTH, TaskPhase};
use super::steps::{Flow, StepCtx, TtyRequest};
use oxdock_pipe::{KeeperGuard, PipeHandle, PipeInner, SharedOutput};
fn top_level_flow(flow: Flow) -> Result<()> {
match flow {
Flow::Done => Ok(()),
Flow::Break { idx } => {
bail!("step {}: BREAK outside loop", idx + 1);
}
Flow::Continue { idx } => {
bail!("step {}: CONTINUE outside loop", idx + 1);
}
Flow::Return { idx, .. } => {
bail!(
"step {}: RETURN outside function, ASYNC task, or LET block",
idx + 1
);
}
}
}
pub(super) fn inherit_env<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
keys: &[String],
) -> Result<()> {
let mut removals: Vec<String> = Vec::new();
let mut inserts: Vec<(String, String)> = Vec::new();
for key in keys {
if cx.state.io.inherit_env_is_removed(key) {
removals.push(key.clone());
continue;
}
if let Some(value) = cx.state.io.inherit_env_value(key).cloned() {
inserts.push((key.clone(), value));
continue;
}
if let Ok(value) = std::env::var(key) {
inserts.push((key.clone(), value));
}
}
let envs = Arc::make_mut(&mut cx.state.envs);
for key in removals {
envs.remove(&key);
}
for (key, value) in inserts {
envs.insert(key, value);
}
Ok(())
}
pub(super) fn workdir<P: ProcessManager>(cx: &mut StepCtx<'_, P>, path: &str) -> Result<()> {
cx.state.cwd = cx
.state
.fs
.resolve_workdir(&cx.state.effective_cwd(), path)
.with_context(|| format!("WORKDIR {}", path))?;
Ok(())
}
pub(super) fn workspace<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
target: &WorkspaceTarget,
) -> Result<()> {
match target {
WorkspaceTarget::Snapshot => {
cx.state.fs.switch_to_snapshot();
cx.state.cwd = cx.state.fs.root().clone();
}
WorkspaceTarget::Local => {
cx.state.fs.switch_to_local();
cx.state.cwd = cx.state.fs.root().clone();
}
WorkspaceTarget::Cache { local } => {
cx.state.fs.switch_to_cache(*local);
cx.state.cwd = cx.state.fs.root().clone();
}
WorkspaceTarget::System => {
cx.state.fs.switch_to_system();
let cwd = cx.state.cwd.clone();
cx.state.cwd = cx.state.fs.system_entry_cwd(&cwd);
}
}
Ok(())
}
pub(super) fn env<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
key: &str,
value: &str,
) -> Result<()> {
Arc::make_mut(&mut cx.state.envs).insert(key.to_owned(), value.to_owned());
Ok(())
}
pub(super) fn run<P: ProcessManager>(cx: &mut StepCtx<'_, P>, cmd: &str) -> Result<()> {
if let Some(tty) = cx.tty {
return run_pty(cx, &tty_shell_argv(cmd), tty, cmd, true);
}
let ctx = cx.state.command_ctx()?;
let step_stdin = if cx.expose_stdin {
cx.stdin.clone()
} else {
CommandStdin::Null
};
let inherit_override = cx
.state
.envs
.get(INHERIT_STDOUT_ENV_VAR)
.map(|v| parse_bool_str(v).unwrap_or(false))
.unwrap_or(false);
if std::env::var(PROCESS_DEBUG_ENV_VAR).is_ok() {
eprintln!(
"DEBUG: step RUN {} inherit_override={}",
cmd, inherit_override
);
}
let stdout_mode = if inherit_override {
CommandStdout::Inherit
} else {
cx.out
.clone()
.map(|handle| handle.to_stdout())
.unwrap_or(CommandStdout::Inherit)
};
let stderr_mode = if inherit_override {
CommandStderr::Inherit
} else {
cx.err
.clone()
.map(|handle| handle.to_stderr())
.unwrap_or(CommandStderr::Inherit)
};
let mut options = if cx.state.inside_async || cx.state.cancellable {
CommandOptions::background()
} else {
CommandOptions::foreground()
};
options.stdin = step_stdin;
options.stdout = stdout_mode;
options.stderr = stderr_mode;
{
use std::sync::atomic::Ordering;
if cx.state.cancel_token.load(Ordering::SeqCst) {
bail!("RUN {} interrupted by cancellation", cmd);
}
}
let mut handle = match cx
.process
.spawn_command(&ctx, cmd, options)
.with_context(|| format!("RUN {}", cmd))?
{
CommandResult::Background(h) => h,
CommandResult::Completed => return Ok(()),
CommandResult::Captured(_) => {
bail!("RUN {} unexpectedly captured output", cmd)
}
};
{
let mut guard = cx
.state
.active_process
.lock()
.unwrap_or_else(|e| e.into_inner());
*guard = Some(Box::new(handle.clone()));
}
{
use std::sync::atomic::Ordering;
if cx.state.cancel_token.load(Ordering::SeqCst) {
let _ = handle.kill();
bail!("RUN {} interrupted by cancellation", cmd);
}
}
let status = handle.wait();
{
let mut guard = cx
.state
.active_process
.lock()
.unwrap_or_else(|e| e.into_inner());
*guard = None;
}
let status = status?;
if !status.success() {
bail!("RUN {} exited with status {}", cmd, status);
}
Ok(())
}
pub(super) fn run_argv<P: ProcessManager>(cx: &mut StepCtx<'_, P>, argv: &[String]) -> Result<()> {
if let Some(tty) = cx.tty {
let what = format!("{argv:?}");
return run_pty(cx, argv, tty, &what, false);
}
let ctx = cx.state.command_ctx()?;
let step_stdin = if cx.expose_stdin {
cx.stdin.clone()
} else {
CommandStdin::Null
};
let inherit_override = cx
.state
.envs
.get(INHERIT_STDOUT_ENV_VAR)
.map(|v| parse_bool_str(v).unwrap_or(false))
.unwrap_or(false);
if std::env::var(PROCESS_DEBUG_ENV_VAR).is_ok() {
eprintln!(
"DEBUG: step RUN {:?} inherit_override={}",
argv, inherit_override
);
}
let stdout_mode = if inherit_override {
CommandStdout::Inherit
} else {
cx.out
.clone()
.map(|handle| handle.to_stdout())
.unwrap_or(CommandStdout::Inherit)
};
let stderr_mode = if inherit_override {
CommandStderr::Inherit
} else {
cx.err
.clone()
.map(|handle| handle.to_stderr())
.unwrap_or(CommandStderr::Inherit)
};
let mut options = if cx.state.inside_async || cx.state.cancellable {
CommandOptions::background()
} else {
CommandOptions::foreground()
};
options.stdin = step_stdin;
options.stdout = stdout_mode;
options.stderr = stderr_mode;
{
use std::sync::atomic::Ordering;
if cx.state.cancel_token.load(Ordering::SeqCst) {
bail!("RUN {argv:?} interrupted by cancellation");
}
}
let mut handle = match cx
.process
.spawn_argv(&ctx, argv, options)
.with_context(|| format!("RUN {argv:?}"))?
{
CommandResult::Background(h) => h,
CommandResult::Completed => return Ok(()),
CommandResult::Captured(_) => {
bail!("RUN {argv:?} unexpectedly captured output",)
}
};
{
let mut guard = cx
.state
.active_process
.lock()
.unwrap_or_else(|e| e.into_inner());
*guard = Some(Box::new(handle.clone()));
}
{
use std::sync::atomic::Ordering;
if cx.state.cancel_token.load(Ordering::SeqCst) {
let _ = handle.kill();
bail!("RUN {argv:?} interrupted by cancellation");
}
}
let status = handle.wait();
{
let mut guard = cx
.state
.active_process
.lock()
.unwrap_or_else(|e| e.into_inner());
*guard = None;
}
let status = status?;
if !status.success() {
bail!("RUN {argv:?} exited with status {}", status);
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn run_pty<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
argv: &[String],
tty: TtyRequest,
what: &str,
shell: bool,
) -> Result<()> {
use std::sync::atomic::Ordering;
if argv.is_empty() {
bail!("RUN {what} needs at least a program");
}
if cx.state.cancel_token.load(Ordering::SeqCst) {
bail!("RUN {what} interrupted by cancellation");
}
if std::env::var(PROCESS_DEBUG_ENV_VAR).is_ok() {
eprintln!("DEBUG: step RUN {what} under tty {tty:?}");
}
let ctx = cx.state.command_ctx()?;
let staged = ctx.envs().as_ref().clone();
check_spawn_anchors(&argv[0], &staged, shell)?;
let cwd = match ctx.cwd() {
PolicyPath::Guarded(p) => command_path(p).to_string_lossy().into_owned(),
PolicyPath::Unguarded(p) => p.as_path().to_string_lossy().into_owned(),
};
let input = match &cx.stdin {
CommandStdin::Null | CommandStdin::Inherit
if !cx.process.stdin_is_terminal() || cx.stdin.is_redirected() =>
{
None
}
CommandStdin::Null | CommandStdin::Inherit => oxdock_pty::acquire_host_stdin(),
CommandStdin::Stream(reader) => match cx.stdin_pipe.clone() {
Some(backend) => {
let reader = reader.clone();
Some(PtyInput {
read_chunk: Box::new(move |buf| read_pump_chunk(&reader, buf)),
cancel: Box::new(move || {
backend.cancel();
}),
})
}
None => None,
},
#[cfg(not(miri))]
CommandStdin::OsPipe(_) => {
bail!(
"WITH_IO [tty] stdin cannot arrive on a live OS pipe; bind a script pipe with stdin=$var"
)
}
};
let output: SharedOutput = match &cx.out {
Some(StreamHandle::Stream(writer)) => writer.clone(),
None => Arc::new(Mutex::new(std::io::stdout())),
#[cfg(not(miri))]
Some(StreamHandle::Os(_)) => {
bail!(
"WITH_IO [tty] stdout cannot arrive on a live OS pipe; bind a script pipe with stdout=$var"
)
}
};
let hub = cx.cancel_hub();
let token = cx.cancel_token();
let size = oxdock_pty::resolve_size(tty.rows, tty.cols);
let outcome = run_pty_session(PtyRequest {
argv: argv.to_vec(),
env: staged.into_iter().collect(),
cwd,
initial_size: size,
input,
output,
size_source: WatchSize::following_host(tty.rows, tty.cols),
should_cancel: Box::new(move || hub.is_cancelled() || token.load(Ordering::SeqCst)),
on_exit: None,
on_output_drained: None,
func: "RUN",
})
.with_context(|| format!("RUN {what}"))?;
match outcome {
PtyOutcome::Completed(code) => {
if code != 0 {
bail!("RUN {what} exited with status {code}");
}
Ok(())
}
PtyOutcome::Cancelled => {
bail!("RUN {what} interrupted by cancellation");
}
}
}
fn tty_shell_argv(cmd: &str) -> Vec<String> {
#[allow(clippy::disallowed_macros)]
let flag = if cfg!(windows) { "/C" } else { "-c" };
vec![batch_shell(), flag.to_string(), cmd.to_string()]
}
pub(super) fn resolve_run_exec_argv<P: ProcessManager>(
argv: &[Arg],
cx: &mut StepCtx<'_, P>,
) -> Result<Vec<String>> {
let mut out = Vec::new();
for arg in argv {
match arg {
Arg::String(_, _) | Arg::Parts(_) => {
out.push(super::args::resolve_arg(arg, cx)?);
}
Arg::Expr(Expr::Literal(v)) if v.as_str().is_some() => {
let s = v.as_str().unwrap_or_default().to_string();
out.push(super::args::expand_string(&s, &cx.state.envs, cx.state)?);
}
Arg::Expr(e) => {
let val = super::args::evaluate_expr(e, cx)?;
flatten_exec_value(&val, &mut out)?;
}
}
}
if out.is_empty() {
bail!("RUN exec form requires at least one argument");
}
Ok(out)
}
fn flatten_exec_value(val: &Value, out: &mut Vec<String>) -> Result<()> {
if let Some(s) = val.as_str() {
out.push(s.to_string());
return Ok(());
}
if let Some(i) = val.as_i64() {
out.push(i.to_string());
return Ok(());
}
if let Some(f) = val.as_f64() {
out.push(f.to_string());
return Ok(());
}
if let Some(b) = val.as_bool() {
out.push(b.to_string());
return Ok(());
}
if val.as_pipe_handle().is_some() {
anyhow::bail!(
"cannot pass PIPE as a command argument: pipes carry streams between steps, not text. Capture the producing step's output with LET $var: STRING = ... instead."
);
}
if val.as_semaphore().is_some() {
anyhow::bail!(
"cannot pass SEMAPHORE as a command argument: semaphores coordinate task access between steps, not text."
);
}
if val.as_permit().is_some() {
anyhow::bail!(
"cannot pass PERMIT as a command argument: permits grant scoped task access, not text."
);
}
if let Some(d) = val.as_duration() {
out.push(oxdock_parser::command::format_duration(&d));
return Ok(());
}
if let Some(p) = val.as_path() {
out.push(p.to_string_lossy().to_string());
return Ok(());
}
if let Some(items) = val.as_list() {
for item in items {
flatten_exec_value(item, out)?;
}
return Ok(());
}
if val.as_map().is_some() {
bail!("RUN exec form element must be a string, got map");
}
if let Some(id) = val.as_handle() {
bail!("RUN exec form element must be a string, got task handle task#{id}");
}
out.push(format!("{val}"));
Ok(())
}
pub(super) fn echo<P: ProcessManager>(cx: &mut StepCtx<'_, P>, msg: &str) -> Result<()> {
let line = format!("{msg}\n");
write_stdout(cx.out.clone(), |writer| {
writer.write_all(line.as_bytes())?;
Ok(())
})?;
Ok(())
}
pub(crate) fn dispatch_sleep_step<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Sleep { duration } = step else {
unreachable!()
};
let duration = super::args::resolve_arg_as_duration(duration, cx)?;
sleep(cx, &duration)
}
pub(crate) fn sleep<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
duration: &std::time::Duration,
) -> Result<()> {
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
let start = Instant::now();
loop {
if cx.state.cancel_token.load(Ordering::SeqCst) {
bail!("SLEEP interrupted by cancellation");
}
let elapsed = start.elapsed();
if elapsed >= *duration {
return Ok(());
}
let remaining = duration.saturating_sub(elapsed);
std::thread::sleep(remaining.min(Duration::from_millis(10)));
}
}
pub(super) fn copy_source_root(target: WorkspaceTarget) -> CopySourceRoot {
match target {
WorkspaceTarget::Snapshot => CopySourceRoot::Snapshot,
WorkspaceTarget::Local => CopySourceRoot::Local,
WorkspaceTarget::Cache { .. } => CopySourceRoot::Cache,
WorkspaceTarget::System => CopySourceRoot::System,
}
}
pub(super) fn copy<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
from_workspace: Option<WorkspaceTarget>,
from: &str,
to: &str,
) -> Result<()> {
let from_abs = if let Some(target) = from_workspace {
cx.state
.fs
.resolve_copy_source_from_target(copy_source_root(target), from)
.with_context(|| format!("COPY {} {}", from, to))?
} else {
cx.state
.fs
.resolve_copy_source(from)
.with_context(|| format!("COPY {} {}", from, to))?
};
let to_abs = cx
.state
.fs
.resolve_write(&cx.state.effective_cwd(), to)
.with_context(|| format!("COPY {} {}", from, to))?;
let to_abs = place_file_in_dir(cx.state.fs.as_ref(), &from_abs, to, &to_abs)
.with_context(|| format!("COPY {} {}", from, to))?;
copy_entry(cx.state.fs.as_ref(), &from_abs, &to_abs)
.with_context(|| format!("COPY {} {}", from, to))?;
Ok(())
}
fn place_file_in_dir(
fs: &dyn oxdock_fs::WorkspaceFs,
from_abs: &GuardedPath,
to: &str,
to_abs: &GuardedPath,
) -> Result<GuardedPath> {
if !matches!(fs.entry_kind(from_abs), Ok(EntryKind::File)) {
return Ok(to_abs.clone());
}
let trailing_slash = to.ends_with('/') || to.ends_with('\\');
let dst_is_dir = matches!(fs.entry_kind(to_abs), Ok(EntryKind::Dir));
if !trailing_slash && !dst_is_dir {
return Ok(to_abs.clone());
}
let base = from_abs
.as_path()
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.with_context(|| format!("COPY source has no file name: {}", from_abs.display()))?;
to_abs
.join(&base)
.with_context(|| format!("COPY destination escapes root: {}", to_abs.display()))
}
#[allow(clippy::too_many_arguments)]
pub(super) fn copy_git<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
rev: &str,
from: &str,
to: &str,
include_dirty: bool,
) -> Result<()> {
let to_abs = cx
.state
.fs
.resolve_write(&cx.state.effective_cwd(), to)
.with_context(|| format!("COPY_GIT {} {} {}", rev, from, to))?;
cx.state
.fs
.copy_from_git(rev, from, &to_abs, include_dirty)
.with_context(|| format!("COPY_GIT {} {} {}", rev, from, to))?;
Ok(())
}
fn archive_entry_mode(meta: &std::fs::Metadata, default: u32) -> u32 {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = default;
meta.permissions().mode() & 0o7777
}
#[cfg(not(unix))]
{
let _ = meta;
default
}
}
fn resolve_archive_src<P: ProcessManager>(
cx: &StepCtx<'_, P>,
src: &str,
tag: &str,
) -> Result<GuardedPath> {
let trimmed = to_forward_slashes(src).trim_end_matches('/').to_string();
let (parent, name) = match trimmed.rfind('/') {
Some(0) => ("/".to_string(), trimmed[1..].to_string()),
Some(idx) => (trimmed[..idx].to_string(), trimmed[idx + 1..].to_string()),
None => (String::new(), trimmed),
};
if name.is_empty() || name == "." || name == ".." {
return cx
.state
.fs
.resolve_read(&cx.state.effective_cwd(), src)
.with_context(|| tag.to_string());
}
let parent_abs = if parent.is_empty() {
cx.state.effective_cwd()
} else {
cx.state
.fs
.resolve_read(&cx.state.effective_cwd(), &parent)
.with_context(|| tag.to_string())?
};
let mut matched = false;
for entry in cx
.state
.fs
.read_dir_entries(&parent_abs)
.with_context(|| tag.to_string())?
{
if entry
.file_name()
.to_string_lossy()
.eq_ignore_ascii_case(&name)
{
matched = true;
let is_link = entry
.file_type()
.map(|kind| kind.is_symlink())
.unwrap_or(true);
if is_link {
bail!("{tag}: refuses to pack symlink source {src:?}");
}
}
}
if !matched {
return cx
.state
.fs
.resolve_read(&cx.state.effective_cwd(), src)
.with_context(|| tag.to_string());
}
parent_abs.join(&name).with_context(|| tag.to_string())
}
type ArchiveTree = (Vec<(String, GuardedPath)>, Vec<(String, GuardedPath)>);
fn collect_archive_tree(
fs: &dyn oxdock_fs::WorkspaceFs,
src_abs: &GuardedPath,
src: &str,
dst: &str,
) -> Result<ArchiveTree> {
let tag = format!("ARCHIVE {src} {dst}");
match fs.entry_kind(src_abs).with_context(|| tag.clone())? {
EntryKind::File => {
let base = src_abs
.as_path()
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.with_context(|| {
format!("{tag}: source has no file name: {}", src_abs.display())
})?;
let rel = sanitize_rel(&to_forward_slashes(&base)).with_context(|| tag.clone())?;
Ok((vec![(rel, src_abs.clone())], Vec::new()))
}
EntryKind::Dir => {
let mut files = Vec::new();
let mut dirs = Vec::new();
let mut stack = vec![(src_abs.clone(), String::new())];
while let Some((dir_abs, dir_rel)) = stack.pop() {
PathResolver::refuse_link_ancestors(src_abs, &dir_rel)
.with_context(|| tag.clone())?;
let mut entries = fs.read_dir_entries(&dir_abs).with_context(|| tag.clone())?;
entries.sort_by_key(|entry| entry.file_name());
for entry in entries {
let name = entry.file_name().to_string_lossy().to_string();
let joined = if dir_rel.is_empty() {
name.clone()
} else {
format!("{dir_rel}/{name}")
};
let child_rel = to_forward_slashes(&joined);
let is_link = entry
.file_type()
.map(|kind| kind.is_symlink())
.unwrap_or(true);
if is_link {
bail!("{tag}: refuses to pack symlink {child_rel:?}");
}
let child = dir_abs.join(&name).with_context(|| tag.clone())?;
match fs.entry_kind(&child).with_context(|| tag.clone())? {
EntryKind::Dir => {
dirs.push((child_rel.clone(), child.clone()));
stack.push((child, child_rel));
}
EntryKind::File => files.push((child_rel, child)),
EntryKind::Symlink => {
unreachable!("following entry_kind never reports symlinks")
}
}
}
}
files.sort_by(|a, b| a.0.cmp(&b.0));
dirs.sort_by(|a, b| a.0.cmp(&b.0));
Ok((files, dirs))
}
EntryKind::Symlink => unreachable!("following entry_kind never reports symlinks"),
}
}
fn append_archive_tree<W: std::io::Write>(
fs: &dyn oxdock_fs::WorkspaceFs,
builder: &mut tar::Builder<W>,
files: &[(String, GuardedPath)],
dirs: &[(String, GuardedPath)],
src_abs: &GuardedPath,
tag: &str,
) -> Result<()> {
for (rel, guard) in dirs {
let rel = sanitize_rel(rel).with_context(|| tag.to_string())?;
let mode = fs
.metadata(guard)
.map(|meta| archive_entry_mode(&meta, 0o755))
.with_context(|| tag.to_string())?;
let mut header = tar::Header::new_gnu();
header.set_mode(mode);
header.set_entry_type(tar::EntryType::Directory);
header.set_size(0);
header.set_cksum();
builder
.append_data(&mut header, &rel, std::io::empty())
.with_context(|| tag.to_string())?;
}
for (rel, guard) in files {
let rel = sanitize_rel(rel).with_context(|| tag.to_string())?;
let meta = fs.metadata(guard).with_context(|| tag.to_string())?;
let mut reader = fs
.open_read_nofollow(guard, src_abs)
.with_context(|| tag.to_string())?;
let mut header = tar::Header::new_gnu();
header.set_mode(archive_entry_mode(&meta, 0o644));
header.set_size(meta.len());
header.set_cksum();
builder
.append_data(&mut header, &rel, &mut reader)
.with_context(|| tag.to_string())?;
}
Ok(())
}
pub(super) fn archive<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
src: &str,
dst: &str,
raw: bool,
) -> Result<()> {
let tag = format!("ARCHIVE {src} {dst}");
let src_abs = resolve_archive_src(cx, src, &tag)?;
let dst_abs = cx
.state
.fs
.resolve_write(&cx.state.effective_cwd(), dst)
.with_context(|| tag.clone())?;
if dst_abs == src_abs {
bail!("{tag}: destination {dst:?} cannot be the source itself");
}
if dst_abs.as_path().starts_with(src_abs.as_path()) && dst_abs.exists() {
bail!("{tag}: destination {dst:?} cannot overwrite inside the packed tree");
}
let (files, dirs) = collect_archive_tree(cx.state.fs.as_ref(), &src_abs, src, dst)?;
cx.state
.fs
.ensure_parent_dir(&dst_abs)
.with_context(|| tag.clone())?;
let out = cx
.state
.fs
.open_write(&dst_abs)
.with_context(|| tag.clone())?;
if raw {
let mut builder = tar::Builder::new(out);
append_archive_tree(
cx.state.fs.as_ref(),
&mut builder,
&files,
&dirs,
&src_abs,
&tag,
)?;
let mut out = builder.into_inner().with_context(|| tag.clone())?;
std::io::Write::flush(&mut out).with_context(|| tag.clone())?;
} else {
let encoder = GzEncoder::new(out, Compression::default());
let mut builder = tar::Builder::new(encoder);
append_archive_tree(
cx.state.fs.as_ref(),
&mut builder,
&files,
&dirs,
&src_abs,
&tag,
)?;
builder
.into_inner()
.with_context(|| tag.clone())?
.try_finish()
.with_context(|| tag.clone())?;
}
Ok(())
}
pub(super) fn unarchive<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
src: &str,
dst: &str,
max_bytes: Option<&str>,
) -> Result<()> {
let tag = format!("UNARCHIVE {src} {dst}");
let cap = match max_bytes {
Some(raw) => oxdock_parser::command::parse_byte_count(raw)
.with_context(|| format!("{tag}: --max-bytes {raw:?}"))?,
None => DEFAULT_UNARCHIVE_MAX_BYTES,
};
let src_abs = cx
.state
.fs
.resolve_read(&cx.state.effective_cwd(), src)
.with_context(|| tag.clone())?;
let dst_abs = cx
.state
.fs
.resolve_write(&cx.state.effective_cwd(), dst)
.with_context(|| tag.clone())?;
cx.state
.fs
.create_dir_all(&dst_abs)
.with_context(|| tag.clone())?;
let reader = cx
.state
.fs
.open_read(&src_abs)
.with_context(|| tag.clone())?;
let fs = cx.state.fs.as_ref();
let mut deferred_dir_modes: Vec<(GuardedPath, u32)> = Vec::new();
let mut remaining = cap;
unpack_auto_from(reader, &mut |entry| {
let entry_tag = format!("{tag}: member");
match entry {
StreamedEntry::Dir { path, mode } => {
let rel = sanitize_rel(&path).with_context(|| entry_tag.clone())?;
PathResolver::refuse_link_ancestors(&dst_abs, &rel)
.with_context(|| entry_tag.clone())?;
let dir = dst_abs.join(&rel).with_context(|| entry_tag.clone())?;
fs.create_dir_all(&dir).with_context(|| entry_tag.clone())?;
deferred_dir_modes.push((dir, mode));
}
StreamedEntry::File { path, mode, reader } => {
let rel = sanitize_rel(&path).with_context(|| entry_tag.clone())?;
PathResolver::refuse_link_ancestors(&dst_abs, &rel)
.with_context(|| entry_tag.clone())?;
let file = dst_abs.join(&rel).with_context(|| entry_tag.clone())?;
fs.ensure_parent_dir(&file)
.with_context(|| entry_tag.clone())?;
let mut out = fs
.open_write_nofollow(&file, &dst_abs)
.with_context(|| entry_tag.clone())?;
let mut capped = CappedReader {
inner: reader,
remaining,
};
std::io::copy(&mut capped, &mut out).map_err(|e| {
if e.kind() == std::io::ErrorKind::QuotaExceeded {
anyhow!(
"{entry_tag}: archive exceeds the {cap}-byte expansion cap at {path:?}"
)
} else {
anyhow::Error::new(e).context(entry_tag.clone())
}
})?;
remaining = capped.remaining;
std::io::Write::flush(&mut out).with_context(|| entry_tag.clone())?;
restore_archive_mode(fs, &file, mode).with_context(|| entry_tag.clone())?;
}
StreamedEntry::Symlink { path, target } => {
bail!("{entry_tag}: refuses symlink member {path:?} -> {target:?}");
}
}
Ok(())
})
.with_context(|| tag.clone())?;
for (dir, mode) in deferred_dir_modes.into_iter().rev() {
restore_archive_mode(fs, &dir, mode).with_context(|| format!("{tag}: restoring mode"))?;
}
Ok(())
}
const DEFAULT_UNARCHIVE_MAX_BYTES: u64 = 1024 * 1024 * 1024;
struct CappedReader<'a> {
inner: &'a mut dyn std::io::Read,
remaining: u64,
}
impl std::io::Read for CappedReader<'_> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if buf.is_empty() {
return Ok(0);
}
if self.remaining == 0 {
let mut probe = [0u8; 1];
if self.inner.read(&mut probe)? == 0 {
return Ok(0);
}
return Err(std::io::Error::new(
std::io::ErrorKind::QuotaExceeded,
"archive member exceeds the expansion cap",
));
}
let allowed = (buf.len() as u64).min(self.remaining) as usize;
let n = self.inner.read(&mut buf[..allowed])?;
self.remaining -= n as u64;
Ok(n)
}
}
fn restore_archive_mode(
fs: &dyn oxdock_fs::WorkspaceFs,
path: &GuardedPath,
mode: u32,
) -> Result<()> {
let mode = mode & 0o7777;
if mode != 0 {
fs.set_permissions_mode_unix(path, mode)?;
}
Ok(())
}
pub(super) fn symlink<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
from_workspace: Option<WorkspaceTarget>,
from: &str,
to: &str,
) -> Result<()> {
let to_abs = cx
.state
.fs
.resolve_write(&cx.state.effective_cwd(), to)
.with_context(|| format!("SYMLINK {} {}", from, to))?;
let from_abs = if let Some(target) = from_workspace {
cx.state
.fs
.resolve_copy_source_from_target(copy_source_root(target), from)
.with_context(|| format!("SYMLINK {} {}", from, to))?
} else {
cx.state
.fs
.resolve_copy_source(from)
.with_context(|| format!("SYMLINK {} {}", from, to))?
};
let to_abs = if to.ends_with('/') || to.ends_with('\\') {
let base = link_base_name(&from_abs, from)?;
to_abs
.join(&base)
.with_context(|| format!("SYMLINK {} {}", from, to))?
} else if matches!(cx.state.fs.entry_kind(&to_abs), Ok(EntryKind::Dir)) {
let base = link_base_name(&from_abs, from)?;
to_abs
.join(&base)
.with_context(|| format!("SYMLINK {} {}", from, to))?
} else {
to_abs
};
cx.state
.fs
.symlink(&from_abs, &to_abs)
.with_context(|| format!("SYMLINK {} {}", from, to))?;
Ok(())
}
fn link_base_name(from_abs: &GuardedPath, from: &str) -> Result<String> {
from_abs
.as_path()
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.with_context(|| format!("SYMLINK source has no file name: {from}"))
}
pub(super) fn mkdir<P: ProcessManager>(cx: &mut StepCtx<'_, P>, path: &str) -> Result<()> {
let target = cx
.state
.fs
.resolve_write(&cx.state.effective_cwd(), path)
.with_context(|| format!("MKDIR {}", path))?;
cx.state
.fs
.create_dir_all(&target)
.with_context(|| format!("failed to create dir {}", target.display()))?;
Ok(())
}
pub(super) fn ls<P: ProcessManager>(cx: &mut StepCtx<'_, P>, arg: &Option<String>) -> Result<()> {
let target_dir = if let Some(p) = arg {
cx.state
.fs
.resolve_read(&cx.state.effective_cwd(), p)
.with_context(|| format!("LS {}", p))?
} else {
cx.state
.fs
.resolve_read(&cx.state.effective_cwd(), ".")
.with_context(|| "LS".to_string())?
};
let mut entries = cx
.state
.fs
.read_dir_entries(&target_dir)
.with_context(|| format!("LS {}", target_dir.display()))?;
entries.sort_by_key(|e| e.file_name());
write_stdout(cx.out.clone(), |writer| {
writeln!(writer, "{}:", target_dir.display())?;
for entry in &entries {
writeln!(writer, "{}", entry.file_name().to_string_lossy())?;
}
Ok(())
})?;
Ok(())
}
pub(super) fn read<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
path_opt: &Option<String>,
) -> Result<()> {
if let Some(path) = path_opt {
let target = cx
.state
.fs
.resolve_read(&cx.state.effective_cwd(), path)
.with_context(|| format!("READ {}", path))?;
let mut reader = cx
.state
.fs
.open_read(&target)
.with_context(|| format!("failed to open {}", target.display()))?;
write_stdout(cx.out.clone(), |writer| {
let mut buf = [0u8; super::io::CHUNK_SIZE];
loop {
let n = reader.read(&mut buf).context("failed to read from file")?;
if n == 0 {
break;
}
writer
.write_all(&buf[..n])
.context("failed to write to output")?;
}
Ok(())
})?;
} else {
let CommandStdin::Stream(input_stream) = cx.stdin.clone() else {
bail!("READ requires stdin (use WITH_IO [stdin=...] READ)");
};
let mut buf = [0u8; super::io::CHUNK_SIZE];
loop {
let n = {
let mut guard = input_stream
.lock()
.map_err(|_| anyhow!("failed to lock stdin for READ"))?;
guard.read(&mut buf).context("failed to read from stdin")?
};
if n == 0 {
break;
}
write_stdout(cx.out.clone(), |writer| {
writer
.write_all(&buf[..n])
.context("failed to write to output")
})?;
}
}
Ok(())
}
pub(super) fn read_line<P: ProcessManager>(cx: &mut StepCtx<'_, P>, var: &str) -> Result<()> {
let CommandStdin::Stream(input_stream) = cx.stdin.clone() else {
bail!("READ_LINE requires stdin (use WITH_IO [stdin=...] READ_LINE $var)");
};
let clean_var = var.trim_start_matches('$').to_string();
let mut buf = Vec::new();
let mut byte = [0u8; 1];
loop {
let n = {
let mut guard = input_stream
.lock()
.map_err(|_| anyhow!("failed to lock stdin for READ_LINE"))?;
guard.read(&mut byte).context("failed to read from stdin")?
};
if n == 0 {
break;
}
buf.push(byte[0]);
if byte[0] == b'\n' {
break;
}
}
let line = String::from_utf8(buf).context("READ_LINE received non-UTF8 bytes")?;
let line = line
.strip_suffix("\r\n")
.or_else(|| line.strip_suffix('\n'))
.unwrap_or(&line);
let text = Value::string(line.to_string());
if cx.state.get_var_typed(&clean_var).is_some() {
cx.state.mutate_var(&clean_var, text)?;
} else {
cx.state.declare_var(clean_var, TypeTag::String, text)?;
}
Ok(())
}
pub(super) fn inspect_var_map<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
var: &str,
) -> Result<BTreeMap<String, Value>> {
let clean_var = var.trim_start_matches('$').to_string();
let Some((decl_type, value)) = cx.state.get_var_typed(&clean_var) else {
bail!("variable '${clean_var}' is not defined");
};
let mut map = BTreeMap::new();
map.insert(
"type".to_string(),
Value::string(render_structural(&decl_type)),
);
map.insert("variable".to_string(), Value::string(clean_var.clone()));
match (decl_type, value.as_pipe_handle()) {
(TypeTag::Pipe, Some(handle)) => {
let info = cx.state.io.inspect_pipe(&handle);
map.insert("name".to_string(), Value::string(clean_var.clone()));
map.insert("value".to_string(), Value::string(format!("{value}")));
map.insert("is_os_pipe".to_string(), Value::bool(info.kind.is_os()));
map.insert(
"pipe_kind".to_string(),
Value::string(info.kind.as_str().to_string()),
);
map.insert(
"buffer_bytes".to_string(),
Value::int(info.buffered.min(i64::MAX as u64) as i64),
);
map.insert("readers".to_string(), Value::int(info.readers as i64));
map.insert("writers".to_string(), Value::int(info.writers as i64));
}
(TypeTag::Handle, _) => {
if let Some(task_id) = value.as_handle() {
map.insert("name".to_string(), Value::string(clean_var.clone()));
map.insert(
"value".to_string(),
Value::string(format!("task {task_id}")),
);
let phase = cx
.state
.named_tasks
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&task_id)
.map(|entry| {
let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
match guard.phase {
TaskPhase::Running => "Running",
TaskPhase::Awaiting => "Awaiting",
TaskPhase::Cancelled => "Cancelled",
TaskPhase::Completed => "Completed",
}
.to_string()
})
.unwrap_or_else(|| "unknown (already awaited?)".to_string());
map.insert("task_id".to_string(), Value::int(task_id as i64));
map.insert("task_phase".to_string(), Value::string(phase));
} else {
map.insert("name".to_string(), Value::string(clean_var.clone()));
map.insert("value".to_string(), Value::string(format!("{value}")));
}
}
_ => {
map.insert("name".to_string(), Value::string(clean_var.clone()));
map.insert("value".to_string(), Value::string(format!("{value}")));
}
}
Ok(map)
}
pub(super) fn write<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
path: &str,
contents: Option<&str>,
) -> Result<()> {
let target = cx
.state
.fs
.resolve_write(&cx.state.effective_cwd(), path)
.with_context(|| format!("WRITE {}", path))?;
cx.state
.fs
.ensure_parent_dir(&target)
.with_context(|| format!("failed to create parent for {}", target.display()))?;
if let Some(body) = contents {
cx.state
.fs
.write_file(&target, body.as_bytes())
.with_context(|| format!("failed to write {}", target.display()))?;
} else {
let CommandStdin::Stream(input_stream) = cx.stdin.clone() else {
bail!(
"WRITE {} requires stdin (use WITH_IO [stdin=...] WRITE)",
path
);
};
let mut guard = input_stream
.lock()
.map_err(|_| anyhow!("failed to lock stdin for WRITE"))?;
let mut writer = cx
.state
.fs
.open_write(&target)
.with_context(|| format!("failed to open {} for writing", target.display()))?;
let mut buf = [0u8; super::io::CHUNK_SIZE];
loop {
let n = guard
.read(&mut buf)
.context("failed to read from stdin for WRITE")?;
if n == 0 {
break;
}
writer
.write_all(&buf[..n])
.with_context(|| format!("failed to write to {}", target.display()))?;
writer.flush()?;
}
}
Ok(())
}
pub(super) fn append<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
path: &str,
contents: Option<&str>,
) -> Result<()> {
let target = cx
.state
.fs
.resolve_write(&cx.state.effective_cwd(), path)
.with_context(|| format!("APPEND {}", path))?;
cx.state
.fs
.ensure_parent_dir(&target)
.with_context(|| format!("failed to create parent for {}", target.display()))?;
if let Some(body) = contents {
cx.state
.fs
.append_file(&target, body.as_bytes())
.with_context(|| format!("failed to append to {}", target.display()))?;
} else {
let CommandStdin::Stream(input_stream) = cx.stdin.clone() else {
bail!(
"APPEND {} requires stdin (use WITH_IO [stdin=...] APPEND)",
path
);
};
let mut guard = input_stream
.lock()
.map_err(|_| anyhow!("failed to lock stdin for APPEND"))?;
let mut writer = cx
.state
.fs
.open_append(&target)
.with_context(|| format!("failed to open {} for appending", target.display()))?;
let mut buf = [0u8; super::io::CHUNK_SIZE];
loop {
let n = guard
.read(&mut buf)
.context("failed to read from stdin for APPEND")?;
if n == 0 {
break;
}
writer
.write_all(&buf[..n])
.with_context(|| format!("failed to append to {}", target.display()))?;
writer.flush()?;
}
}
Ok(())
}
pub(super) fn replace<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
path_opt: &Option<String>,
overrides: &[(String, String)],
) -> Result<()> {
let ctx = cx.state.command_ctx()?;
let vars = cx.state.all_vars();
let table = cx.state.pure_function_table();
let calls: oxdock_process::PlaceholderCall = Arc::new(move |module, func, args| {
let callee = table
.get(module)
.and_then(|entries| entries.get(func))
.ok_or_else(|| {
let mut known: Vec<String> = table
.iter()
.flat_map(|(m, entries)| entries.keys().map(move |f| format!("{m}::{f}")))
.collect();
known.sort();
anyhow!(
"unknown placeholder function '{module}::{func}'; known functions: {}",
known.join(", ")
)
})?;
callee(args)
});
let mut expander = oxdock_process::StreamingExpand::new(overrides, ctx.envs())
.with_vars(&vars)
.with_call_resolver(calls);
let mut out_buf = Vec::with_capacity(super::io::CHUNK_SIZE);
write_stdout(cx.out.clone(), |w| {
if let Some(path) = path_opt {
let target = cx
.state
.fs
.resolve_read(&cx.state.effective_cwd(), path)
.with_context(|| format!("EXPAND {}", path))?;
let mut reader = cx
.state
.fs
.open_read(&target)
.with_context(|| format!("failed to open {}", target.display()))?;
let mut buf = [0u8; super::io::CHUNK_SIZE];
loop {
let n = reader
.read(&mut buf)
.with_context(|| format!("failed to read {}", target.display()))?;
if n == 0 {
break;
}
expander.process_bytes(&buf[..n], &mut out_buf)?;
w.write_all(&out_buf).context("failed to write output")?;
out_buf.clear();
}
} else {
let CommandStdin::Stream(input_stream) = cx.stdin.clone() else {
bail!(
"EXPAND requires stdin when no file path is given \
(use WITH_IO [stdin=...] EXPAND)"
);
};
let mut guard = input_stream
.lock()
.map_err(|_| anyhow!("failed to lock stdin for EXPAND"))?;
let mut buf = [0u8; super::io::CHUNK_SIZE];
loop {
let n = guard.read(&mut buf).context("failed to read from stdin")?;
if n == 0 {
break;
}
expander.process_bytes(&buf[..n], &mut out_buf)?;
w.write_all(&out_buf).context("failed to write output")?;
out_buf.clear();
}
}
expander.flush(&mut out_buf)?;
if !out_buf.is_empty() {
w.write_all(&out_buf).context("failed to write output")?;
out_buf.clear();
}
Ok(())
})?;
Ok(())
}
pub(super) fn assert_eq<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
generation: usize,
hash: &Option<String>,
actual: &super::steps::ResolvedAssertTarget,
expected: Option<&Value>,
) -> Result<()> {
use super::steps::ResolvedAssertTarget;
if let ResolvedAssertTarget::Stdout = actual
&& let CommandStdin::Stream(input_stream) = cx.stdin.clone()
{
let drained = drain_stdin_bounded(input_stream, "ASSERT_EQ")?;
super::io::write_stdout(cx.out.clone(), |w| {
w.write_all(&drained)?;
Ok(())
})?;
let Some(want) = expected.and_then(|v| v.as_str()) else {
bail!(
"ASSERT_EQ stream mismatch\nexpected: {:?}\nactual: {:?}",
expected,
String::from_utf8_lossy(&drained)
);
};
if drained != want.as_bytes() {
bail!(
"ASSERT_EQ stream mismatch\nexpected: {:?}\nactual: {:?}",
want,
String::from_utf8_lossy(&drained)
);
}
return Ok(());
}
if let Some(sha) = hash {
let actual_bytes: Vec<u8> = match actual {
ResolvedAssertTarget::Value(v) => match v.as_str() {
Some(s) => s.as_bytes().to_vec(),
None => {
bail!("ASSERT_EQ --hash needs a string actual, found {:?}", v);
}
},
ResolvedAssertTarget::Pipe(bytes) => bytes.clone(),
ResolvedAssertTarget::Stdout => exact_stdout_bytes(cx, generation)?,
ResolvedAssertTarget::Stderr => {
bail!("ASSERT_EQ over stderr is not supported; use ASSERT_CONTAINS stderr ...");
}
};
let mut hasher = Sha256::new();
hasher.update(&actual_bytes);
let digest = hasher.finalize();
let bytes: &[u8] = digest.as_ref();
let computed: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
if !computed.eq_ignore_ascii_case(sha) {
bail!(
"ASSERT_EQ --hash mismatch: expected {}, computed {}",
sha,
computed
);
}
return Ok(());
}
match actual {
ResolvedAssertTarget::Value(got) => {
let Some(want) = expected else {
bail!("ASSERT_EQ requires an expected value");
};
if got == want {
Ok(())
} else {
bail!(
"ASSERT_EQ mismatch\nexpected: {:?}\nactual: {:?}",
want,
got
);
}
}
ResolvedAssertTarget::Stdout => {
let bytes = exact_stdout_bytes(cx, generation)?;
let Some(want) = expected.and_then(|v| v.as_str()) else {
bail!(
"ASSERT_EQ stream mismatch\nexpected: {:?}\nactual: {:?}",
expected,
String::from_utf8_lossy(&bytes)
);
};
if bytes != want.as_bytes() {
bail!(
"ASSERT_EQ stream mismatch\nexpected: {:?}\nactual: {:?}",
want,
String::from_utf8_lossy(&bytes)
);
}
Ok(())
}
ResolvedAssertTarget::Stderr => {
bail!("ASSERT_EQ over stderr is not supported; use ASSERT_CONTAINS stderr ...");
}
ResolvedAssertTarget::Pipe(bytes) => {
let actual_str = String::from_utf8(bytes.clone())
.with_context(|| "ASSERT_EQ pipe content is not UTF-8".to_string())?;
let Some(want) = expected.and_then(|v| v.as_str()) else {
bail!(
"ASSERT_EQ pipe mismatch\nexpected: {:?}\nactual: {:?}",
expected,
actual_str
);
};
if actual_str != want {
bail!(
"ASSERT_EQ pipe mismatch\nexpected: {:?}\nactual: {:?}",
want,
actual_str
);
}
Ok(())
}
}
}
fn drain_stdin_bounded(input_stream: SharedInput, verb: &str) -> Result<Vec<u8>> {
let mut guard = input_stream
.lock()
.map_err(|_| anyhow!("failed to lock stdin for {verb}"))?;
let mut out = Vec::new();
let mut buf = [0u8; super::io::CHUNK_SIZE];
loop {
let n = guard
.read(&mut buf)
.with_context(|| format!("failed to read from stdin for {verb}"))?;
if n == 0 {
break;
}
if out.len() + n > super::io::EXACT_STDOUT_CAP {
bail!(
"{verb} stdin exceeded the 8 MiB exact buffer; assert via pipe targets or harness expect.stdout"
);
}
out.extend_from_slice(&buf[..n]);
}
Ok(out)
}
fn exact_stdout_bytes<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
generation: usize,
) -> Result<Vec<u8>> {
let captures = cx
.state
.exact_stdout
.lock()
.map_err(|_| anyhow!("exact_stdout poisoned"))?;
match captures.get(&generation) {
Some(entry) if entry.overflowed => bail!(
"ASSERT_EQ stdout overflowed the 8 MiB exact buffer; assert via pipe targets or harness expect.stdout",
),
Some(entry) => Ok(entry.bytes.clone()),
None => bail!("ASSERT_EQ stdout has no exact capture registered"),
}
}
pub(super) fn assert_contains<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
generation: usize,
idx_step: usize,
haystack: &super::steps::ResolvedAssertTarget,
needle: &Arg,
) -> Result<()> {
use super::steps::ResolvedAssertTarget;
let needle_str = super::args::resolve_arg(needle, cx)?;
match haystack {
ResolvedAssertTarget::Value(v) => {
if let Some(hay) = v.as_str() {
if hay.contains(needle_str.as_str()) {
return Ok(());
}
bail!(
"ASSERT_CONTAINS did not contain '{}'; actual: {:?}",
needle_str,
hay
);
}
if let Some(items) = v.as_list() {
if items
.iter()
.any(|e| e.as_str() == Some(needle_str.as_str()))
{
return Ok(());
}
bail!(
"ASSERT_CONTAINS did not contain '{}'; actual: {:?}",
needle_str,
v
);
}
if let Some(map) = v.as_map() {
if map.contains_key(needle_str.as_str()) {
return Ok(());
}
bail!("ASSERT_CONTAINS did not contain '{}'", needle_str);
}
bail!(
"ASSERT_CONTAINS needs a string, list, or map haystack, found {:?}",
v
);
}
ResolvedAssertTarget::Stdout => {
if let CommandStdin::Stream(input_stream) = cx.stdin.clone() {
let mut guard = input_stream
.lock()
.map_err(|_| anyhow!("failed to lock stdin for ASSERT_CONTAINS"))?;
let mut window = super::io::SlidingWindow::new(needle_str.as_bytes().to_vec());
let mut buf = [0u8; super::io::CHUNK_SIZE];
let mut read_any = false;
loop {
let n = guard
.read(&mut buf)
.context("failed to read from stdin for ASSERT_CONTAINS")?;
if n == 0 {
break;
}
read_any = true;
window.push_chunk(&buf[..n]);
super::io::write_stdout(cx.out.clone(), |w| {
w.write_all(&buf[..n])?;
Ok(())
})?;
}
if read_any {
if window.matched {
return Ok(());
}
let emitted = String::from_utf8_lossy(&window.ring_buffer()).into_owned();
bail!(
"ASSERT_CONTAINS did not contain '{}'; emitted:\n{}",
needle_str,
emitted.trim_end()
);
}
}
let windows = cx
.state
.assert_windows
.lock()
.map_err(|_| anyhow!("assert_windows poisoned"))?;
match windows.get(&(generation, idx_step)) {
Some(w) if w.matched => Ok(()),
Some(w) => {
let emitted = String::from_utf8_lossy(&w.ring_buffer()).into_owned();
bail!(
"ASSERT_CONTAINS did not contain '{}'; emitted:\n{}",
needle_str,
emitted.trim_end()
)
}
_ => bail!("ASSERT_CONTAINS did not contain '{}'", needle_str),
}
}
ResolvedAssertTarget::Stderr => {
let windows = cx
.state
.assert_windows_stderr
.lock()
.map_err(|_| anyhow!("assert_windows_stderr poisoned"))?;
match windows.get(&(generation, idx_step)) {
Some(w) if w.matched => Ok(()),
Some(w) => {
let emitted = String::from_utf8_lossy(&w.ring_buffer()).into_owned();
bail!(
"ASSERT_CONTAINS did not contain '{}'; emitted:\n{}",
needle_str,
emitted.trim_end()
)
}
_ => bail!("ASSERT_CONTAINS did not contain '{}'", needle_str),
}
}
ResolvedAssertTarget::Pipe(bytes) => {
let hay = String::from_utf8(bytes.clone())
.with_context(|| "ASSERT_CONTAINS pipe content is not UTF-8".to_string())?;
if hay.contains(needle_str.as_str()) {
Ok(())
} else {
bail!(
"ASSERT_CONTAINS did not contain '{}'; pipe held {:?}",
needle_str,
hay
);
}
}
}
}
pub(crate) fn with_io_block<P: ProcessManager>(
_cx: &mut StepCtx<'_, P>,
_generation: usize,
_idx: usize,
_bindings: &[IoBinding],
) -> Result<()> {
bail!("WITH_IO block should have been expanded during parsing")
}
fn is_single_run(cmd: &StepKind) -> bool {
matches!(cmd, StepKind::Run(_) | StepKind::RunExec { .. })
}
fn async_single_run_body(cmd: &StepKind) -> bool {
match cmd {
StepKind::AsyncBlock { body } | StepKind::AssignAsync { body, .. } => {
matches!(body.as_slice(), [step] if is_single_run(&step.kind))
}
_ => false,
}
}
fn run_terminated(cmd: &StepKind) -> bool {
is_single_run(cmd) || async_single_run_body(cmd)
}
pub(crate) fn with_io<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
generation: usize,
idx: usize,
bindings: &[IoBinding],
cmd: &StepKind,
) -> Result<Flow> {
let (step_stdin, next_expose_stdin, step_stdout, step_stderr, out_pipe, stdin_pipe) =
resolve_io_streams(cx, bindings, cmd)?;
let tty = tty_request(bindings, cmd)?;
super::steps::execute_single_step_with_generation(
cx.state,
cx.process,
cmd,
generation,
idx,
step_stdin,
next_expose_stdin,
step_stdout,
step_stderr,
out_pipe,
stdin_pipe,
tty,
)
}
fn tty_request(bindings: &[IoBinding], cmd: &StepKind) -> Result<Option<TtyRequest>> {
let mut tty = false;
let mut rows = None;
let mut cols = None;
for binding in bindings {
match binding.stream {
IoStream::Tty => tty = true,
IoStream::Rows(value) => rows = Some(value),
IoStream::Cols(value) => cols = Some(value),
IoStream::Stdin | IoStream::Stdout | IoStream::Stderr => {}
}
}
if !tty {
if rows.is_some() || cols.is_some() {
bail!(
"WITH_IO [rows]/[cols] need [tty] on the same step: geometry without a terminal has nothing to size"
);
}
return Ok(None);
}
if bindings
.iter()
.any(|b| matches!(b.stream, IoStream::Stderr))
{
bail!(
"WITH_IO [tty] cannot bind stderr: the pty master carries stdout and stderr interleaved, so the two streams cannot demultiplex"
);
}
match cmd {
StepKind::Run(_) | StepKind::RunExec { .. } => Ok(Some(TtyRequest { rows, cols })),
_ => bail!(
"WITH_IO [tty] only wraps a RUN step: the pty master is one interleaved child stream, so terminal-unaware commands cannot run under it",
),
}
}
#[allow(clippy::type_complexity)]
fn resolve_io_streams<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
bindings: &[IoBinding],
cmd: &StepKind,
) -> Result<(
CommandStdin,
bool,
Option<StreamHandle>,
Option<StreamHandle>,
Option<Arc<PipeInner>>,
Option<Arc<PipeInner>>,
)> {
let mut step_stdin = CommandStdin::Null;
let mut step_stdout = cx.out.clone();
let mut step_stderr = cx.err.clone();
let mut out_pipe = cx.out_pipe.clone();
let mut stdin_pipe = cx.stdin_pipe.clone();
let mut next_expose_stdin = false;
let mut seen_stdin = false;
let mut seen_stdout = false;
let mut seen_stderr = false;
let mut seen_tty = false;
let mut seen_rows = false;
let mut seen_cols = false;
let direct = run_terminated(cmd);
let allow_promote = cx.state.inside_async;
let tty_present = bindings.iter().any(|b| matches!(b.stream, IoStream::Tty));
let direct = direct && !tty_present;
for binding in bindings {
if let Some(target) = &binding.pipe {
let handle = resolve_pipe_handle(cx, target)?;
let promote = allow_promote && !tty_present && cx.state.can_promote_to_os(&handle);
cx.state.io.ensure_handle(&handle, promote)?;
}
match binding.stream {
IoStream::Stdin => {
if seen_stdin {
bail!("WITH_IO declared stdin more than once");
}
seen_stdin = true;
next_expose_stdin = true;
(step_stdin, stdin_pipe) = if let Some(target) = &binding.pipe {
let handle = resolve_pipe_handle(cx, target)?;
let promote =
allow_promote && !tty_present && cx.state.can_promote_to_os(&handle);
let (stdin, backend) = cx.state.io.resolve_stdin(&handle, direct, promote)?;
(stdin, backend)
} else {
(cx.stdin.clone(), None)
};
}
IoStream::Stdout => {
if seen_stdout {
bail!("WITH_IO declared stdout more than once");
}
seen_stdout = true;
(step_stdout, out_pipe) = if let Some(target) = &binding.pipe {
let handle = resolve_pipe_handle(cx, target)?;
let promote =
allow_promote && !tty_present && cx.state.can_promote_to_os(&handle);
let (stdout, backend) = cx.state.io.resolve_stdout(&handle, direct, promote)?;
(Some(stdout), backend)
} else {
(cx.out.clone(), cx.out_pipe.clone())
};
}
IoStream::Stderr => {
if seen_stderr {
bail!("WITH_IO declared stderr more than once");
}
seen_stderr = true;
step_stderr = if let Some(target) = &binding.pipe {
let handle = resolve_pipe_handle(cx, target)?;
let promote =
allow_promote && !tty_present && cx.state.can_promote_to_os(&handle);
Some(cx.state.io.resolve_stderr(&handle, direct, promote)?)
} else {
cx.err.clone()
};
}
IoStream::Tty => {
if seen_tty {
bail!("WITH_IO declared tty more than once");
}
seen_tty = true;
}
IoStream::Rows(_) => {
if seen_rows {
bail!("WITH_IO declared rows more than once");
}
seen_rows = true;
}
IoStream::Cols(_) => {
if seen_cols {
bail!("WITH_IO declared cols more than once");
}
seen_cols = true;
}
}
}
Ok((
step_stdin,
next_expose_stdin,
step_stdout,
step_stderr,
out_pipe,
stdin_pipe,
))
}
fn resolve_pipe_handle<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
target: &PipeTarget,
) -> Result<PipeHandle> {
let PipeTarget::Var(var) = target;
match cx.state.get_var_typed(var) {
Some((kind, value)) if matches!(kind, TypeTag::Pipe) => {
let Some(handle) = value.as_pipe_handle() else {
bail!(
"TypeMismatch: expected PIPE, got {} ({:?})",
kind.name(),
value
);
};
Ok(handle)
}
Some((kind, value)) => {
bail!(
"TypeMismatch: expected PIPE, got {} ({:?})",
kind.name(),
value
);
}
None => {
bail!("undeclared variable ${var}");
}
}
}
fn extract_call(cmd: &StepKind) -> Option<(Vec<IoBinding>, &str, &[Expr])> {
let mut layers: Vec<&Vec<IoBinding>> = Vec::new();
let mut current = cmd;
loop {
match current {
StepKind::Call { name, args } => {
let mut merged: Vec<IoBinding> = Vec::new();
for layer in &layers {
for binding in layer.iter() {
match merged.iter_mut().find(|m| m.stream == binding.stream) {
Some(slot) => *slot = binding.clone(),
None => merged.push(binding.clone()),
}
}
}
return Some((merged, name, args));
}
StepKind::WithIo { bindings, cmd } => {
layers.push(bindings);
current = cmd;
}
_ => return None,
}
}
}
fn extract_import(cmd: &StepKind) -> Option<(Vec<IoBinding>, &str, &str)> {
let mut layers: Vec<&Vec<IoBinding>> = Vec::new();
let mut current = cmd;
loop {
match current {
StepKind::ImportFile { path, alias } => {
let mut merged: Vec<IoBinding> = Vec::new();
for layer in &layers {
for binding in layer.iter() {
match merged.iter_mut().find(|m| m.stream == binding.stream) {
Some(slot) => *slot = binding.clone(),
None => merged.push(binding.clone()),
}
}
}
return Some((merged, path, alias));
}
StepKind::WithIo { bindings, cmd } => {
layers.push(bindings);
current = cmd;
}
_ => return None,
}
}
}
pub(super) fn exit<P: ProcessManager>(cx: &mut StepCtx<'_, P>, code: i64) -> Result<()> {
for child in cx.state.bg_children.iter_mut() {
if let Ok(None) = child.handle.try_wait() {
let _ = child.handle.kill();
let _ = child.handle.try_wait();
}
}
cx.state.bg_children.clear();
Err(anyhow::Error::new(super::exit::ExitRequest(code)))
}
pub(crate) fn for_loop<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
key_var: Option<&str>,
key_type: Option<String>,
val_var: &str,
val_type: String,
in_expr: &Expr,
body: &[Step],
) -> Result<Flow> {
let iterable = super::args::evaluate_expr(in_expr, cx)?;
let clean_val_var = val_var.trim_start_matches('$').to_string();
let val_tag = cx.state.resolve_tag(&val_type)?;
if let Some(items) = iterable.as_list() {
for (i, item) in items.iter().enumerate() {
cx.state.push_scope();
if let Some(idx_name) = key_var {
let clean_idx = idx_name.trim_start_matches('$').to_string();
let kt = match &key_type {
Some(name) => cx.state.resolve_tag(name)?,
None => TypeTag::Int,
};
cx.state.declare_var(
clean_idx,
kt.clone(),
super::args::coerce_value(Value::int(i as i64), &kt)?,
)?;
}
cx.state.declare_var(
clean_val_var.clone(),
val_tag.clone(),
super::args::coerce_value(item.clone(), &val_tag)?,
)?;
let res = super::steps::execute_steps(
cx.state,
cx.process,
body,
cx.stdin.clone(),
false,
cx.out.clone(),
cx.err.clone(),
cx.out_pipe.clone(),
cx.stdin_pipe.clone(),
false,
);
let pop_res = cx.state.pop_scope();
let flow = match (res, pop_res) {
(Ok(flow), Ok(())) => flow,
(Err(e), _) => return Err(e),
(Ok(_), Err(e)) => return Err(e),
};
match flow {
Flow::Done | Flow::Continue { .. } => {}
Flow::Break { .. } => return Ok(Flow::Done),
Flow::Return { .. } => return Ok(flow),
}
}
return Ok(Flow::Done);
}
if let Some(map) = iterable.as_map() {
let key_name = key_var.ok_or_else(|| {
anyhow!("FOR loop over Map requires key and value bindings: FOR $k: STRING, $v: TYPE IN $map")
})?;
let clean_key_var = key_name.trim_start_matches('$').to_string();
let mut keys: Vec<_> = map.keys().cloned().collect();
keys.sort();
let kt = match &key_type {
Some(name) => cx.state.resolve_tag(name)?,
None => TypeTag::String,
};
if !matches!(kt, TypeTag::String) {
anyhow::bail!(
"FOR loop over MAP requires a STRING key variable, got {}",
kt.name(),
);
}
for k in keys {
let v = map[&k].clone();
cx.state.push_scope();
cx.state.declare_var(
clean_key_var.clone(),
TypeTag::String,
Value::string(k.clone()),
)?;
cx.state.declare_var(
clean_val_var.clone(),
val_tag.clone(),
super::args::coerce_value(v, &val_tag)?,
)?;
let res = super::steps::execute_steps(
cx.state,
cx.process,
body,
cx.stdin.clone(),
false,
cx.out.clone(),
cx.err.clone(),
cx.out_pipe.clone(),
cx.stdin_pipe.clone(),
false,
);
let pop_res = cx.state.pop_scope();
let flow = match (res, pop_res) {
(Ok(flow), Ok(())) => flow,
(Err(e), _) => return Err(e),
(Ok(_), Err(e)) => return Err(e),
};
match flow {
Flow::Done | Flow::Continue { .. } => {}
Flow::Break { .. } => return Ok(Flow::Done),
Flow::Return { .. } => return Ok(flow),
}
}
return Ok(Flow::Done);
}
bail!(
"FOR loop requires a List or Map iterable, found {:?}",
iterable
)
}
pub(crate) fn define_func<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
name: &str,
params: &[(String, String)],
body: &[Step],
) -> Result<()> {
let mut resolved = Vec::with_capacity(params.len());
for (pname, ptype) in params {
resolved.push((pname.clone(), cx.state.resolve_tag(ptype)?));
}
let owner = cx.state.current_module();
cx.state
.functions
.define_script(name, &resolved, body, owner.as_deref())
}
pub(crate) fn call_func_value<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
name: &str,
args: &[Expr],
) -> Result<Value> {
let Some(entry) = cx.state.functions.get(name) else {
bail!("unknown function `{name}`");
};
if cx.state.call_depth >= MAX_CALL_DEPTH {
bail!(
"recursion depth limit exceeded in FUNC {}",
super::base_name(name)
);
}
if let Some(params) = entry.meta.params.as_deref() {
let required = super::required_arity(params);
if args.len() < required || args.len() > params.len() {
if required == params.len() {
bail!(
"{}() expects {} argument(s), got {}",
super::base_name(name),
params.len(),
args.len()
);
}
bail!(
"{}() expects {} to {} argument(s), got {}",
super::base_name(name),
required,
params.len(),
args.len()
);
}
}
let mut arg_vals = Vec::with_capacity(args.len());
for arg in args {
arg_vals.push(super::args::evaluate_expr(arg, cx)?);
}
match entry.body {
FuncBody::Script(def) => {
let module_key = def.module.clone();
let module_ctx = module_key.as_deref().and_then(|key| {
cx.state.modules.get(key).map(|record| {
(
record.dir.clone(),
record
.init
.as_ref()
.map(|init| (init.envs.clone(), init.inherit_names.clone())),
)
})
});
cx.state.call_depth += 1;
cx.state.push_scope();
cx.state.module_stack.push(module_key);
if let Some((dir, Some((envs, inherit_names)))) = module_ctx {
cx.state.reset_module_context(dir, envs);
if !inherit_names.is_empty() {
inherit_env(cx, &inherit_names)?;
}
}
let outcome: Result<Value> = (|| {
for ((pname, ptype), pval) in def.params.iter().zip(arg_vals) {
cx.state.declare_var(pname.clone(), ptype.clone(), pval)?;
}
let flow = super::steps::execute_steps(
cx.state,
cx.process,
&def.body,
cx.stdin.clone(),
false,
cx.out.clone(),
cx.err.clone(),
cx.out_pipe.clone(),
cx.stdin_pipe.clone(),
false,
)?;
match flow {
Flow::Done => Ok(Value::string(String::new())),
Flow::Return { value, .. } => Ok(value),
Flow::Break { idx } => {
bail!(
"step {}: BREAK cannot cross function boundary (in {name}())",
idx + 1
);
}
Flow::Continue { idx } => {
bail!(
"step {}: CONTINUE cannot cross function boundary (in {name}())",
idx + 1
);
}
}
})();
let pop_res = cx.state.pop_scope();
cx.state.call_depth -= 1;
let _ = cx.state.module_stack.pop();
match (outcome, pop_res) {
(Ok(value), Ok(())) => Ok(value),
(Err(e), _) => Err(e),
(Ok(_), Err(e)) => Err(e),
}
}
FuncBody::Pure(func) => {
let value = func(arg_vals).with_context(|| format!("function `{name}` failed"))?;
super::args::check_host_return_value(
&format!("function `{}` returned", super::base_name(name)),
&entry.meta.returns,
&value,
)?;
Ok(value)
}
FuncBody::Ctx(func) | FuncBody::Both { ctx: func, .. } => {
let value = func(cx, arg_vals).with_context(|| format!("function `{name}` failed"))?;
super::args::check_host_return_value(
&format!("function `{}` returned", super::base_name(name)),
&entry.meta.returns,
&value,
)?;
Ok(value)
}
}
}
pub(crate) fn block_value<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
body: &[Step],
) -> Result<Value> {
cx.state.push_scope();
let outcome: Result<Value> = (|| {
let flow = super::steps::execute_steps(
cx.state,
cx.process,
body,
cx.stdin.clone(),
false,
cx.out.clone(),
cx.err.clone(),
cx.out_pipe.clone(),
cx.stdin_pipe.clone(),
false,
)?;
match flow {
Flow::Done => Ok(Value::string(String::new())),
Flow::Return { value, .. } => Ok(value),
Flow::Break { idx } => {
bail!("step {}: BREAK cannot cross block boundary", idx + 1)
}
Flow::Continue { idx } => {
bail!("step {}: CONTINUE cannot cross block boundary", idx + 1)
}
}
})();
let pop_res = cx.state.pop_scope();
match (outcome, pop_res) {
(Ok(value), Ok(())) => Ok(value),
(Err(e), _) => Err(e),
(Ok(_), Err(e)) => Err(e),
}
}
pub(crate) fn handle_return<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
idx: usize,
expr: &Expr,
) -> Result<Flow> {
let value = super::args::evaluate_expr(expr, cx)?;
Ok(Flow::Return { idx, value })
}
pub(crate) fn while_loop<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
cond: &Expr,
body: &[Step],
) -> Result<Flow> {
use std::sync::atomic::Ordering;
loop {
if cx.state.cancel_token.load(Ordering::SeqCst) {
bail!("ASYNC task cancelled");
}
let val = super::args::evaluate_expr(cond, cx)?;
if !super::args::is_truthy(&val)? {
return Ok(Flow::Done);
}
cx.state.push_scope();
let res = super::steps::execute_steps(
cx.state,
cx.process,
body,
cx.stdin.clone(),
false,
cx.out.clone(),
cx.err.clone(),
cx.out_pipe.clone(),
cx.stdin_pipe.clone(),
false,
);
let pop_res = cx.state.pop_scope();
let flow = match (res, pop_res) {
(Ok(flow), Ok(())) => flow,
(Err(e), _) => return Err(e),
(Ok(_), Err(e)) => return Err(e),
};
match flow {
Flow::Done | Flow::Continue { .. } => {}
Flow::Break { .. } => return Ok(Flow::Done),
Flow::Return { .. } => return Ok(flow),
}
}
}
pub(crate) fn assign<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
var: &str,
decl_type: String,
expr: &Expr,
) -> Result<()> {
let value = super::args::evaluate_expr(expr, cx)?;
let clean_var = var.trim_start_matches('$').to_string();
let tag = cx.state.resolve_tag(&decl_type)?;
cx.state.declare_var(clean_var, tag, value)?;
Ok(())
}
pub(crate) fn set_var_value<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
var: &str,
expr: &Expr,
) -> Result<()> {
let value = super::args::evaluate_expr(expr, cx)?;
let clean_var = var.trim_start_matches('$').to_string();
cx.state.mutate_var(&clean_var, value)?;
Ok(())
}
pub(crate) fn assign_capture<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
generation: usize,
idx: usize,
var: &str,
decl_type: String,
cmd: &StepKind,
) -> Result<Flow> {
use std::sync::Arc;
if let Some((bindings, path, alias)) = extract_import(cmd) {
if bindings
.iter()
.any(|b| b.stream == IoStream::Stdout && b.pipe.is_some())
{
bail!(
"LET capture cannot use WITH_IO [stdout=$var]; the capture binds the RETURN value"
);
}
let value = if bindings.is_empty() {
super::import::import_file(cx, path, alias)?
} else {
let (step_stdin, expose_stdin, step_stdout, step_stderr, out_pipe, stdin_pipe) =
resolve_io_streams(cx, &bindings, cmd)?;
let state = &mut *cx.state;
let process = &mut *cx.process;
let mut sub_cx = super::steps::StepCtx {
state,
process,
stdin: step_stdin,
expose_stdin,
out: step_stdout,
err: step_stderr,
out_pipe,
stdin_pipe,
tty: None,
};
super::import::import_file(&mut sub_cx, path, alias)?
};
let clean_var = var.trim_start_matches('$').to_string();
let tag = cx.state.resolve_tag(&decl_type)?;
cx.state.declare_var(clean_var, tag, value)?;
return Ok(Flow::Done);
}
if let Some((bindings, name, args)) = extract_call(cmd) {
if bindings
.iter()
.any(|b| b.stream == IoStream::Stdout && b.pipe.is_some())
{
bail!(
"LET capture cannot use WITH_IO [stdout=$var]; the capture binds the RETURN value"
);
}
if bindings.is_empty() {
let value = call_func_value(cx, name, args)?;
let clean_var = var.trim_start_matches('$').to_string();
let tag = cx.state.resolve_tag(&decl_type)?;
cx.state.declare_var(clean_var, tag, value)?;
return Ok(Flow::Done);
}
let (step_stdin, expose_stdin, step_stdout, step_stderr, out_pipe, stdin_pipe) =
resolve_io_streams(cx, &bindings, cmd)?;
let state = &mut *cx.state;
let process = &mut *cx.process;
let mut sub_cx = super::steps::StepCtx {
state,
process,
stdin: step_stdin,
expose_stdin,
out: step_stdout,
err: step_stderr,
out_pipe,
stdin_pipe,
tty: None,
};
let value = call_func_value(&mut sub_cx, name, args)?;
let tag = sub_cx.state.resolve_tag(&decl_type)?;
sub_cx
.state
.declare_var(var.trim_start_matches('$').to_string(), tag, value)?;
return Ok(Flow::Done);
}
let sink = Arc::new(super::capture::new_spill_buffer());
let capture_out = Some(StreamHandle::Stream(sink.writer()));
let flow = super::steps::execute_single_step_with_generation(
cx.state,
cx.process,
cmd,
generation,
idx,
cx.stdin.clone(),
cx.expose_stdin,
capture_out,
cx.err.clone(),
None,
None,
cx.tty,
)?;
match flow {
Flow::Done => {}
Flow::Break { idx } => {
bail!("step {}: BREAK outside loop (cannot be captured)", idx + 1);
}
Flow::Continue { idx } => {
bail!(
"step {}: CONTINUE outside loop (cannot be captured)",
idx + 1
);
}
Flow::Return { idx, .. } => {
bail!(
"step {}: RETURN outside function (cannot be captured)",
idx + 1
);
}
}
let text = sink
.drain_string_strict()
.map_err(|e| anyhow!("LET ${var} capture is not valid UTF-8: {e}"))?;
let clean_var = var.trim_start_matches('$').to_string();
let tag = cx.state.resolve_tag(&decl_type)?;
cx.state.declare_var(clean_var, tag, Value::string(text))?;
Ok(Flow::Done)
}
pub(crate) fn if_then<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
cond: &Expr,
then_body: &[Step],
else_ifs: &[(Box<Expr>, Vec<Step>)],
else_body: &Option<Vec<Step>>,
) -> Result<Flow> {
let val = super::args::evaluate_expr(cond, cx)?;
if super::args::is_truthy(&val)? {
return super::steps::execute_scoped_steps(
cx.state,
cx.process,
then_body,
cx.stdin.clone(),
false,
cx.out.clone(),
cx.err.clone(),
cx.out_pipe.clone(),
cx.stdin_pipe.clone(),
false,
);
}
for (else_cond, else_block) in else_ifs {
let val = super::args::evaluate_expr(else_cond.as_ref(), cx)?;
if super::args::is_truthy(&val)? {
return super::steps::execute_scoped_steps(
cx.state,
cx.process,
else_block,
cx.stdin.clone(),
false,
cx.out.clone(),
cx.err.clone(),
cx.out_pipe.clone(),
cx.stdin_pipe.clone(),
false,
);
}
}
if let Some(body) = else_body {
return super::steps::execute_scoped_steps(
cx.state,
cx.process,
body,
cx.stdin.clone(),
false,
cx.out.clone(),
cx.err.clone(),
cx.out_pipe.clone(),
cx.stdin_pipe.clone(),
false,
);
}
Ok(Flow::Done)
}
struct BodyBinding {
handle: PipeHandle,
produces: bool,
}
fn binding_handle<P: ProcessManager>(
state: &ExecState<P>,
target: &PipeTarget,
) -> Option<PipeHandle> {
let PipeTarget::Var(var) = target;
match state.get_var_typed(var) {
Some((TypeTag::Pipe, value)) => value.as_pipe_handle(),
_ => None,
}
}
fn collect_body_bindings<P: ProcessManager>(
kind: &StepKind,
state: &ExecState<P>,
out: &mut Vec<BodyBinding>,
) {
match kind {
StepKind::WithIo { bindings, cmd } => {
let tty = bindings.iter().any(|b| matches!(b.stream, IoStream::Tty));
for binding in bindings {
if tty
&& matches!(
binding.stream,
IoStream::Stdin | IoStream::Stdout | IoStream::Stderr
)
{
continue;
}
let Some(target) = &binding.pipe else {
continue;
};
let Some(handle) = binding_handle(state, target) else {
continue;
};
out.push(BodyBinding {
handle,
produces: !matches!(binding.stream, IoStream::Stdin),
});
}
collect_body_bindings(cmd, state, out);
}
StepKind::Timeout { body, .. }
| StepKind::Isolated { body }
| StepKind::For { body, .. }
| StepKind::While { body, .. } => {
for step in body {
collect_body_bindings(&step.kind, state, out);
}
}
StepKind::If {
then_body,
else_ifs,
else_body,
..
} => {
for step in then_body {
collect_body_bindings(&step.kind, state, out);
}
for (_, branch) in else_ifs {
for step in branch {
collect_body_bindings(&step.kind, state, out);
}
}
if let Some(body) = else_body {
for step in body {
collect_body_bindings(&step.kind, state, out);
}
}
}
StepKind::FuncDef { .. }
| StepKind::Call { .. }
| StepKind::AsyncBlock { .. }
| StepKind::AssignAsync { .. } => {}
_ => {}
}
}
fn pin_async_keepers<P: ProcessManager>(
cx: &StepCtx<'_, P>,
body: &[Step],
worker_task_id: u64,
) -> Result<Option<super::state::KeeperExpiry>> {
struct Acc {
handle: PipeHandle,
last_producer: Option<usize>,
}
let mut accs: Vec<Acc> = Vec::new();
for (idx, step) in body.iter().enumerate() {
let mut found = Vec::new();
collect_body_bindings(&step.kind, cx.state, &mut found);
for b in found {
match accs.iter_mut().find(|a| a.handle.ptr_eq(&b.handle)) {
Some(a) => {
if b.produces {
a.last_producer = Some(idx);
}
}
None => accs.push(Acc {
handle: b.handle,
last_producer: b.produces.then_some(idx),
}),
}
}
}
for a in &accs {
let promote = ExecState::<P>::can_promote_in_task(&a.handle, worker_task_id);
cx.state.io.ensure_handle(&a.handle, promote)?;
}
let mut map: HashMap<usize, Vec<KeeperGuard>> = HashMap::new();
for a in &accs {
if let Some(idx) = a.last_producer
&& let Some(guard) = cx.state.io.pin_keeper(&a.handle)?
{
map.entry(idx).or_default().push(guard);
}
}
if map.is_empty() {
Ok(None)
} else {
Ok(Some(super::state::KeeperExpiry::new(body, map)))
}
}
pub(crate) fn dispatch_run<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Run(arg) = step else {
unreachable!()
};
let cmd = super::args::resolve_arg(arg, cx)?;
let cmd = super::args::expand_dsl_vars(&cmd, cx.state)?;
run(cx, &cmd)
}
pub(crate) fn dispatch_run_exec<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::RunExec { argv } = step else {
unreachable!()
};
let resolved = resolve_run_exec_argv(argv, cx)?;
run_argv(cx, &resolved)
}
pub(crate) fn dispatch_async_block<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::AsyncBlock { body } = step else {
unreachable!()
};
let body = body.clone();
let worker_task_id = cx.state.alloc_task_id()?;
let expiry = pin_async_keepers(cx, &body, worker_task_id)?;
let mut forked_state = cx.state.fork();
forked_state.keeper_expiry = expiry;
forked_state.task_id = worker_task_id;
cx.state.mark_captured_pipes_escaped();
let forked_process = cx.process.clone();
let stdin = cx.stdin.clone();
let expose_stdin = cx.expose_stdin;
let out = cx.out.clone();
let err = cx.err.clone();
let out_pipe = cx.out_pipe.clone();
let stdin_pipe = cx.stdin_pipe.clone();
let out_keepalive = out_pipe
.as_ref()
.map(|backend| KeeperGuard::new(std::sync::Arc::clone(backend)));
let cancel_token = std::sync::Arc::clone(&forked_state.cancel_token);
let cancel_hub = std::sync::Arc::clone(&forked_state.cancel_hub);
let active_process = std::sync::Arc::clone(&forked_state.active_process);
let worker: std::sync::Arc<std::sync::Mutex<Option<std::thread::ThreadId>>> =
std::sync::Arc::new(std::sync::Mutex::new(None));
let worker_child = std::sync::Arc::clone(&worker);
let join = std::thread::spawn(move || {
let _slot =
super::state::TaskSlotGuard::new(std::sync::Arc::clone(&forked_state.live_tasks));
*worker_child.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::thread::current().id());
let _out_keepalive = out_keepalive;
let mut child_state = forked_state;
let mut child_process = forked_process;
let flow = super::steps::execute_steps(
&mut child_state,
&mut child_process,
&body,
stdin,
expose_stdin,
out,
err,
out_pipe,
stdin_pipe,
true, )?;
match flow {
Flow::Done => Ok(()),
Flow::Break { idx } => {
anyhow::bail!("step {}: BREAK cannot cross ASYNC boundary", idx + 1);
}
Flow::Continue { idx } => {
anyhow::bail!("step {}: CONTINUE cannot cross ASYNC boundary", idx + 1);
}
Flow::Return { idx, .. } => {
anyhow::bail!("step {}: RETURN cannot cross ASYNC boundary", idx + 1);
}
}
});
cx.state.bg_children.push(super::state::BgChild {
handle: Box::new(super::steps::ThreadJoinHandle::new(
join,
cancel_token,
cancel_hub,
active_process,
worker,
)),
task_id: worker_task_id,
});
Ok(())
}
pub(crate) fn dispatch_echo<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Echo(arg) = step else {
unreachable!()
};
let msg = super::args::resolve_arg(arg, cx)?;
echo(cx, &msg)
}
pub(crate) fn dispatch_workdir<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Workdir(arg) = step else {
unreachable!()
};
let path = super::args::resolve_arg(arg, cx)?;
workdir(cx, &path)
}
pub(crate) fn dispatch_workspace<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Workspace(target) = step else {
unreachable!()
};
workspace(cx, target)
}
pub(crate) fn dispatch_remote<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::RemoteBlock {
target,
vars,
env,
body,
} = step
else {
unreachable!()
};
super::remote::run_remote_block(cx, target, vars, env, body)
}
pub(crate) fn dispatch_env<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Env { key, value } = step else {
unreachable!()
};
let resolved = super::args::resolve_arg(value, cx)?;
env(cx, key, &resolved)
}
pub(crate) fn dispatch_copy<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Copy {
from_workspace,
from_host,
to_host,
from,
to,
} = step
else {
unreachable!()
};
if *from_host || *to_host {
return super::remote::copy_transfer(cx, *from_host, *to_host, from, to);
}
let from_resolved = super::args::resolve_arg(from, cx)?;
let to_resolved = super::args::resolve_arg(to, cx)?;
copy(cx, from_workspace.clone(), &from_resolved, &to_resolved)
}
pub(crate) fn dispatch_archive<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Archive { src, dst, raw } = step else {
unreachable!()
};
let src_resolved = super::args::resolve_arg(src, cx)?;
let dst_resolved = super::args::resolve_arg(dst, cx)?;
archive(cx, &src_resolved, &dst_resolved, *raw)
}
pub(crate) fn dispatch_unarchive<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Unarchive {
src,
dst,
max_bytes,
} = step
else {
unreachable!()
};
let src_resolved = super::args::resolve_arg(src, cx)?;
let dst_resolved = super::args::resolve_arg(dst, cx)?;
let cap_resolved = super::args::resolve_arg_opt(max_bytes, cx)?;
unarchive(cx, &src_resolved, &dst_resolved, cap_resolved.as_deref())
}
pub(crate) fn dispatch_copy_git<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::CopyGit {
rev,
from,
to,
include_dirty,
} = step
else {
unreachable!()
};
let rev_resolved = super::args::resolve_arg(rev, cx)?;
let from_resolved = super::args::resolve_arg(from, cx)?;
let to_resolved = super::args::resolve_arg(to, cx)?;
copy_git(
cx,
&rev_resolved,
&from_resolved,
&to_resolved,
*include_dirty,
)
}
pub(crate) fn dispatch_symlink<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Symlink {
from_workspace,
from,
to,
} = step
else {
unreachable!()
};
let from_resolved = super::args::resolve_arg(from, cx)?;
let to_resolved = super::args::resolve_arg(to, cx)?;
symlink(cx, from_workspace.clone(), &from_resolved, &to_resolved)
}
pub(crate) fn dispatch_mkdir<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Mkdir(arg) = step else {
unreachable!()
};
let path = super::args::resolve_arg(arg, cx)?;
mkdir(cx, &path)
}
pub(super) fn install<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
from: &str,
to: &str,
) -> Result<()> {
let from_abs = cx
.state
.fs
.resolve_read(&cx.state.effective_cwd(), from)
.with_context(|| format!("INSTALL {from} {to}"))?;
let to_abs = cx
.state
.fs
.resolve_write(&cx.state.effective_cwd(), to)
.with_context(|| format!("INSTALL {from} {to}"))?;
cx.state
.fs
.install_file_atomic(&from_abs, &to_abs, 0o755)
.with_context(|| format!("INSTALL {from} {to}"))?;
Ok(())
}
pub(crate) fn dispatch_install<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Install { from, to } = step else {
unreachable!()
};
let from_resolved = super::args::resolve_arg(from, cx)?;
let to_resolved = super::args::resolve_arg(to, cx)?;
install(cx, &from_resolved, &to_resolved)
}
pub(crate) fn dispatch_ls<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Ls(arg) = step else {
unreachable!()
};
let resolved = super::args::resolve_arg_opt(arg, cx)?;
ls(cx, &resolved)
}
pub(crate) fn dispatch_read<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Read(arg) = step else {
unreachable!()
};
let resolved = super::args::resolve_arg_opt(arg, cx)?;
read(cx, &resolved)
}
pub(crate) fn dispatch_read_line<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::ReadLine { var } = step else {
unreachable!()
};
read_line(cx, var)
}
#[cfg_attr(miri, allow(dead_code))]
pub(super) fn format_prompt(message: &str, default: Option<&str>) -> String {
match default {
Some(d) => format!("{message} [{d}]: "),
None => format!("{message}: "),
}
}
#[cfg_attr(miri, allow(dead_code))]
pub(super) fn apply_prompt_answer(line: &str, default: Option<&str>) -> String {
if line.is_empty() {
default.unwrap_or("").to_string()
} else {
line.to_string()
}
}
pub(super) fn prompt<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
var: &str,
message: &str,
default: Option<&str>,
) -> Result<()> {
#[cfg(miri)]
{
let _ = (cx, var, message, default);
bail!("PROMPT unavailable under Miri (no terminal)");
}
#[cfg(not(miri))]
{
let clean_var = var.trim_start_matches('$').to_string();
if !cx.process.stdin_is_terminal() || cx.stdin.is_redirected() {
match default {
Some(d) => {
eprintln!("non-interactive: using default for {message}");
let text = Value::string(d.to_string());
bind_prompt_var(cx, &clean_var, text)?;
return Ok(());
}
None => {
bail!("PROMPT {message}: non-TTY stdin has no answer and no default",);
}
}
}
let rendered = format_prompt(message, default);
{
use std::io::Write;
let mut err = std::io::stderr().lock();
err.write_all(rendered.as_bytes())
.with_context(|| format!("PROMPT {message}: failed to write prompt"))?;
err.flush()
.with_context(|| format!("PROMPT {message}: failed to flush prompt"))?;
}
let mut line = String::new();
let n = std::io::stdin()
.read_line(&mut line)
.with_context(|| format!("PROMPT {message}: failed reading stdin"))?;
if n == 0 && line.is_empty() {
bail!("PROMPT {message}: EOF on stdin before any input",);
}
let trimmed = line
.strip_suffix("\r\n")
.or_else(|| line.strip_suffix('\n'))
.unwrap_or(&line);
let text = Value::string(apply_prompt_answer(trimmed, default));
bind_prompt_var(cx, &clean_var, text)?;
Ok(())
}
}
#[cfg_attr(miri, allow(dead_code))]
fn bind_prompt_var<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
clean_var: &str,
text: Value,
) -> Result<()> {
if cx.state.get_var_typed(clean_var).is_some() {
cx.state
.mutate_var(clean_var, text)
.with_context(|| format!("PROMPT ${clean_var}"))?;
} else {
cx.state
.declare_var(clean_var.to_string(), TypeTag::String, text)
.with_context(|| format!("PROMPT ${clean_var}"))?;
}
Ok(())
}
pub(crate) fn dispatch_prompt<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Prompt {
var,
message,
default,
} = step
else {
unreachable!()
};
let message_resolved = super::args::resolve_arg(message, cx)?;
let default_resolved = match default {
Some(d) => Some(super::args::resolve_arg(d, cx)?),
None => None,
};
prompt(cx, var, &message_resolved, default_resolved.as_deref())
}
pub(super) fn push_into<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
var: &str,
item: Value,
) -> Result<()> {
cx.state
.push_into_list(var, item)
.with_context(|| format!("LIST_APPEND ${var}"))
}
pub(crate) fn dispatch_push_into_step<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::ListAppend { list, item } = step else {
unreachable!()
};
let value = super::args::evaluate_assert_operand(item, cx)?;
push_into(cx, list, value)
}
pub(crate) fn dispatch_write<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Write { path, contents } = step else {
unreachable!()
};
let path_resolved = super::args::resolve_arg(path, cx)?;
let contents_resolved = super::args::resolve_arg_opt(contents, cx)?;
write(cx, &path_resolved, contents_resolved.as_deref())
}
pub(crate) fn dispatch_append<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Append { path, contents } = step else {
unreachable!()
};
let path_resolved = super::args::resolve_arg(path, cx)?;
let contents_resolved = super::args::resolve_arg_opt(contents, cx)?;
append(cx, &path_resolved, contents_resolved.as_deref())
}
pub(super) fn remove<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
path: &str,
recursive: bool,
) -> Result<()> {
let cwd = cx.state.effective_cwd();
let target = cx
.state
.fs
.resolve_write(&cwd, path)
.with_context(|| format!("REMOVE {path}"))?;
let guard_cwd = cx.state.cwd.clone();
let cwd_canon = cx
.state
.fs
.canonicalize(&guard_cwd)
.unwrap_or_else(|_| guard_cwd.clone());
if target == cwd_canon
|| cwd_canon.as_path().starts_with(target.as_path())
|| Some(&target) == cx.state.fs.workspace_root()
|| target == *cx.state.fs.root()
{
bail!("REMOVE {path}: cannot remove working directory or workspace root",);
}
if cx
.state
.fs
.remove_link_if_symlink(&cwd, path)
.with_context(|| format!("REMOVE {path}"))?
{
return Ok(());
}
match cx.state.fs.entry_kind_no_follow(&target) {
Err(_) => bail!("REMOVE {path}: no such file or directory"),
Ok(EntryKind::File) => {
cx.state
.fs
.remove_file(&target)
.with_context(|| format!("REMOVE {path}"))?;
Ok(())
}
Ok(EntryKind::Symlink) => bail!("REMOVE {path}: link changed during removal",),
Ok(EntryKind::Dir) => {
if recursive {
cx.state
.fs
.remove_dir_all(&target)
.with_context(|| format!("REMOVE {path}"))?;
Ok(())
} else {
cx.state.fs.remove_empty_dir(&target).with_context(|| {
format!("REMOVE {path}: directory not empty (use --recursive)",)
})?;
Ok(())
}
}
}
}
pub(crate) fn dispatch_remove<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Remove { path, recursive } = step else {
unreachable!()
};
let path_resolved = super::args::resolve_arg(path, cx)?;
remove(cx, &path_resolved, *recursive)
}
pub(crate) fn dispatch_expand<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Expand { path, overrides } = step else {
unreachable!()
};
let path_resolved = super::args::resolve_arg_opt(path, cx)?;
let overrides_resolved = super::args::resolve_overrides(overrides, cx)?;
replace(cx, &path_resolved, &overrides_resolved)
}
pub(crate) fn dispatch_assert_eq<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::AssertEq {
hash,
actual,
expected,
} = step
else {
unreachable!()
};
let target = super::steps::resolve_assert_target(actual, cx)?;
let expected_val = match expected {
Some(e) => Some(super::args::evaluate_assert_operand(e, cx)?),
None => None,
};
assert_eq(cx, 0, hash, &target, expected_val.as_ref())
}
pub(crate) fn dispatch_assert_contains<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::AssertContains { haystack, needle } = step else {
unreachable!()
};
let target = super::steps::resolve_assert_target(haystack, cx)?;
assert_contains(cx, 0, 0, &target, needle)
}
pub(crate) fn dispatch_exit<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Exit(code) = step else {
unreachable!()
};
let code = super::args::resolve_arg_as_int(code, cx)?;
exit(cx, code)
}
pub(crate) fn dispatch_inherit_env<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::InheritEnv { keys } = step else {
unreachable!()
};
inherit_env(cx, keys)
}
pub(crate) fn dispatch_isolated_inherit_env<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::IsolatedInheritEnv { keys } = step else {
unreachable!()
};
isolated_inherit_env(cx, keys)
}
pub(crate) fn dispatch_for_loop<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::For {
key_var,
key_type,
var,
var_type,
in_expr,
body,
} = step
else {
unreachable!()
};
top_level_flow(for_loop(
cx,
key_var.as_deref(),
key_type.clone(),
var,
var_type.clone(),
in_expr,
body,
)?)
}
pub(crate) fn dispatch_if_then<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::If {
cond,
then_body,
else_ifs,
else_body,
} = step
else {
unreachable!()
};
top_level_flow(if_then(cx, cond, then_body, else_ifs, else_body)?)
}
pub(crate) fn dispatch_assign<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Assign {
var,
decl_type,
expr,
} = step
else {
unreachable!()
};
assign(cx, var, decl_type.clone(), expr)
}
pub(crate) fn dispatch_set<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Set { var, expr } = step else {
unreachable!()
};
set_var_value(cx, var, expr)
}
pub(crate) fn dispatch_with_io<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::WithIo { bindings, cmd } = step else {
unreachable!()
};
top_level_flow(with_io(cx, 0, 0, bindings, cmd)?)
}
pub(crate) fn dispatch_with_io_block<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::WithIoBlock { bindings } = step else {
unreachable!()
};
with_io_block(cx, 0, 0, bindings)
}
pub(crate) fn dispatch_func_def<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::FuncDef {
name, params, body, ..
} = step
else {
unreachable!()
};
define_func(cx, name, params, body)
}
pub(crate) fn dispatch_import_file<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::ImportFile { path, alias } = step else {
unreachable!()
};
super::import::import_file(cx, path, alias).map(|_| ())
}
pub(crate) fn dispatch_import_funcs<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::ImportFuncs {
path,
alias,
func_names,
type_names,
} = step
else {
unreachable!()
};
super::import::import_funcs(cx, path, alias.as_deref(), func_names, type_names)
}
pub(crate) fn dispatch_call<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Call { name, args } = step else {
unreachable!()
};
call_func_value(cx, name, args).map(|_| ())
}
pub(crate) fn dispatch_return<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Return { expr } = step else {
unreachable!()
};
top_level_flow(handle_return(cx, 0, expr)?)
}
pub(crate) fn dispatch_while_loop<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::While { cond, body } = step else {
unreachable!()
};
top_level_flow(while_loop(cx, cond, body)?)
}
pub(crate) fn dispatch_break<P: ProcessManager>(
step: &StepKind,
_cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Break = step else {
unreachable!()
};
bail!("BREAK outside loop");
}
pub(crate) fn dispatch_continue<P: ProcessManager>(
step: &StepKind,
_cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Continue = step else {
unreachable!()
};
bail!("CONTINUE outside loop");
}
fn body_returns_value(body: &[Step]) -> bool {
body.iter().any(|step| step_returns_value(&step.kind))
}
fn step_returns_value(kind: &StepKind) -> bool {
match kind {
StepKind::Return { .. } => true,
StepKind::ImportFile { .. } => true,
StepKind::WithIo { cmd, .. } => step_returns_value(cmd),
StepKind::For { body, .. }
| StepKind::While { body, .. }
| StepKind::Timeout { body, .. }
| StepKind::Isolated { body } => body_returns_value(body),
StepKind::If {
then_body,
else_ifs,
else_body,
..
} => {
body_returns_value(then_body)
|| else_ifs
.iter()
.any(|(_, branch)| body_returns_value(branch))
|| else_body
.as_ref()
.is_some_and(|body| body_returns_value(body))
}
StepKind::FuncDef { .. } | StepKind::AsyncBlock { .. } | StepKind::AssignAsync { .. } => {
false
}
_ => false,
}
}
pub(crate) fn dispatch_assign_async<P: ProcessManager>(
var: &str,
decl_type: String,
body: &[Step],
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let task_id = cx.state.alloc_task_id()?;
let body = body.to_vec();
let expiry = pin_async_keepers(cx, &body, task_id)?;
let mut forked_state = cx.state.fork();
forked_state.keeper_expiry = expiry;
forked_state.task_id = task_id;
cx.state.mark_captured_pipes_escaped();
let forked_process = cx.process.clone();
let stdin = cx.stdin.clone();
let expose_stdin = cx.expose_stdin;
let tails = std::sync::Arc::new(std::sync::Mutex::new(super::state::TaskTails::new()));
let out = TaskTee::wrap(cx.out.clone(), &tails, TeeStream::Stdout);
let err = TaskTee::wrap(cx.err.clone(), &tails, TeeStream::Stderr);
let out_pipe = cx.out_pipe.clone();
let stdin_pipe = cx.stdin_pipe.clone();
let out_keepalive = out_pipe
.as_ref()
.map(|backend| KeeperGuard::new(std::sync::Arc::clone(backend)));
let cancel_token = std::sync::Arc::clone(&forked_state.cancel_token);
let cancel_hub = std::sync::Arc::clone(&forked_state.cancel_hub);
let active_process = std::sync::Arc::clone(&forked_state.active_process);
let worker: std::sync::Arc<std::sync::Mutex<Option<std::thread::ThreadId>>> =
std::sync::Arc::new(std::sync::Mutex::new(None));
let worker_child = std::sync::Arc::clone(&worker);
let call_task: Option<(Vec<IoBinding>, String, Vec<Expr>)> = match body.as_slice() {
[step] => extract_call(&step.kind)
.map(|(bindings, name, args)| (bindings, name.to_string(), args.to_vec())),
_ => None,
};
let import_task: Option<(Vec<IoBinding>, String, String)> = match body.as_slice() {
[step] => extract_import(&step.kind)
.map(|(bindings, path, alias)| (bindings, path.to_string(), alias.to_string())),
_ => None,
};
let returns_value = call_task.is_some() || import_task.is_some() || body_returns_value(&body);
let (entry_tx, entry_rx) = std::sync::mpsc::channel::<Arc<super::state::TaskEntry>>();
let join = std::thread::spawn(move || {
let _slot =
super::state::TaskSlotGuard::new(std::sync::Arc::clone(&forked_state.live_tasks));
*worker_child.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::thread::current().id());
let _out_keepalive = out_keepalive;
let mut child_state = forked_state;
let mut child_process = forked_process;
let entry = entry_rx
.recv()
.map_err(|_| anyhow::anyhow!("ASYNC task entry unavailable"))?;
if let Some((bindings, name, args)) = call_task {
let mut child_cx = super::steps::StepCtx {
state: &mut child_state,
process: &mut child_process,
stdin,
expose_stdin,
out,
err,
out_pipe,
stdin_pipe,
tty: None,
};
let value = if bindings.is_empty() {
call_func_value(&mut child_cx, &name, &args)?
} else {
let (task_stdin, task_expose, task_out, task_err, task_out_pipe, task_stdin_pipe) =
resolve_io_streams(&mut child_cx, &bindings, &body[0].kind)?;
let state = &mut *child_cx.state;
let process = &mut *child_cx.process;
let mut sub_cx = super::steps::StepCtx {
state,
process,
stdin: task_stdin,
expose_stdin: task_expose,
out: task_out,
err: task_err,
out_pipe: task_out_pipe.or(child_cx.out_pipe.clone()),
stdin_pipe: task_stdin_pipe.or(child_cx.stdin_pipe.clone()),
tty: None,
};
call_func_value(&mut sub_cx, &name, &args)?
};
entry
.state
.lock()
.unwrap_or_else(|e| e.into_inner())
.return_value = Some(value);
return Ok(());
}
if let Some((bindings, path, alias)) = import_task {
let mut child_cx = super::steps::StepCtx {
state: &mut child_state,
process: &mut child_process,
stdin,
expose_stdin,
out,
err,
out_pipe,
stdin_pipe,
tty: None,
};
let value = if bindings.is_empty() {
super::import::import_file(&mut child_cx, &path, &alias)?
} else {
let (task_stdin, task_expose, task_out, task_err, task_out_pipe, task_stdin_pipe) =
resolve_io_streams(&mut child_cx, &bindings, &body[0].kind)?;
let state = &mut *child_cx.state;
let process = &mut *child_cx.process;
let mut sub_cx = super::steps::StepCtx {
state,
process,
stdin: task_stdin,
expose_stdin: task_expose,
out: task_out,
err: task_err,
out_pipe: task_out_pipe.or(child_cx.out_pipe.clone()),
stdin_pipe: task_stdin_pipe.or(child_cx.stdin_pipe.clone()),
tty: None,
};
super::import::import_file(&mut sub_cx, &path, &alias)?
};
entry
.state
.lock()
.unwrap_or_else(|e| e.into_inner())
.return_value = Some(value);
return Ok(());
}
let flow = super::steps::execute_steps(
&mut child_state,
&mut child_process,
&body,
stdin,
expose_stdin,
out,
err,
out_pipe,
stdin_pipe,
true,
)?;
match flow {
Flow::Done => Ok(()),
Flow::Break { idx } => {
anyhow::bail!("step {}: BREAK cannot cross ASYNC boundary", idx + 1);
}
Flow::Continue { idx } => {
anyhow::bail!("step {}: CONTINUE cannot cross ASYNC boundary", idx + 1);
}
Flow::Return { value, .. } => {
entry
.state
.lock()
.unwrap_or_else(|e| e.into_inner())
.return_value = Some(value);
Ok(())
}
}
});
let handle =
super::steps::ThreadJoinHandle::new(join, cancel_token, cancel_hub, active_process, worker);
{
let mut named = cx
.state
.named_tasks
.lock()
.unwrap_or_else(|e| e.into_inner());
let entry = Arc::new(super::state::TaskEntry::new(
Box::new(handle),
returns_value,
Arc::clone(&tails),
));
named.insert(task_id, Arc::clone(&entry));
let _ = entry_tx.send(entry);
}
let tag = cx.state.resolve_tag(&decl_type)?;
cx.state
.declare_var(var.to_string(), tag, Value::handle(task_id))?;
Ok(())
}
fn resolve_task_entry<P: ProcessManager>(
var: &str,
cx: &StepCtx<'_, P>,
) -> Result<Arc<super::state::TaskEntry>> {
let val = cx
.state
.get_var(var)
.ok_or_else(|| anyhow::anyhow!("variable '${var}' is not defined"))?;
let Some(task_id) = val.as_handle() else {
bail!("variable '${var}' is not a task handle");
};
resolve_task_entry_by_id(task_id, &format!("${var}"), cx)
}
pub(crate) fn resolve_task_entry_by_id<P: ProcessManager>(
task_id: u64,
label: &str,
cx: &StepCtx<'_, P>,
) -> Result<Arc<super::state::TaskEntry>> {
let entry = {
let named = cx
.state
.named_tasks
.lock()
.unwrap_or_else(|e| e.into_inner());
named.get(&task_id).cloned()
};
let Some(entry) = entry else {
bail!("task handle for '{label}' was not found or has already been awaited");
};
Ok(entry)
}
fn await_task_entry(
entry: &Arc<super::state::TaskEntry>,
cancel_token: &Arc<std::sync::atomic::AtomicBool>,
var: &str,
) -> Result<std::process::ExitStatus> {
use super::state::TaskPhase;
{
let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
match guard.phase {
TaskPhase::Cancelled => {
drop(guard);
entry.wait_reaped();
bail!("AWAIT task '${var}' was cancelled");
}
TaskPhase::Completed | TaskPhase::Awaiting => {
bail!("task handle for '${var}' was not found or has already been awaited");
}
TaskPhase::Running => {
guard.phase = TaskPhase::Awaiting;
}
}
}
loop {
enum Decision {
Pending,
Cancelled,
KillOnTimeout,
Done(std::process::ExitStatus),
}
let mut timeout_kill: Option<Box<dyn BackgroundHandle>> = None;
let decision = {
let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
if matches!(guard.phase, TaskPhase::Cancelled) {
Decision::Cancelled
} else if cancel_token.load(std::sync::atomic::Ordering::SeqCst) {
match guard.handle.take() {
Some(handle) => {
guard.phase = TaskPhase::Cancelled;
timeout_kill = Some(handle);
Decision::KillOnTimeout
}
None => Decision::Cancelled,
}
} else {
match guard.handle.as_mut() {
Some(handle) => match handle.try_wait() {
Ok(Some(status)) => {
let _ = guard.handle.take();
guard.phase = TaskPhase::Completed;
Decision::Done(status)
}
Ok(None) => Decision::Pending,
Err(err) => {
let _ = guard.handle.take();
guard.phase = TaskPhase::Completed;
drop(guard);
entry.finish_teardown();
return Err(err);
}
},
None => Decision::Cancelled,
}
}
};
match decision {
Decision::Pending => {
std::thread::sleep(std::time::Duration::from_millis(10));
}
Decision::Cancelled => {
entry.wait_reaped();
bail!("AWAIT task '${var}' was cancelled");
}
Decision::KillOnTimeout => {
if let Some(mut handle) = timeout_kill {
let _ = handle.kill();
}
entry.finish_teardown();
bail!("AWAIT task '${var}' interrupted by TIMEOUT");
}
Decision::Done(status) => {
entry.finish_teardown();
if !status.success() {
bail!("AWAIT task '${var}' failed with status {status}");
}
return Ok(status);
}
}
}
}
pub(crate) fn dispatch_await<P: ProcessManager>(var: &str, cx: &mut StepCtx<'_, P>) -> Result<()> {
let val = cx
.state
.get_var(var)
.ok_or_else(|| anyhow::anyhow!("variable '${var}' is not defined"))?;
if let Some(items) = val.as_list().cloned() {
for (idx, item) in items.iter().enumerate() {
let member = format!("{var}[{idx}]");
let label = format!("${member}");
let Some(task_id) = item.as_handle() else {
bail!(
"AWAIT '{label}' is not a task handle, got {}",
item.type_name()
);
};
let entry = resolve_task_entry_by_id(task_id, &label, cx)?;
await_task_entry(&entry, &cx.state.cancel_token, &member)?;
}
return Ok(());
}
let entry = resolve_task_entry(var, cx)?;
await_task_entry(&entry, &cx.state.cancel_token, var)?;
Ok(())
}
pub(crate) fn dispatch_await_capture<P: ProcessManager>(
out_var: &str,
out_type: String,
task_var: &str,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let entry = resolve_task_entry(task_var, cx)?;
await_task_entry(&entry, &cx.state.cancel_token, task_var)?;
let (return_value, returns_value) = {
let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
(guard.return_value.clone(), guard.returns_value)
};
if let Some(value) = return_value {
let tag = cx.state.resolve_tag(&out_type)?;
cx.state
.declare_var(out_var.trim_start_matches('$').to_string(), tag, value)?;
return Ok(());
}
if returns_value {
anyhow::bail!(
"LET ${out_var} = AWAIT ${task_var} fell off the end without RETURN: the task body can return a value on some path but this run produced none"
);
}
let tag = cx.state.resolve_tag(&out_type)?;
cx.state.declare_var(
out_var.trim_start_matches('$').to_string(),
tag,
Value::int(0),
)?;
Ok(())
}
pub(crate) fn dispatch_cancel<P: ProcessManager>(var: &str, cx: &mut StepCtx<'_, P>) -> Result<()> {
use super::state::TaskPhase;
let val = cx
.state
.get_var(var)
.ok_or_else(|| anyhow::anyhow!("variable '${var}' is not defined"))?;
let Some(task_id) = val.as_handle() else {
bail!("variable '${var}' is not a task handle");
};
let entry = {
let named = cx
.state
.named_tasks
.lock()
.unwrap_or_else(|e| e.into_inner());
named.get(&task_id).cloned()
};
let Some(entry) = entry else {
bail!("CANCEL: task '${var}' has already been awaited or does not exist");
};
let handle = {
let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
match guard.phase {
TaskPhase::Cancelled => {
bail!("CANCEL: task '${var}' was already cancelled");
}
TaskPhase::Completed => {
bail!("CANCEL: task '${var}' has already been awaited or does not exist");
}
TaskPhase::Running | TaskPhase::Awaiting => {
guard.phase = TaskPhase::Cancelled;
guard.handle.take()
}
}
};
if let Some(mut handle) = handle {
handle.kill()?;
}
entry.finish_teardown();
Ok(())
}
pub(crate) fn dispatch_assign_async_step<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::AssignAsync {
var,
decl_type,
body,
} = step
else {
unreachable!()
};
dispatch_assign_async(var, decl_type.clone(), body, cx)
}
pub(crate) fn dispatch_await_step<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Await { var } = step else {
unreachable!()
};
dispatch_await(var, cx)
}
pub(crate) fn dispatch_assign_capture_step<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::AssignCapture {
var,
decl_type,
cmd,
} = step
else {
unreachable!()
};
top_level_flow(assign_capture(
cx,
super::steps::allocate_assert_generation(),
0,
var,
decl_type.clone(),
cmd,
)?)
}
pub(crate) fn dispatch_await_capture_step<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::AwaitCapture {
out_var,
out_type,
task_var,
} = step
else {
unreachable!()
};
dispatch_await_capture(out_var, out_type.clone(), task_var, cx)
}
pub(crate) fn dispatch_cancel_step<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Cancel { var } = step else {
unreachable!()
};
dispatch_cancel(var, cx)
}
pub(crate) fn dispatch_timeout_step<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Timeout { duration, body } = step else {
unreachable!()
};
let duration = super::args::resolve_arg_as_duration(duration, cx)?;
top_level_flow(timeout(cx, &duration, body)?)
}
pub(crate) fn dispatch_isolated_step<P: ProcessManager>(
step: &StepKind,
cx: &mut StepCtx<'_, P>,
) -> Result<()> {
let StepKind::Isolated { body } = step else {
unreachable!()
};
top_level_flow(isolated(cx, body)?)
}
pub(crate) fn timeout<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
duration: &std::time::Duration,
body: &[Step],
) -> Result<Flow> {
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
let initial_cancel = cx.state.cancel_token.load(Ordering::SeqCst);
let deadline = Instant::now() + *duration;
let done = Arc::new(AtomicBool::new(false));
let fired = Arc::new(AtomicBool::new(false));
let cancel_token = Arc::clone(&cx.state.cancel_token);
let cancel_hub = Arc::clone(&cx.state.cancel_hub);
let active_process = Arc::clone(&cx.state.active_process);
let watcher_done = Arc::clone(&done);
let watcher_fired = Arc::clone(&fired);
let watcher = std::thread::spawn(move || {
loop {
if watcher_done.load(Ordering::SeqCst) {
return;
}
if Instant::now() >= deadline {
watcher_fired.store(true, Ordering::SeqCst);
cancel_token.store(true, Ordering::SeqCst);
cancel_hub.mark_cancelled();
if let Ok(mut guard) = active_process.lock()
&& let Some(proc) = guard.as_mut()
{
let _ = proc.kill();
}
return;
}
std::thread::sleep(Duration::from_millis(10));
}
});
let prev_cancellable = cx.state.cancellable;
cx.state.cancellable = true;
let floor = cx.state.next_task_id.load(Ordering::SeqCst);
let prev_floor = cx.state.reap_floor.replace(floor);
let result = super::steps::execute_scoped_steps(
cx.state,
cx.process,
body,
cx.stdin.clone(),
cx.expose_stdin,
cx.out.clone(),
cx.err.clone(),
cx.out_pipe.clone(),
cx.stdin_pipe.clone(),
true,
);
cx.state.cancellable = prev_cancellable;
cx.state.reap_floor = prev_floor;
done.store(true, Ordering::SeqCst);
let _ = watcher.join();
if !fired.load(Ordering::SeqCst) {
cx.state
.cancel_token
.store(initial_cancel, Ordering::SeqCst);
}
let budget = oxdock_parser::command::format_duration(duration);
match result {
Ok(Flow::Done) => {
if fired.load(Ordering::SeqCst) {
bail!("TIMEOUT after {} — deadline exceeded", budget);
}
Ok(Flow::Done)
}
Ok(flow) => {
if fired.load(Ordering::SeqCst) {
bail!("TIMEOUT after {} — deadline exceeded", budget);
}
Ok(flow)
}
Err(err) => {
if fired.load(Ordering::SeqCst) {
Err(err).with_context(|| format!("TIMEOUT after {} — deadline exceeded", budget))
} else {
Err(err)
}
}
}
}
struct IsolatedScopeGuard<'a, 'b, P: ProcessManager> {
cx: &'a mut StepCtx<'b, P>,
}
impl<'a, 'b, P: ProcessManager> IsolatedScopeGuard<'a, 'b, P> {
fn enter(cx: &'a mut StepCtx<'b, P>) -> Self {
cx.state.isolated_stack.push(Arc::clone(&cx.state.envs));
cx.state.envs = Arc::clone(&cx.state.seed);
Self { cx }
}
}
impl<'a, 'b, P: ProcessManager> std::ops::Deref for IsolatedScopeGuard<'a, 'b, P> {
type Target = StepCtx<'b, P>;
fn deref(&self) -> &Self::Target {
self.cx
}
}
impl<'a, 'b, P: ProcessManager> std::ops::DerefMut for IsolatedScopeGuard<'a, 'b, P> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.cx
}
}
impl<P: ProcessManager> Drop for IsolatedScopeGuard<'_, '_, P> {
fn drop(&mut self) {
if let Some(snapshot) = self.cx.state.isolated_stack.pop() {
self.cx.state.envs = snapshot;
}
}
}
pub(crate) fn isolated<P: ProcessManager>(cx: &mut StepCtx<'_, P>, body: &[Step]) -> Result<Flow> {
let mut guard = IsolatedScopeGuard::enter(cx);
let scoped: &mut StepCtx<'_, P> = &mut guard;
let result = super::steps::execute_scoped_steps(
scoped.state,
scoped.process,
body,
scoped.stdin.clone(),
scoped.expose_stdin,
scoped.out.clone(),
scoped.err.clone(),
scoped.out_pipe.clone(),
scoped.stdin_pipe.clone(),
false,
);
drop(guard);
result.with_context(|| "inside ISOLATED block".to_string())
}
pub(crate) fn isolated_inherit_env<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
keys: &[String],
) -> Result<()> {
let Some(snapshot) = cx.state.isolated_stack.last().cloned() else {
bail!("isolated allowlist outside ISOLATED");
};
let envs = Arc::make_mut(&mut cx.state.envs);
for key in keys {
let matched = snapshot
.iter()
.find(|(k, _)| oxdock_process::names_eq(k, key));
if let Some((_, value)) = matched {
envs.retain(|k, _| !oxdock_process::names_eq(k, key));
envs.insert(key.clone(), value.clone());
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::{apply_prompt_answer, format_prompt};
#[test]
fn prompt_format_shows_default_in_brackets() {
assert_eq!(
format_prompt("Install destination?", Some("/tmp/bin")),
"Install destination? [/tmp/bin]: "
);
assert_eq!(
format_prompt("Install destination?", None),
"Install destination?: "
);
}
#[test]
fn prompt_answer_prefers_input_over_default() {
assert_eq!(
apply_prompt_answer("/custom/bin", Some("/tmp/bin")),
"/custom/bin"
);
assert_eq!(apply_prompt_answer("", Some("/tmp/bin")), "/tmp/bin");
assert_eq!(apply_prompt_answer("", None), "");
}
}