#![forbid(unsafe_code)]
#![warn(missing_docs)]
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
pub struct ReadmeDoctests;
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::convert::Infallible;
use std::fmt;
pub const DEFAULT_MAX_DEPTH: usize = 64;
pub trait Context {
type Error;
fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, Self::Error>;
fn set(&mut self, _name: &str, _value: &str) -> Result<bool, Self::Error> {
Ok(false)
}
}
impl Context for HashMap<String, String> {
type Error = Infallible;
fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, Infallible> {
Ok(HashMap::get(self, name).map(|v| Cow::Borrowed(v.as_str())))
}
fn set(&mut self, name: &str, value: &str) -> Result<bool, Infallible> {
self.insert(name.to_string(), value.to_string());
Ok(true)
}
}
impl Context for BTreeMap<String, String> {
type Error = Infallible;
fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, Infallible> {
Ok(BTreeMap::get(self, name).map(|v| Cow::Borrowed(v.as_str())))
}
fn set(&mut self, name: &str, value: &str) -> Result<bool, Infallible> {
self.insert(name.to_string(), value.to_string());
Ok(true)
}
}
impl Context for &HashMap<String, String> {
type Error = Infallible;
fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, Infallible> {
Ok((**self).get(name).map(|v| Cow::Borrowed(v.as_str())))
}
}
impl Context for &BTreeMap<String, String> {
type Error = Infallible;
fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, Infallible> {
Ok((**self).get(name).map(|v| Cow::Borrowed(v.as_str())))
}
}
impl<F: FnMut(&str) -> Option<String>> Context for F {
type Error = Infallible;
fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, Infallible> {
Ok(self(name).map(Cow::Owned))
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Env;
impl Context for Env {
type Error = Infallible;
fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, Infallible> {
Ok(std::env::var(name).ok().map(Cow::Owned))
}
}
#[derive(Debug, Clone)]
pub struct TryFn<F>(pub F);
impl<F, E> Context for TryFn<F>
where
F: FnMut(&str) -> Result<Option<String>, E>,
{
type Error = E;
fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, E> {
Ok((self.0)(name)?.map(Cow::Owned))
}
}
#[derive(Debug, Clone)]
pub struct Chain<A, B>(A, B);
impl<A, B> Context for Chain<A, B>
where
A: Context,
B: Context<Error = A::Error>,
{
type Error = A::Error;
fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, Self::Error> {
match self.0.get(name)? {
Some(v) => Ok(Some(Cow::Owned(v.into_owned()))),
None => Ok(self.1.get(name)?.map(|v| Cow::Owned(v.into_owned()))),
}
}
fn set(&mut self, name: &str, value: &str) -> Result<bool, Self::Error> {
if self.0.set(name, value)? {
return Ok(true);
}
self.1.set(name, value)
}
}
pub trait ContextExt: Context + Sized {
fn chain<B: Context<Error = Self::Error>>(self, fallback: B) -> Chain<Self, B> {
Chain(self, fallback)
}
}
impl<C: Context + Sized> ContextExt for C {}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Error<E> {
Required {
var: String,
message: String,
},
BadSubstitution(String),
AssignUnsupported {
var: String,
},
TooDeep,
Context(E),
}
impl<E: fmt::Display> fmt::Display for Error<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Required { var, message } if message.is_empty() => {
write!(f, "{var}: parameter null or not set")
}
Error::Required { var, message } => write!(f, "{var}: {message}"),
Error::BadSubstitution(s) => write!(f, "bad substitution: ${{{s}}}"),
Error::AssignUnsupported { var } => {
write!(f, "{var}: assignment not supported by this context")
}
Error::TooDeep => write!(f, "expansion nested too deeply"),
Error::Context(e) => write!(f, "variable lookup failed: {e}"),
}
}
}
impl<E: fmt::Debug + fmt::Display> std::error::Error for Error<E> {}
impl<E> From<E> for Error<E> {
fn from(e: E) -> Self {
Error::Context(e)
}
}
pub fn expand<C: Context>(input: &str, ctx: &mut C) -> Result<String, Error<C::Error>> {
Expander::new().expand(input, ctx)
}
#[derive(Debug, Clone)]
pub struct Expander {
max_depth: usize,
}
impl Default for Expander {
fn default() -> Self {
Self::new()
}
}
impl Expander {
pub fn new() -> Self {
Expander {
max_depth: DEFAULT_MAX_DEPTH,
}
}
pub fn max_depth(mut self, depth: usize) -> Self {
self.max_depth = depth;
self
}
pub fn expand<C: Context>(&self, input: &str, ctx: &mut C) -> Result<String, Error<C::Error>> {
self.expand_depth(input, ctx, 0)
}
fn expand_depth<C: Context>(
&self,
input: &str,
ctx: &mut C,
depth: usize,
) -> Result<String, Error<C::Error>> {
if depth > self.max_depth {
return Err(Error::TooDeep);
}
let mut out = String::with_capacity(input.len());
let chars: Vec<char> = input.chars().collect();
let mut i = 0;
while i < chars.len() {
match chars[i] {
'\\' if i + 1 < chars.len() && chars[i + 1] == '$' => {
out.push('$');
i += 2;
}
'$' if i + 1 < chars.len() => {
if chars[i + 1] == '{' {
let (inner, end) = read_braced(&chars, i + 2)?;
out.push_str(&self.expand_braced(&inner, ctx, depth)?);
i = end;
} else if let Some((name, end)) = read_name(&chars, i + 1) {
if let Some(v) = get(ctx, &name)? {
out.push_str(&v);
}
i = end;
} else {
out.push('$');
i += 1;
}
}
c => {
out.push(c);
i += 1;
}
}
}
Ok(out)
}
fn expand_braced<C: Context>(
&self,
body: &str,
ctx: &mut C,
depth: usize,
) -> Result<String, Error<C::Error>> {
if let Some(rest) = body.strip_prefix('#') {
if is_name(rest) {
let len = get(ctx, rest)?.map(|v| v.chars().count()).unwrap_or(0);
return Ok(len.to_string());
}
}
if let Some(rest) = body.strip_prefix('!') {
if is_name(rest) {
let target = get(ctx, rest)?.unwrap_or_default();
return Ok(get(ctx, &target)?.unwrap_or_default());
}
}
let chars: Vec<char> = body.chars().collect();
let (name, op_start) =
read_name(&chars, 0).ok_or_else(|| Error::BadSubstitution(body.to_string()))?;
let op: String = chars[op_start..].iter().collect();
let value = get(ctx, &name)?;
if op.is_empty() {
return Ok(value.unwrap_or_default());
}
let (colon, op) = match op.strip_prefix(':') {
Some(rest) if rest.starts_with(['-', '=', '+', '?']) => (true, rest.to_string()),
_ => (false, op),
};
let missing = match &value {
None => true,
Some(s) => colon && s.is_empty(),
};
match op.chars().next().unwrap() {
'-' => {
let word = &op[1..];
return if missing {
self.expand_depth(word, ctx, depth + 1)
} else {
Ok(value.unwrap())
};
}
'=' => {
let word = &op[1..];
return if missing {
if name.starts_with(|c: char| c.is_ascii_digit()) {
return Err(Error::AssignUnsupported { var: name });
}
let w = self.expand_depth(word, ctx, depth + 1)?;
match ctx.set(&name, &w) {
Ok(true) => Ok(w),
Ok(false) => Err(Error::AssignUnsupported { var: name }),
Err(e) => Err(Error::Context(e)),
}
} else {
Ok(value.unwrap())
};
}
'+' => {
let word = &op[1..];
return if missing {
Ok(String::new())
} else {
self.expand_depth(word, ctx, depth + 1)
};
}
'?' => {
let word = &op[1..];
return if missing {
Err(Error::Required {
var: name,
message: self.expand_depth(word, ctx, depth + 1)?,
})
} else {
Ok(value.unwrap())
};
}
_ => {}
}
let unset = value.is_none();
let val = value.unwrap_or_default();
if let Some(spec) = op.strip_prefix(':') {
return substring(&val, &self.expand_depth(spec, ctx, depth + 1)?);
}
if let Some(pat) = op.strip_prefix("##") {
let g = Glob::compile(&self.expand_depth(pat, ctx, depth + 1)?);
return Ok(strip_prefix_glob(&val, &g, true));
}
if let Some(pat) = op.strip_prefix('#') {
let g = Glob::compile(&self.expand_depth(pat, ctx, depth + 1)?);
return Ok(strip_prefix_glob(&val, &g, false));
}
if let Some(pat) = op.strip_prefix("%%") {
let g = Glob::compile(&self.expand_depth(pat, ctx, depth + 1)?);
return Ok(strip_suffix_glob(&val, &g, true));
}
if let Some(pat) = op.strip_prefix('%') {
let g = Glob::compile(&self.expand_depth(pat, ctx, depth + 1)?);
return Ok(strip_suffix_glob(&val, &g, false));
}
if let Some(spec) = op.strip_prefix('/') {
return self.replace(&val, spec, ctx, depth);
}
if op.starts_with('^') || op.starts_with(',') {
return Ok(case_modify(&val, &op));
}
if let Some(t) = op.strip_prefix('@') {
if unset {
return Ok(String::new());
}
return transform(&val, t).ok_or_else(|| Error::BadSubstitution(body.to_string()));
}
Err(Error::BadSubstitution(body.to_string()))
}
fn replace<C: Context>(
&self,
val: &str,
spec: &str,
ctx: &mut C,
depth: usize,
) -> Result<String, Error<C::Error>> {
enum Mode {
First,
Global,
Prefix,
Suffix,
}
let (mode, rest) = match spec.chars().next() {
Some('/') => (Mode::Global, &spec[1..]),
Some('#') => (Mode::Prefix, &spec[1..]),
Some('%') => (Mode::Suffix, &spec[1..]),
_ => (Mode::First, spec),
};
let mut pat = String::new();
let mut repl = String::new();
let mut in_repl = false;
let mut it = rest.chars().peekable();
while let Some(c) = it.next() {
if in_repl {
repl.push(c);
} else if c == '\\' && it.peek().is_some() {
pat.push('\\');
pat.push(it.next().unwrap());
} else if c == '/' {
in_repl = true;
} else {
pat.push(c);
}
}
let pat = Glob::compile(&self.expand_depth(&pat, ctx, depth + 1)?);
let repl = self.expand_depth(&repl, ctx, depth + 1)?;
let chars: Vec<char> = val.chars().collect();
match mode {
Mode::Prefix => Ok(match pat.longest_prefix(&chars) {
Some(l) => format!("{repl}{}", chars[l..].iter().collect::<String>()),
None => val.to_string(),
}),
Mode::Suffix => {
for start in 0..=chars.len() {
if pat.matches(&chars[start..]) {
return Ok(format!(
"{}{repl}",
chars[..start].iter().collect::<String>()
));
}
}
Ok(val.to_string())
}
Mode::First | Mode::Global => {
let global = matches!(mode, Mode::Global);
let mut out = String::new();
let mut i = 0;
let mut replaced = false;
while i < chars.len() {
let m = if replaced && !global {
None
} else {
pat.longest_prefix(&chars[i..]).filter(|&l| l > 0)
};
match m {
Some(l) => {
out.push_str(&repl);
i += l;
replaced = true;
}
None => {
out.push(chars[i]);
i += 1;
}
}
}
Ok(out)
}
}
}
}
fn get<C: Context>(ctx: &mut C, name: &str) -> Result<Option<String>, Error<C::Error>> {
match ctx.get(name) {
Ok(v) => Ok(v.map(Cow::into_owned)),
Err(e) => Err(Error::Context(e)),
}
}
fn read_braced<E>(chars: &[char], start: usize) -> Result<(String, usize), Error<E>> {
let mut depth = 1usize;
let mut i = start;
let mut buf = String::new();
while i < chars.len() {
match chars[i] {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
return Ok((buf, i + 1));
}
}
'\\' if i + 1 < chars.len() => {
buf.push('\\');
buf.push(chars[i + 1]);
i += 2;
continue;
}
_ => {}
}
buf.push(chars[i]);
i += 1;
}
Err(Error::BadSubstitution(chars[start..].iter().collect()))
}
fn read_name(chars: &[char], start: usize) -> Option<(String, usize)> {
let mut i = start;
let mut name = String::new();
while i < chars.len() && (chars[i] == '_' || chars[i].is_alphanumeric()) {
name.push(chars[i]);
i += 1;
}
if name.is_empty() {
None
} else {
Some((name, i))
}
}
fn is_name(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| c == '_' || c.is_alphanumeric())
}
fn substring<E>(val: &str, spec: &str) -> Result<String, Error<E>> {
let bad = || Error::BadSubstitution(format!("var:{spec}"));
let mut parts = spec.splitn(2, ':');
let off: i64 = parts.next().unwrap().trim().parse().map_err(|_| bad())?;
let len: Option<i64> = match parts.next() {
Some(l) => Some(l.trim().parse().map_err(|_| bad())?),
None => None,
};
let chars: Vec<char> = val.chars().collect();
let n = chars.len() as i64;
let start = if off < 0 {
if n + off < 0 {
return Ok(String::new());
}
n + off
} else {
off.min(n)
} as usize;
let end = match len {
None => n as usize,
Some(l) if l < 0 => (n + l).max(start as i64) as usize,
Some(l) => (start as i64 + l).min(n) as usize,
};
Ok(chars[start..end.max(start)].iter().collect())
}
fn strip_prefix_glob(val: &str, pat: &Glob, longest: bool) -> String {
let chars: Vec<char> = val.chars().collect();
let range: Box<dyn Iterator<Item = usize>> = if longest {
Box::new((0..=chars.len()).rev())
} else {
Box::new(0..=chars.len())
};
for l in range {
if pat.matches(&chars[..l]) {
return chars[l..].iter().collect();
}
}
val.to_string()
}
fn strip_suffix_glob(val: &str, pat: &Glob, longest: bool) -> String {
let chars: Vec<char> = val.chars().collect();
let n = chars.len();
let range: Box<dyn Iterator<Item = usize>> = if longest {
Box::new(0..=n)
} else {
Box::new((0..=n).rev())
};
for start in range {
if pat.matches(&chars[start..]) {
return chars[..start].iter().collect();
}
}
val.to_string()
}
fn case_modify(val: &str, op: &str) -> String {
let (upper, all) = match op {
_ if op.starts_with("^^") => (true, true),
_ if op.starts_with(",,") => (false, true),
_ if op.starts_with('^') => (true, false),
_ => (false, false),
};
let pat = &op[if all { 2 } else { 1 }..];
let glob = (!pat.is_empty()).then(|| Glob::compile(pat));
let convert = |c: char| -> String {
let hit = glob.as_ref().map_or(true, |g| g.matches(&[c]));
match (hit, upper) {
(false, _) => c.to_string(),
(true, true) => c.to_uppercase().to_string(),
(true, false) => c.to_lowercase().to_string(),
}
};
if all {
val.chars().map(convert).collect()
} else {
let mut it = val.chars();
match it.next() {
Some(f) => convert(f) + it.as_str(),
None => String::new(),
}
}
}
fn transform(val: &str, t: &str) -> Option<String> {
Some(match t {
"U" => val.to_uppercase(),
"L" => val.to_lowercase(),
"u" => {
let mut it = val.chars();
match it.next() {
Some(f) => f.to_uppercase().to_string() + it.as_str(),
None => String::new(),
}
}
"Q" => format!("'{}'", val.replace('\'', r"'\''")),
"E" => unescape(val),
_ => return None,
})
}
fn unescape(s: &str) -> String {
let mut out = String::new();
let mut it = s.chars();
while let Some(c) = it.next() {
if c != '\\' {
out.push(c);
continue;
}
match it.next() {
Some('n') => out.push('\n'),
Some('t') => out.push('\t'),
Some('r') => out.push('\r'),
Some('0') => out.push('\0'),
Some('\\') => out.push('\\'),
Some(o) => {
out.push('\\');
out.push(o);
}
None => out.push('\\'),
}
}
out
}
#[derive(Debug, Clone, PartialEq)]
enum Tok {
Star,
Any,
Lit(char),
Class {
negate: bool,
ranges: Vec<(char, char)>,
},
}
#[derive(Debug, Clone)]
struct Glob {
toks: Vec<Tok>,
}
impl Glob {
fn compile(pat: &str) -> Glob {
let chars: Vec<char> = pat.chars().collect();
let mut toks = Vec::new();
let mut i = 0;
while i < chars.len() {
match chars[i] {
'*' => {
if toks.last() != Some(&Tok::Star) {
toks.push(Tok::Star);
}
i += 1;
}
'?' => {
toks.push(Tok::Any);
i += 1;
}
'\\' if i + 1 < chars.len() => {
toks.push(Tok::Lit(chars[i + 1]));
i += 2;
}
'[' => match parse_class(&chars, i) {
Some((tok, next)) => {
toks.push(tok);
i = next;
}
None => {
toks.push(Tok::Lit('['));
i += 1;
}
},
c => {
toks.push(Tok::Lit(c));
i += 1;
}
}
}
Glob { toks }
}
fn tok_matches(tok: &Tok, c: char) -> bool {
match tok {
Tok::Star => false, Tok::Any => true,
Tok::Lit(l) => *l == c,
Tok::Class { negate, ranges } => {
ranges.iter().any(|&(a, b)| c >= a && c <= b) != *negate
}
}
}
fn matches(&self, text: &[char]) -> bool {
let (mut p, mut t) = (0usize, 0usize);
let (mut star, mut star_t) = (None::<usize>, 0usize);
loop {
if t < text.len() {
match self.toks.get(p) {
Some(Tok::Star) => {
star = Some(p);
star_t = t;
p += 1;
}
Some(tok) if Self::tok_matches(tok, text[t]) => {
p += 1;
t += 1;
}
_ => match star {
Some(sp) => {
p = sp + 1;
star_t += 1;
t = star_t;
}
None => return false,
},
}
} else {
while self.toks.get(p) == Some(&Tok::Star) {
p += 1;
}
return p == self.toks.len();
}
}
}
fn longest_prefix(&self, text: &[char]) -> Option<usize> {
(0..=text.len()).rev().find(|&l| self.matches(&text[..l]))
}
}
fn parse_class(chars: &[char], start: usize) -> Option<(Tok, usize)> {
let mut i = start + 1;
let negate = matches!(chars.get(i), Some('!') | Some('^'));
if negate {
i += 1;
}
let first = i;
let mut ranges = Vec::new();
while i < chars.len() {
let c = chars[i];
if c == ']' && i > first {
return Some((Tok::Class { negate, ranges }, i + 1));
}
if i + 2 < chars.len() && chars[i + 1] == '-' && chars[i + 2] != ']' {
ranges.push((c, chars[i + 2]));
i += 3;
} else {
ranges.push((c, c));
i += 1;
}
}
None }
#[cfg(test)]
mod tests {
use super::*;
fn v() -> HashMap<String, String> {
HashMap::from([
("x".to_string(), "abc".to_string()),
("file".to_string(), "dir/sub/name.tar.gz".to_string()),
("empty".to_string(), String::new()),
])
}
#[test]
fn basics() {
let mut m = v();
assert_eq!(expand("$x-${x}", &mut m).unwrap(), "abc-abc");
assert_eq!(expand("$", &mut m).unwrap(), "$");
assert_eq!(expand("$1", &mut m).unwrap(), "");
m.insert("1".to_string(), "one".to_string());
assert_eq!(expand("$1-${1}", &mut m).unwrap(), "one-one");
assert_eq!(expand("${1=x}-${1:-d}-${#1}", &mut m).unwrap(), "one-one-3");
assert!(matches!(
expand("${9:=x}", &mut m),
Err(Error::AssignUnsupported { .. })
));
assert!(!m.contains_key("9"));
assert_eq!(expand(r"\$x", &mut m).unwrap(), "$x");
assert_eq!(expand("no vars here", &mut m).unwrap(), "no vars here");
assert_eq!(expand("", &mut m).unwrap(), "");
}
#[test]
fn defaults() {
let mut m = v();
assert_eq!(expand("${nope-d}", &mut m).unwrap(), "d");
assert_eq!(expand("${empty-d}", &mut m).unwrap(), "");
assert_eq!(expand("${empty:-d}", &mut m).unwrap(), "d");
assert_eq!(expand("${nope:=set}", &mut m).unwrap(), "set");
assert_eq!(m["nope"], "set");
assert_eq!(expand("${x:+alt}", &mut m).unwrap(), "alt");
assert_eq!(expand("${empty:+alt}", &mut m).unwrap(), "");
assert!(matches!(
expand("${nada:?boom}", &mut m),
Err(Error::Required { .. })
));
assert_eq!(expand("${nope2:-${x}!}", &mut m).unwrap(), "abc!");
}
#[test]
fn length_indirection() {
let mut m = v();
m.insert("p".into(), "x".into());
assert_eq!(expand("${#file}", &mut m).unwrap(), "19");
assert_eq!(expand("${#nope}", &mut m).unwrap(), "0");
assert_eq!(expand("${!p}", &mut m).unwrap(), "abc");
}
#[test]
fn substrings() {
let mut m = v();
assert_eq!(expand("${file:0:3}", &mut m).unwrap(), "dir");
assert_eq!(expand("${file:4}", &mut m).unwrap(), "sub/name.tar.gz");
assert_eq!(expand("${file: -2}", &mut m).unwrap(), "gz");
assert_eq!(expand("${file:4:-7}", &mut m).unwrap(), "sub/name");
assert_eq!(expand("${file:100}", &mut m).unwrap(), "");
assert_eq!(expand("${file:0:0}", &mut m).unwrap(), "");
assert_eq!(expand("${x: -3}", &mut m).unwrap(), "abc");
assert_eq!(expand("${x: -4}", &mut m).unwrap(), "");
assert_eq!(expand("${x: -4:2}", &mut m).unwrap(), "");
}
#[test]
fn pattern_removal() {
let mut m = v();
assert_eq!(expand("${file#*/}", &mut m).unwrap(), "sub/name.tar.gz");
assert_eq!(expand("${file##*/}", &mut m).unwrap(), "name.tar.gz");
assert_eq!(expand("${file%.*}", &mut m).unwrap(), "dir/sub/name.tar");
assert_eq!(expand("${file%%.*}", &mut m).unwrap(), "dir/sub/name");
assert_eq!(
expand("${file#zzz}", &mut m).unwrap(),
"dir/sub/name.tar.gz"
);
}
#[test]
fn replacement() {
let mut m = v();
assert_eq!(
expand("${file/sub/S}", &mut m).unwrap(),
"dir/S/name.tar.gz"
);
assert_eq!(
expand("${file//\\//_}", &mut m).unwrap(),
"dir_sub_name.tar.gz"
);
assert_eq!(
expand("${file/#dir/R}", &mut m).unwrap(),
"R/sub/name.tar.gz"
);
assert_eq!(
expand("${file/%gz/xz}", &mut m).unwrap(),
"dir/sub/name.tar.xz"
);
assert_eq!(expand("${x/b}", &mut m).unwrap(), "ac");
}
#[test]
fn case_ops() {
let mut m = HashMap::from([
("g".to_string(), "hello world".to_string()),
("G".to_string(), "HELLO".to_string()),
]);
assert_eq!(expand("${g^}", &mut m).unwrap(), "Hello world");
assert_eq!(expand("${g^^}", &mut m).unwrap(), "HELLO WORLD");
assert_eq!(expand("${g^^[lo]}", &mut m).unwrap(), "heLLO wOrLd");
assert_eq!(expand("${G,,}", &mut m).unwrap(), "hello");
assert_eq!(expand("${G,}", &mut m).unwrap(), "hELLO");
}
#[test]
fn at_transforms() {
let mut m = HashMap::from([("g".to_string(), "Hello World".to_string())]);
assert_eq!(expand("${g@U}", &mut m).unwrap(), "HELLO WORLD");
assert_eq!(expand("${g@L}", &mut m).unwrap(), "hello world");
assert_eq!(expand("${g@u}", &mut m).unwrap(), "Hello World");
assert_eq!(expand("${g@Q}", &mut m).unwrap(), "'Hello World'");
assert!(matches!(
expand("${g@Z}", &mut m),
Err(Error::BadSubstitution(_))
));
assert_eq!(expand("${nope@Q}", &mut m).unwrap(), "");
assert_eq!(expand("${nope@U}", &mut m).unwrap(), "");
assert_eq!(expand("${nope@Z}", &mut m).unwrap(), "");
}
#[test]
fn quoting_is_safe() {
let mut m = HashMap::from([("s".to_string(), "it's a 'test'".to_string())]);
assert_eq!(
expand("${s@Q}", &mut m).unwrap(),
r#"'it'\''s a '\''test'\'''"#
);
}
#[test]
fn shared_ref_maps_read_only() {
let m = v();
assert_eq!(expand("${x}-${nope:-d}", &mut &m).unwrap(), "abc-d");
assert!(matches!(
expand("${nope:=d}", &mut &m),
Err(Error::AssignUnsupported { .. })
));
assert_eq!(m.len(), 3);
let b = BTreeMap::from([("k".to_string(), "v".to_string())]);
assert_eq!(expand("${k}", &mut &b).unwrap(), "v");
assert!(matches!(
expand("${z:=d}", &mut &b),
Err(Error::AssignUnsupported { .. })
));
}
#[test]
fn depth_limit() {
let mut s = String::from("x");
for _ in 0..(DEFAULT_MAX_DEPTH + 2) {
s = format!("${{a:-{s}}}");
}
let mut m: HashMap<String, String> = HashMap::new();
assert_eq!(expand(&s, &mut m), Err(Error::TooDeep));
}
#[test]
fn glob_no_blowup() {
let g = Glob::compile("a*a*a*a*a*a*a*a*a*a*b");
let text: Vec<char> = "a".repeat(200).chars().collect();
assert!(!g.matches(&text));
assert!(glob_ok("*.tar.gz", "name.tar.gz"));
assert!(glob_ok("a?c", "abc"));
assert!(glob_ok("[a-c]x", "bx"));
assert!(glob_ok("[!a-c]x", "dx"));
assert!(!glob_ok("[a-c]x", "dx"));
assert!(glob_ok(r"\*x", "*x"));
assert!(!glob_ok(r"\*x", "ax"));
assert!(glob_ok("", ""));
assert!(!glob_ok("", "a"));
assert!(glob_ok("*", ""));
}
fn glob_ok(p: &str, t: &str) -> bool {
Glob::compile(p).matches(&t.chars().collect::<Vec<_>>())
}
#[test]
fn bad_substitution() {
let mut m = v();
assert!(matches!(
expand("${x&}", &mut m),
Err(Error::BadSubstitution(_))
));
assert!(matches!(
expand("${unclosed", &mut m),
Err(Error::BadSubstitution(_))
));
assert!(matches!(
expand("${x:zz}", &mut m),
Err(Error::BadSubstitution(_))
));
}
#[test]
fn unicode() {
let mut m = HashMap::from([("s".to_string(), "héllo wörld".to_string())]);
assert_eq!(expand("${#s}", &mut m).unwrap(), "11");
assert_eq!(expand("${s:1:4}", &mut m).unwrap(), "éllo");
assert_eq!(expand("${s^^}", &mut m).unwrap(), "HÉLLO WÖRLD");
}
}