use std::ffi::{OsStr, OsString};
const RESPONSE_DEPTH: usize = 8;
pub fn expand_response_files(
args: &[OsString],
) -> std::result::Result<Vec<OsString>, String> {
let mut out = Vec::with_capacity(args.len());
for arg in args {
expand_one(arg, RESPONSE_DEPTH, &mut out)?;
}
Ok(out)
}
fn expand_one(
arg: &OsStr,
depth: usize,
out: &mut Vec<OsString>,
) -> std::result::Result<(), String> {
let Some(arg) = arg.to_str() else {
out.push(arg.to_os_string());
return Ok(());
};
let Some(path) = arg.strip_prefix('@') else {
out.push(OsString::from(arg));
return Ok(());
};
if depth == 0 {
return Err(format!(
"xold: response files nested more than {RESPONSE_DEPTH} deep at \
`{path}`: a file that names itself is the usual cause"
));
}
let text = std::fs::read_to_string(path).map_err(|err| {
format!("xold: cannot read response file `{path}`: {err}")
})?;
for word in split_response(&text) {
expand_one(OsStr::new(&word), depth - 1, out)?;
}
Ok(())
}
fn split_response(text: &str) -> Vec<String> {
let mut out = Vec::new();
let mut word = String::new();
let mut quote: Option<char> = None;
let mut escaped = false;
for ch in text.chars() {
if escaped {
word.push(ch);
escaped = false;
} else if ch == '\\' {
escaped = true;
} else if let Some(q) = quote {
if ch == q {
quote = None;
} else {
word.push(ch);
}
} else if ch == '\'' || ch == '"' {
quote = Some(ch);
} else if ch.is_whitespace() {
if !word.is_empty() {
out.push(std::mem::take(&mut word));
}
} else {
word.push(ch);
}
}
if !word.is_empty() {
out.push(word);
}
out
}