use std::collections::HashMap;
use super::value::UsdValue;
pub type Variables = HashMap<String, String>;
pub fn variables_of(metadata: &[(String, UsdValue)]) -> Variables {
let mut out = Variables::new();
for (key, value) in metadata {
if key
.split_once(' ')
.map(|(_, rest)| rest)
.unwrap_or(key)
!= "expressionVariables"
{
continue;
}
if let UsdValue::Dict(entries) = value {
for (name, value) in entries {
if let Some(text) = value.as_str() {
out.insert(name.clone(), text.to_string());
}
}
}
}
out
}
pub fn is_expression(text: &str) -> bool {
text.len() >= 2 && text.starts_with('`') && text.ends_with('`')
}
pub fn evaluate(text: &str, variables: &Variables) -> Option<String> {
if !is_expression(text) {
return Some(text.to_string());
}
let body = text[1..text.len() - 1].trim();
let inner = match (body.starts_with('"'), body.ends_with('"'), body.len() >= 2) {
(true, true, true) => &body[1..body.len() - 1],
_ => return None,
};
let mut out = String::with_capacity(inner.len());
let mut rest = inner;
while let Some(at) = rest.find("${") {
out.push_str(&rest[..at]);
let after = &rest[at + 2..];
let end = after.find('}')?;
let name = &after[..end];
out.push_str(variables.get(name)?);
rest = &after[end + 1..];
}
out.push_str(rest);
Some(out)
}
#[cfg(test)]
mod tests {
use super::*;
fn vars(pairs: &[(&str, &str)]) -> Variables {
pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect()
}
#[test]
fn a_plain_path_is_left_alone() {
let v = vars(&[]);
assert_eq!(evaluate("asset.usda", &v).as_deref(), Some("asset.usda"));
assert_eq!(evaluate("a`b.usda", &v).as_deref(), Some("a`b.usda"));
}
#[test]
fn a_variable_is_substituted() {
let v = vars(&[("COLOR", "red")]);
assert_eq!(
evaluate("`\"${COLOR}_asset.usda\"`", &v).as_deref(),
Some("red_asset.usda")
);
let v = vars(&[("SHOT", "010"), ("DEPT", "anim")]);
assert_eq!(
evaluate("`\"shots/${SHOT}/${DEPT}.usda\"`", &v).as_deref(),
Some("shots/010/anim.usda")
);
}
#[test]
fn an_undefined_variable_does_not_resolve() {
assert_eq!(evaluate("`\"${MISSING}.usda\"`", &vars(&[])), None);
}
#[test]
fn anything_beyond_substitution_is_declined() {
let v = vars(&[("A", "1")]);
assert_eq!(evaluate("`if(eq(${A}, 1), \"x.usda\", \"y.usda\")`", &v), None);
assert_eq!(evaluate("`${A}`", &v), None, "not a string literal");
}
#[test]
fn an_unterminated_substitution_does_not_resolve() {
let v = vars(&[("A", "1")]);
assert_eq!(evaluate("`\"${A\"`", &v), None);
}
#[test]
fn variables_are_read_from_the_layer() {
let layer = super::super::parse::parse(
r#"#usda 1.0
(
expressionVariables = {
string COLOR = "red"
string SHOT = "010"
}
)
"#,
)
.unwrap();
let v = variables_of(&layer.metadata);
assert_eq!(v.get("COLOR").map(String::as_str), Some("red"));
assert_eq!(v.get("SHOT").map(String::as_str), Some("010"));
}
}