use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Target {
Script(PathBuf),
Inferred(PathBuf),
Unresolved(String),
}
pub(super) struct Context<'a> {
pub script: &'a Path,
pub root: &'a Path,
pub all: &'a [PathBuf],
}
type Vars = BTreeMap<String, PathBuf>;
type Held = BTreeMap<String, String>;
pub(super) fn calls(text: &str, cx: &Context<'_>) -> Vec<Target> {
let mut vars = Vars::new();
let mut held = Held::new();
let mut out = Vec::new();
for line in text.lines() {
let line = line.trim();
if line.starts_with('#') {
continue;
}
let words = words(line);
assign(&words, cx, &mut vars, &mut held);
for call in invoked(&words, &held) {
out.push(resolve(&call, cx, &vars));
}
}
out
}
fn assign(
words: &[String],
cx: &Context<'_>,
vars: &mut Vars,
held: &mut Held,
) {
let prefix = ["export", "readonly", "local"];
for w in words.iter().filter(|w| !prefix.contains(&w.as_str())) {
let Some((name, value)) = w.split_once('=') else {
break;
};
if !is_name(name) {
break;
}
let value = unquote(value);
let dir = eval(&value, cx, vars);
set(vars, name, dir);
let call = held_call(&value, vars, held);
set(held, name, call);
}
}
fn set<V>(map: &mut BTreeMap<String, V>, name: &str, value: Option<V>) {
match value {
Some(v) => map.insert(name.to_string(), v),
None => map.remove(name),
};
}
fn held_call(value: &str, vars: &Vars, held: &Held) -> Option<String> {
if value.ends_with(".sh") {
return Some(value.to_string());
}
let (inner, tail) = balanced(value.strip_prefix("${")?, '{', '}')?;
let (name, default) = inner.split_once(":-").filter(|_| tail.is_empty())?;
match held.get(name) {
Some(call) => Some(call.clone()),
None if vars.contains_key(name) => None,
None => default_call(default),
}
}
fn default_call(default: &str) -> Option<String> {
let words = words(default);
let call = match words.as_slice() {
[runner, x] if is_runner(&unquote(runner)) => unquote(x),
_ => default.to_string(),
};
call.ends_with(".sh").then_some(call)
}
fn script_word(bare: &str, held: &Held) -> Option<String> {
if bare.ends_with(".sh") {
return Some(bare.to_string());
}
let rest = bare.strip_prefix('$')?;
let name = rest
.strip_prefix('{')
.and_then(|r| r.strip_suffix('}'))
.unwrap_or(rest);
held.get(name).cloned()
}
fn is_name(s: &str) -> bool {
let mut cs = s.chars();
cs.next()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& cs.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
fn is_assignment(w: &str) -> bool {
w.split_once('=').is_some_and(|(n, _)| is_name(n))
}
fn invoked(words: &[String], held: &Held) -> Vec<String> {
let mut out = Vec::new();
let mut at_command = true;
let mut runner = false;
let mut shell_in_command = false;
for w in words {
for inner in substitutions(w) {
out.extend(invoked(&self::words(&inner), held));
}
let bare = unquote(w);
shell_in_command |= matches!(bare.as_str(), "sh" | "bash");
if is_separator(&bare) {
at_command = true;
runner = false;
shell_in_command = false;
continue;
}
let call = script_word(&bare, held);
let script = call.is_some();
if shell_in_command && script && bare.starts_with('<') {
out.push(bare);
continue;
}
let flag = runner && bare.starts_with('-');
let prefix = at_command && is_assignment(w);
if flag || prefix {
continue;
}
let next_runner = at_command && !script && is_runner(&bare);
if let Some(call) = call.filter(|_| at_command || runner) {
out.push(call);
}
runner = next_runner;
at_command = false;
}
out
}
fn is_runner(w: &str) -> bool {
matches!(w, "source" | "." | "bash" | "sh" | "exec")
}
fn is_separator(w: &str) -> bool {
matches!(
w,
";" | "&&"
| "||"
| "|"
| "&"
| "then"
| "do"
| "else"
| "elif"
| "if"
| "while"
| "until"
| "!"
| "time"
| "{"
| "("
)
}
fn substitutions(word: &str) -> Vec<String> {
let mut out = Vec::new();
let mut rest = word;
while let Some(i) = rest.find("$(") {
let after = rest.get(i.saturating_add(2)..).unwrap_or("");
match balanced(after, '(', ')') {
Some((inner, tail)) => {
out.push(inner.to_string());
rest = tail;
}
None => break,
}
}
out
}
fn words(line: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cur = String::new();
let mut quote: Option<char> = None;
let mut depth = 0usize;
let mut chars = line.chars().peekable();
while let Some(c) = chars.next() {
match (quote, c) {
(Some(q), _) if c == q => {
quote = None;
cur.push(c);
}
(Some(_), _) => cur.push(c),
(None, '\'' | '"') => {
quote = Some(c);
cur.push(c);
}
(None, '(') => {
depth = depth.saturating_add(1);
cur.push(c);
}
(None, ')') => {
depth = depth.saturating_sub(1);
cur.push(c);
}
(None, ' ' | '\t') if depth == 0 => flush(&mut cur, &mut out),
(None, ';' | '|' | '&') if depth == 0 => {
flush(&mut cur, &mut out);
let mut op = c.to_string();
while chars.next_if_eq(&c).is_some() {
op.push(c);
}
out.push(op);
}
_ => cur.push(c),
}
}
flush(&mut cur, &mut out);
out
}
fn flush(cur: &mut String, out: &mut Vec<String>) {
if !cur.is_empty() {
out.push(std::mem::take(cur));
}
}
fn unquote(w: &str) -> String {
w.chars().filter(|c| *c != '"' && *c != '\'').collect()
}
fn eval(expr: &str, cx: &Context<'_>, vars: &Vars) -> Option<PathBuf> {
if expr.starts_with('/') && !expr.contains('$') {
return Some(normalize(Path::new(expr)));
}
let (base, tail) = if let Some(rest) = expr.strip_prefix("$(") {
let (inner, tail) = balanced(rest, '(', ')')?;
(command_dir(inner.trim(), cx, vars)?, tail)
} else if let Some(rest) = expr.strip_prefix("${") {
let (inner, tail) = balanced(rest, '{', '}')?;
(braced(inner, cx, vars)?, tail)
} else {
let rest = expr.strip_prefix('$')?;
let end = rest
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
.unwrap_or(rest.len());
let (name, tail) = rest.split_at(end);
(vars.get(name).cloned()?, tail)
};
if tail.contains('$') {
return None;
}
Some(normalize(&base.join(tail.trim_start_matches('/'))))
}
fn braced(inner: &str, cx: &Context<'_>, vars: &Vars) -> Option<PathBuf> {
match inner.split_once(":-") {
Some((name, default)) => {
vars.get(name).cloned().or_else(|| eval(default, cx, vars))
}
None => vars.get(inner).cloned(),
}
}
fn command_dir(cmd: &str, cx: &Context<'_>, vars: &Vars) -> Option<PathBuf> {
if let Some(arg) = cmd.strip_prefix("dirname ") {
let own = arg.contains("$0") || arg.contains("BASH_SOURCE");
return own.then(|| cx.script.parent().map(Path::to_path_buf))?;
}
if cmd.starts_with("git rev-parse --show-toplevel") {
return Some(cx.root.to_path_buf());
}
let rest = cmd.strip_prefix("cd ")?;
let arg = words(rest).into_iter().next()?;
eval(&unquote(&arg), cx, vars)
}
fn balanced(s: &str, open: char, close: char) -> Option<(&str, &str)> {
let mut depth = 1usize;
for (i, c) in s.char_indices() {
if c == open {
depth = depth.saturating_add(1);
} else if c == close {
depth = depth.saturating_sub(1);
if depth == 0 {
return Some((s.get(..i)?, s.get(i.saturating_add(1)..)?));
}
}
}
None
}
fn normalize(p: &Path) -> PathBuf {
let mut out = PathBuf::new();
for c in p.components() {
match c {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
other => out.push(other.as_os_str()),
}
}
out
}
fn resolve(call: &str, cx: &Context<'_>, vars: &Vars) -> Target {
let call = call.trim_start_matches('<');
let candidates: Vec<PathBuf> = if call.starts_with('$') {
eval(call, cx, vars).into_iter().collect()
} else if call.contains('$') {
Vec::new()
} else {
let here = cx.script.parent().unwrap_or(cx.root);
vec![normalize(&here.join(call)), normalize(&cx.root.join(call))]
};
let bound = !candidates.is_empty();
if let Some(p) = candidates.into_iter().find(|c| cx.all.contains(c)) {
return Target::Script(p);
}
if bound {
return Target::Unresolved(call.to_string());
}
unbound_tail(call)
.map(|tail| normalize(&cx.root.join(tail)))
.filter(|p| cx.all.contains(p))
.map_or_else(|| Target::Unresolved(call.to_string()), Target::Inferred)
}
fn unbound_tail(call: &str) -> Option<&str> {
let rest = call.strip_prefix('$')?;
let tail = if let Some(braced) = rest.strip_prefix('{') {
balanced(braced, '{', '}')?.1
} else {
let end = rest
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
.unwrap_or(rest.len());
rest.get(end..)?
};
let tail = tail.strip_prefix('/')?;
(!tail.is_empty() && !tail.contains('$')).then_some(tail)
}