use std::collections::HashMap;
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, Command as SysCommand, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use crate::shell::ast::{Command, Pipeline, Redirect, ScriptNode, SeqOp};
use crate::shell::builtins::{is_inproc_builtin, run_inproc_builtin};
use crate::shell::environment::{expand_glob, ShellEnv};
#[cfg(unix)]
use nix::errno::Errno;
#[cfg(unix)]
use nix::sys::signal::{self, Signal};
#[cfg(unix)]
use nix::unistd::Pid;
#[cfg(unix)]
use std::os::unix::process::CommandExt;
#[derive(Debug, Clone)]
pub struct CommandResult {
pub command: Command,
pub stdout: String,
pub stderr: String,
pub exit_code: i32,
pub timed_out: bool,
pub output_files: Vec<(String, PathBuf)>,
pub piped_stdout: Option<PathBuf>,
}
#[derive(Debug, Clone)]
pub struct ScriptResult {
pub exit_code: i32,
pub stdout: String,
pub stderr: String,
pub timed_out: bool,
}
#[derive(Debug, Clone)]
struct RedirectLayout {
stdin_path: Option<PathBuf>,
stdout_path: PathBuf,
stderr_path: PathBuf,
stdout_append: bool,
stderr_append: bool,
stderr_to_stdout: bool,
explicit_stdout_redirect: bool,
explicit_stdin_redirect: bool,
explicit_stderr_redirect: bool,
pipe_stdout: bool,
}
#[derive(Debug, Clone)]
struct ParsedCommand {
env: ShellEnv,
args: Vec<String>,
not_count: usize,
not_crash: bool,
env_prefix_used: bool,
env_print: bool,
}
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
pub fn execute_script_node(
script: &ScriptNode,
shenv: &mut ShellEnv,
timeout: Option<Duration>,
) -> Result<ScriptResult, String> {
match script {
ScriptNode::Pipeline(pipeline) => execute_pipeline(pipeline, shenv, timeout),
ScriptNode::Seq(lhs, op, rhs) => match op {
SeqOp::Semicolon => {
let left = execute_script_node(lhs, shenv, timeout)?;
if left.timed_out {
return Ok(left);
}
let right = execute_script_node(rhs, shenv, timeout)?;
Ok(ScriptResult {
exit_code: right.exit_code,
stdout: concat_strings(&left.stdout, &right.stdout),
stderr: concat_strings(&left.stderr, &right.stderr),
timed_out: left.timed_out || right.timed_out,
})
}
SeqOp::Ampersand => Err("unsupported shell operator: '&'".to_string()),
SeqOp::Or => {
let left = execute_script_node(lhs, shenv, timeout)?;
if left.exit_code == 0 || left.timed_out {
Ok(left)
} else {
execute_script_node(rhs, shenv, timeout)
}
}
SeqOp::And => {
let left = execute_script_node(lhs, shenv, timeout)?;
if !left.timed_out && left.exit_code == 0 {
execute_script_node(rhs, shenv, timeout)
} else {
Ok(left)
}
}
},
}
}
fn execute_pipeline(
pipeline: &Pipeline,
shenv: &mut ShellEnv,
timeout: Option<Duration>,
) -> Result<ScriptResult, String> {
let mut command_results: Vec<CommandResult> = Vec::new();
let mut stdin_source = None;
for (idx, command) in pipeline.commands.iter().enumerate() {
let is_last = idx + 1 == pipeline.commands.len();
let result =
execute_single_command(command, shenv, stdin_source.clone(), is_last, timeout)?;
stdin_source = result.piped_stdout.clone();
let failed = result.exit_code != 0;
let timed_out = result.timed_out;
let pipeline_break = result.piped_stdout.is_none();
command_results.push(result);
if timed_out {
break;
}
if pipeline.pipe_fail && failed {
break;
}
if pipeline_break {
stdin_source = None;
}
}
let timed_out = command_results.iter().any(|result| result.timed_out);
let stdout = gather_output(&command_results, "stdout");
let stderr = gather_output(&command_results, "stderr");
let exit_code = if command_results.is_empty() {
0
} else if pipeline.pipe_fail {
command_results
.iter()
.find(|result| result.exit_code != 0)
.map(|result| result.exit_code)
.unwrap_or_else(|| {
command_results
.last()
.expect("pipeline not empty")
.exit_code
})
} else {
command_results
.last()
.expect("pipeline not empty")
.exit_code
};
let mut output_files = Vec::new();
for result in &command_results {
output_files.extend(result.output_files.clone());
}
let _ = output_files;
Ok(ScriptResult {
exit_code: if pipeline.negate {
i32::from(!(exit_code == 0))
} else {
exit_code
},
stdout,
stderr,
timed_out,
})
}
fn concat_strings(left: &str, right: &str) -> String {
let mut output = String::with_capacity(left.len() + right.len());
output.push_str(left);
output.push_str(right);
output
}
fn gather_output(results: &[CommandResult], stream: &str) -> String {
let mut output = String::new();
for result in results {
for (name, path) in &result.output_files {
if name != stream {
continue;
}
match fs::read_to_string(path) {
Ok(data) => output.push_str(&data),
Err(error) => output.push_str(&format!("{error}\n")),
}
}
}
output
}
fn parse_prefixes(command: &Command, shenv: &ShellEnv) -> Result<ParsedCommand, String> {
let args = command.args.clone();
let mut env = shenv.clone();
let mut not_count = 0usize;
let mut not_crash = false;
let mut env_prefix_used = false;
let mut env_print = None;
let mut pos = 0usize;
while pos < args.len() {
let token = args[pos].as_str();
if token == "not" {
not_count += 1;
pos += 1;
if pos < args.len() && args[pos] == "--crash" {
not_crash = true;
pos += 1;
}
continue;
}
if token == "!" {
not_count += 1;
pos += 1;
continue;
}
if token != "env" {
break;
}
env_prefix_used = true;
pos += 1;
while pos < args.len() {
match args[pos].as_str() {
"-i" => {
env.env.clear();
pos += 1;
}
"-u" => {
let name = args.get(pos + 1).ok_or_else(|| {
format!("'env -u' requires a variable name at position {}", pos + 1)
})?;
env.env.remove(name);
pos += 2;
}
value => {
if let Some((key, value)) = value.split_once('=') {
env.env.insert(key.to_string(), value.to_string());
pos += 1;
continue;
}
break;
}
}
}
if pos >= args.len() {
let mut entries = env
.env
.iter()
.map(|(key, value)| format!("{key}={value}"))
.collect::<Vec<_>>();
entries.sort_unstable();
env_print = Some(entries.join("\n"));
}
}
let args = args[pos..].to_vec();
if args.is_empty() {
if env_prefix_used {
return Ok(ParsedCommand {
env,
args: Vec::new(),
not_count,
not_crash,
env_prefix_used,
env_print: true,
});
}
return Err("empty command".to_string());
}
Ok(ParsedCommand {
env,
args,
not_count,
not_crash,
env_prefix_used,
env_print: env_print.is_some(),
})
}
fn execute_single_command(
command: &Command,
shenv: &mut ShellEnv,
stdin_source: Option<PathBuf>,
is_last: bool,
timeout: Option<Duration>,
) -> Result<CommandResult, String> {
let mut parsed = parse_prefixes(command, shenv)?;
if parsed.env_print {
return Ok(CommandResult {
command: command.clone(),
stdout: parsed
.env
.env
.iter()
.map(|(key, value)| format!("{key}={value}"))
.collect::<Vec<_>>()
.join("\n")
+ "\n",
stderr: String::new(),
exit_code: 0,
timed_out: false,
output_files: Vec::new(),
piped_stdout: None,
});
}
expand_late_substitutions(&mut parsed.args, &parsed.env.cwd)?;
expand_glob_arguments(&mut parsed.args, &parsed.env.cwd);
if parsed.args.is_empty() {
return Err("empty command".to_string());
}
let executable = parsed.args[0].clone();
let remaining_args = parsed.args[1..].to_vec();
let layout = resolve_redirects(&command.redirects, &parsed.env.cwd, stdin_source, !is_last)?;
let use_inproc_builtin = is_inproc_builtin(&executable)
&& !parsed.not_crash
&& is_last
&& !parsed.env_prefix_used
&& command.redirects.is_empty()
&& !layout.stderr_to_stdout;
if use_inproc_builtin {
let mut stdin = None;
if let Some(path) = &layout.stdin_path {
stdin = Some(
read_file_to_string(path)
.map_err(|error| format!("failed to read stdin file: {error}"))?,
);
}
let mut command_env = parsed.env;
let result = run_inproc_builtin(
&Command {
args: std::iter::once(executable.clone())
.chain(remaining_args)
.collect(),
redirects: Vec::new(),
},
&mut command_env,
stdin.as_deref(),
)?;
write_all_to_file(&layout.stdout_path, layout.stdout_append, &result.stdout)?;
if layout.stderr_to_stdout {
write_all_to_file(&layout.stdout_path, layout.stdout_append, &result.stderr)?;
} else {
write_all_to_file(&layout.stderr_path, layout.stderr_append, &result.stderr)?;
}
*shenv = command_env;
let mut exit_code = result.exit_code;
apply_not(&mut exit_code, parsed.not_count, parsed.not_crash);
return Ok(CommandResult {
command: command.clone(),
stdout: read_file_to_string(&layout.stdout_path).unwrap_or_default(),
stderr: if layout.stderr_to_stdout {
String::new()
} else {
read_file_to_string(&layout.stderr_path).unwrap_or_default()
},
exit_code,
timed_out: false,
output_files: vec![
("stdout".to_string(), layout.stdout_path.clone()),
("stderr".to_string(), layout.stderr_path.clone()),
],
piped_stdout: if layout.pipe_stdout {
Some(layout.stdout_path)
} else {
None
},
});
}
let result =
execute_external_command(&executable, &remaining_args, &parsed.env, &layout, timeout)?;
let mut exit_code = result.exit_code;
apply_not(&mut exit_code, parsed.not_count, parsed.not_crash);
Ok(CommandResult {
exit_code,
command: command.clone(),
stdout: result.stdout,
stderr: result.stderr,
timed_out: result.timed_out,
output_files: result.output_files,
piped_stdout: if layout.pipe_stdout {
Some(layout.stdout_path)
} else {
None
},
})
}
fn execute_external_command(
executable: &str,
args: &[String],
env: &ShellEnv,
layout: &RedirectLayout,
timeout: Option<Duration>,
) -> Result<CommandResult, String> {
let resolved_executable = resolve_executable(executable, &env.env)?;
let stdin_file = layout
.stdin_path
.as_ref()
.map(|path| File::open(path).map_err(|error| error.to_string()))
.transpose()?;
let stdout_file =
open_output_file(&layout.stdout_path, layout.stdout_append).map_err(|error| {
format!(
"failed to open stdout file '{}': {error}",
layout.stdout_path.display()
)
})?;
let mut stderr_sink = if layout.stderr_to_stdout {
Some(
stdout_file
.try_clone()
.map_err(|error| format!("failed to clone stdout for stderr: {error}"))?,
)
} else {
Some(
open_output_file(&layout.stderr_path, layout.stderr_append).map_err(|error| {
format!(
"failed to open stderr file '{}': {error}",
layout.stderr_path.display()
)
})?,
)
};
let mut command = SysCommand::new(resolved_executable);
command
.args(args)
.current_dir(&env.cwd)
.env_clear()
.envs(&env.env)
.stdin(stdin_file.map_or(Stdio::null(), Stdio::from))
.stdout(Stdio::from(stdout_file));
#[cfg(unix)]
{
unsafe {
command.pre_exec(|| {
nix::unistd::setpgid(Pid::from_raw(0), Pid::from_raw(0))
.map_err(io::Error::other)?;
Ok(())
});
}
}
if let Some(stderr) = stderr_sink.take() {
command.stderr(Stdio::from(stderr));
}
let mut process = command
.spawn()
.map_err(|error| format!("failed to spawn command '{executable}': {error}"))?;
let (exit_code, timed_out) = wait_for_process_timeout(&mut process, timeout)
.map_err(|error| format!("failed while waiting for '{executable}': {error}"))?;
Ok(CommandResult {
command: Command {
args: std::iter::once(executable.to_string())
.chain(args.iter().cloned())
.collect(),
redirects: Vec::new(),
},
stdout: read_file_to_string(&layout.stdout_path).unwrap_or_default(),
stderr: if layout.stderr_to_stdout {
String::new()
} else {
read_file_to_string(&layout.stderr_path).unwrap_or_default()
},
exit_code,
timed_out,
output_files: vec![
("stdout".to_string(), layout.stdout_path.clone()),
("stderr".to_string(), layout.stderr_path.clone()),
],
piped_stdout: None,
})
}
fn resolve_redirects(
redirects: &[Redirect],
cwd: &Path,
stdin_source: Option<PathBuf>,
in_pipeline: bool,
) -> Result<RedirectLayout, String> {
let mut layout = RedirectLayout {
stdin_path: stdin_source,
stdout_path: next_temp_file("stdout"),
stderr_path: next_temp_file("stderr"),
stdout_append: false,
stderr_append: false,
stderr_to_stdout: false,
explicit_stdout_redirect: false,
explicit_stdin_redirect: false,
explicit_stderr_redirect: false,
pipe_stdout: false,
};
for redirect in redirects {
let target = expand_glob_argument(&redirect.target, cwd)?;
let path = resolve_path(cwd, &target);
match (redirect.source_fd, redirect.op.as_str()) {
(0, "<") => {
layout.stdin_path = Some(path);
layout.explicit_stdin_redirect = true;
}
(1, ">") => {
layout.stdout_path = path;
layout.stdout_append = false;
layout.explicit_stdout_redirect = true;
}
(1, ">>") => {
layout.stdout_path = path;
layout.stdout_append = true;
layout.explicit_stdout_redirect = true;
}
(2, "2>") => {
layout.stderr_path = path;
layout.stderr_append = false;
layout.explicit_stderr_redirect = true;
}
(2, "2>>") => {
layout.stderr_path = path;
layout.stderr_append = true;
layout.explicit_stderr_redirect = true;
}
(2, ">&") if target == "1" => {
layout.stderr_to_stdout = true;
layout.explicit_stderr_redirect = true;
}
(1, "&>") => {
layout.stdout_path = path;
layout.stdout_append = false;
layout.explicit_stdout_redirect = true;
layout.stderr_to_stdout = true;
}
(1, ">&") if target == "2" => {
layout.explicit_stdout_redirect = true;
layout.explicit_stderr_redirect = true;
layout.stdout_path = layout.stderr_path.clone();
}
_ => {
return Err(format!(
"unsupported redirection '{}{} {}'",
redirect.source_fd, redirect.op, redirect.target
));
}
}
}
layout.pipe_stdout =
in_pipeline && !layout.explicit_stdout_redirect && !layout.explicit_stdin_redirect;
Ok(layout)
}
fn resolve_path(cwd: &Path, target: &str) -> PathBuf {
let candidate = PathBuf::from(target);
if candidate.is_absolute() {
candidate
} else {
cwd.join(candidate)
}
}
fn expand_glob_arguments(args: &mut Vec<String>, cwd: &Path) {
let mut expanded = Vec::new();
for arg in args.drain(..) {
expanded.extend(expand_glob(&arg, cwd));
}
*args = expanded;
}
fn expand_late_substitutions(args: &mut [String], cwd: &Path) -> Result<(), String> {
let marker = "%{readfile:";
for arg in args {
let mut out = String::new();
let mut rest = arg.as_str();
while let Some(start) = rest.find(marker) {
out.push_str(&rest[..start]);
let candidate = &rest[start + marker.len()..];
let Some(end) = candidate.find('}') else {
return Err("readfile substitution missing '}'".to_string());
};
let path = &candidate[..end];
let absolute = if Path::new(path).is_absolute() {
PathBuf::from(path)
} else {
cwd.join(path)
};
let contents = fs::read_to_string(&absolute).map_err(|error| {
format!(
"readfile substitution failed for '{}': {}",
absolute.display(),
error
)
})?;
out.push_str(&contents);
rest = &candidate[end + 1..];
}
out.push_str(rest);
*arg = out;
}
Ok(())
}
fn resolve_executable(name: &str, env_vars: &HashMap<String, String>) -> Result<PathBuf, String> {
if name.contains('/') || name.contains('\\') {
let candidate = PathBuf::from(name);
if candidate.exists() {
return Ok(candidate);
}
return Err(format!("{name}: command not found"));
}
let path = env_vars
.get("PATH")
.cloned()
.or_else(|| std::env::var("PATH").ok());
let search_paths = path
.as_deref()
.map(std::env::split_paths)
.map(|paths| paths.collect::<Vec<_>>())
.unwrap_or_else(|| {
std::env::current_dir()
.ok()
.map_or_else(|| vec![PathBuf::from(".")], |cwd| vec![cwd])
});
let mut candidates = Vec::new();
for search in search_paths {
let candidate = search.join(name);
candidates.push(candidate);
if cfg!(windows) {
let path_ext = env_vars
.get("PATHEXT")
.cloned()
.or_else(|| {
std::env::var("PATHEXT")
.ok()
.or(Some(String::from(".COM;.EXE;.BAT;.CMD")))
})
.unwrap_or_default();
let mut exts = path_ext.split(';').collect::<Vec<_>>();
exts.push("");
for ext in exts {
let candidate = search.join(format!("{name}{ext}"));
candidates.push(candidate);
}
}
}
candidates
.into_iter()
.find(|candidate| {
if !candidate.exists() {
return false;
}
let meta = candidate.metadata().ok();
match meta {
Some(meta) if meta.is_file() => {
if cfg!(unix) {
use std::os::unix::fs::PermissionsExt;
meta.permissions().mode() & 0o111 != 0
} else {
true
}
}
_ => false,
}
})
.ok_or_else(|| format!("{name}: command not found"))
}
fn open_output_file(path: &Path, append: bool) -> io::Result<File> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let mut options = fs::OpenOptions::new();
options.write(true).create(true);
if append {
options.append(true);
} else {
options.truncate(true).write(true);
}
options.open(path)
}
fn write_all_to_file(path: &Path, append: bool, text: &str) -> Result<(), String> {
let mut file = open_output_file(path, append).map_err(|error| {
format!(
"failed to open output file '{}' for write: {error}",
path.display()
)
})?;
file.write_all(text.as_bytes())
.map_err(|error| format!("failed to write output file '{}': {error}", path.display()))
}
fn read_file_to_string(path: &Path) -> io::Result<String> {
let mut file = File::open(path)?;
let mut out = String::new();
file.read_to_string(&mut out)?;
Ok(out)
}
pub(crate) fn wait_for_process_timeout(
process: &mut Child,
timeout: Option<Duration>,
) -> Result<(i32, bool), String> {
let Some(timeout) = timeout else {
let status = process
.wait()
.map_err(|error| format!("failed waiting for child: {error}"))?;
return Ok((process_exit_code(status), false));
};
let deadline = Instant::now() + timeout;
loop {
if let Some(status) = process
.try_wait()
.map_err(|error| format!("failed checking process status: {error}"))?
{
return Ok((process_exit_code(status), false));
}
if Instant::now() >= deadline {
let pid = process.id();
kill_command_tree(pid).ok();
let status = process
.wait()
.map_err(|error| format!("failed waiting for child after timeout: {error}"))?;
return Ok((process_exit_code(status), true));
}
std::thread::sleep(Duration::from_millis(10));
}
}
fn process_exit_code(status: std::process::ExitStatus) -> i32 {
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
if let Some(signal) = status.signal() {
return -signal;
}
}
status.code().unwrap_or(128)
}
fn kill_command_tree(pid: u32) -> Result<(), String> {
#[cfg(unix)]
{
let c_pid = Pid::from_raw(pid as i32);
signal::killpg(c_pid, Signal::SIGKILL)
.or_else(|error| {
if matches!(error, Errno::ESRCH) {
Ok(())
} else {
Err(error)
}
})
.map_err(|error| error.to_string())?;
Ok(())
}
#[cfg(not(unix))]
{
let _ = pid;
Ok(())
}
}
fn apply_not(code: &mut i32, not_count: usize, not_crash: bool) {
if not_count % 2 == 0 {
if not_count > 1 && *code != 0 {
*code = 1;
}
return;
}
if not_crash {
if *code <= 0 {
*code = 1;
} else {
*code = 0;
}
} else if *code == 0 {
*code = 1;
} else {
*code = 0;
}
}
fn expand_glob_argument(raw: &str, cwd: &Path) -> Result<String, String> {
let expanded = expand_glob(raw, cwd);
if expanded.len() != 1 {
return Err(format!(
"globbing produced multiple results for redirect '{}'
{}",
raw,
expanded.join(", ")
));
}
Ok(expanded
.into_iter()
.next()
.expect("glob expansion always returns at least one element"))
}
fn next_temp_file(tag: &str) -> PathBuf {
let serial = TEMP_COUNTER.fetch_add(1, Ordering::SeqCst);
let pid = std::process::id();
let mut path = std::env::temp_dir();
path.push(format!("litnik-{tag}-{pid}-{serial}"));
path
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::path::PathBuf;
use tempfile::tempdir;
use crate::shell::environment::ShellEnv;
use crate::shell::ShParser;
#[test]
fn executes_single_command_with_not() {
let path = std::env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| String::from("."));
let command = "not false";
let mut parser = ShParser::new(command, false, false);
let ast = parser.parse().unwrap();
let mut env = ShellEnv::new(PathBuf::from(path), HashMap::new(), false);
let result = super::execute_script_node(&ast, &mut env, None).unwrap();
assert_eq!(result.exit_code, 0);
}
#[test]
fn executes_double_not_as_double_negation() {
let path = std::env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| String::from("."));
let command = "not not false";
let mut parser = ShParser::new(command, false, false);
let ast = parser.parse().unwrap();
let mut env = ShellEnv::new(PathBuf::from(path.clone()), HashMap::new(), false);
let result = super::execute_script_node(&ast, &mut env, None).unwrap();
assert_eq!(result.exit_code, 1);
let command = "not ! false";
let mut parser = ShParser::new(command, false, false);
let ast = parser.parse().unwrap();
let result = super::execute_script_node(&ast, &mut env, None).unwrap();
assert_eq!(result.exit_code, 1);
}
#[test]
fn executes_single_command_with_not_crash() {
let path = std::env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| String::from("."));
let mut parser = ShParser::new("not --crash false", false, false);
let ast = parser.parse().unwrap();
let mut env = ShellEnv::new(PathBuf::from(path), HashMap::new(), false);
let should_crash = super::execute_script_node(&ast, &mut env, None).unwrap();
assert_eq!(should_crash.exit_code, 0);
let mut parser = ShParser::new("not --crash true", false, false);
let ast = parser.parse().unwrap();
let succeeded = super::execute_script_node(&ast, &mut env, None).unwrap();
assert_eq!(succeeded.exit_code, 1);
}
#[test]
fn executes_redirect_stderr_to_stdout() {
let root = tempdir().unwrap();
let out_path = root.path().join("out.txt");
let command = format!(
"/bin/sh -c 'printf \"stdout\\\\n\"; printf \"stderr\\\\n\" 1>&2' > {} 2>&1",
out_path.display()
);
let mut parser = ShParser::new(&command, false, false);
let ast = parser.parse().unwrap();
let mut env = ShellEnv::new(
std::env::var("CARGO_TARGET_DIR")
.unwrap_or_else(|_| String::from("."))
.into(),
HashMap::new(),
false,
);
let result = super::execute_script_node(&ast, &mut env, None).unwrap();
assert_eq!(result.exit_code, 0);
let output = std::fs::read_to_string(&out_path).unwrap_or_default();
assert!(output.contains("stdout"));
assert!(output.contains("stderr"));
}
#[test]
fn pipeline_respects_pipefail_setting() {
let root = tempdir().unwrap();
let path = root.path().to_path_buf();
let command = "false | true";
let mut parser = ShParser::new(command, false, true);
let ast = parser.parse().unwrap();
let mut env = ShellEnv::new(path.clone(), HashMap::new(), false);
let result = super::execute_script_node(&ast, &mut env, None).unwrap();
assert_eq!(result.exit_code, 1);
let mut parser = ShParser::new(command, false, false);
let ast = parser.parse().unwrap();
let mut env = ShellEnv::new(path, HashMap::new(), false);
let result = super::execute_script_node(&ast, &mut env, None).unwrap();
assert_eq!(result.exit_code, 0);
}
#[test]
fn substitution_readfile_is_applied() {
let tmp = tempdir().unwrap();
let file = tmp.path().join("x.txt");
std::fs::write(&file, "abc").unwrap();
let mut args = vec!["cat".to_string(), "%{readfile:./x.txt}".to_string()];
let cwd = tmp.path();
super::expand_late_substitutions(&mut args, cwd).unwrap();
assert_eq!(args[1], "abc");
}
}