use std::collections::{HashMap, HashSet};
use std::iter::once;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use heck::{
ToKebabCase, ToLowerCamelCase, ToShoutyKebabCase, ToShoutySnakeCase, ToSnakeCase,
ToUpperCamelCase,
};
use indexmap::IndexSet;
use path_absolutize::Absolutize;
use rand::prelude::*;
use regex::Regex;
use serde_json::{Map as JsonMap, Value as JsonValue, json};
use std::sync::LazyLock as Lazy;
use tera::{Context, Kwargs, State, Tera, TeraResult, Value};
use versions::{Requirement, Versioning};
use crate::cache::CacheManagerBuilder;
use crate::cmd::cmd;
use crate::env_diff::EnvMap;
use crate::file::strip_shims_from_path;
use crate::{dirs, duration, env, hash};
use mise_settings::Settings;
static TERA_ACCESSED_FILES: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
fn track_tera_file(path: &Path) {
if let Ok(mut files) = TERA_ACCESSED_FILES.lock() {
files.push(path.to_path_buf());
}
}
pub fn take_tera_accessed_files() -> Vec<PathBuf> {
let mut files = TERA_ACCESSED_FILES
.lock()
.map(|mut f| std::mem::take(&mut *f))
.unwrap_or_default();
files.sort();
files.dedup();
files
}
pub fn contains_template_syntax(input: &str) -> bool {
input.contains("{{") || input.contains("{%") || input.contains("{#")
}
pub enum TeraEngine {
V2(Box<Tera>),
V1(Box<tera1::Tera>),
}
impl TeraEngine {
fn render_str(&mut self, input: &str, context: &Context) -> TeraResult<String> {
match self {
Self::V2(tera) => tera
.render_str(input, context, false)
.map_err(|err| hide_env_names(err, context)),
Self::V1(tera) => {
let context = tera1_context(input, context)?;
tera.render_str(input, &context)
.map_err(|e| tera::Error::chain(e.to_string(), e))
}
}
}
pub fn validate_template_syntax(&mut self, name: &str, input: &str) -> TeraResult<()> {
match self {
Self::V2(tera) => tera.add_raw_template(name, input),
Self::V1(tera) => tera
.add_raw_template(name, input)
.map_err(|err| tera_err(err.to_string())),
}
}
}
pub fn render_str(tera: &mut TeraEngine, input: &str, context: &Context) -> TeraResult<String> {
tera.render_str(input, &safe_context(context))
}
pub fn render_str_with_env(
tera: &mut TeraEngine,
input: &str,
context: &Context,
) -> TeraResult<String> {
tera.render_str(input, context)
}
pub fn render_str_v2(tera: &mut Tera, input: &str, context: &Context) -> TeraResult<String> {
let context = safe_context(context);
tera.render_str(input, &context, false)
.map_err(|err| hide_env_names(err, &context))
}
fn hide_env_names(err: tera::Error, context: &Context) -> tera::Error {
const MARKER: &str = " Available fields: ";
let tera::ErrorKind::RenderingError(report) = err.kind() else {
return err;
};
let Some((head, listed)) = report.message().split_once(MARKER) else {
return err;
};
let Some(field) = head
.strip_prefix("Field `")
.and_then(|rest| rest.strip_suffix("` is not defined."))
else {
return err;
};
let Some(env) = context.get("env").and_then(|env| env.as_map()) else {
return err;
};
let mut names: Vec<String> = env.keys().map(|name| name.to_string()).collect();
names.sort();
names.dedup();
if names.join(", ") != listed {
return err;
}
let hint = format!(
"Field `{field}` is not defined in `env`. For an optional variable use \
`get_env(name=\"{field}\", default=\"\")` or `env.{field} | default(value=\"\")`."
);
let rendered = err.to_string();
if rendered.contains(report.message()) {
return tera_err(rendered.replace(report.message(), &hint));
}
let span = report.span();
tera_err(format!(
"{hint}\n --> {}:{}:{}",
report.filename(),
span.start_line,
span.start_col + 1,
))
}
fn safe_mode() -> bool {
match mise_settings::last_cached() {
Some(settings) => settings.safe,
None => env::var_is_true("MISE_SAFE"),
}
}
tokio::task_local! {
static TRUSTED_TEMPLATES: bool;
}
pub async fn with_trusted_templates<T>(future: impl std::future::Future<Output = T>) -> T {
TRUSTED_TEMPLATES.scope(true, future).await
}
pub async fn with_templates_trusted<T>(
trusted: bool,
future: impl std::future::Future<Output = T>,
) -> T {
TRUSTED_TEMPLATES.scope(trusted, future).await
}
pub fn in_trusted_templates() -> bool {
TRUSTED_TEMPLATES
.try_with(|trusted| *trusted)
.unwrap_or(false)
}
fn safe_context(context: &Context) -> std::borrow::Cow<'_, Context> {
if !context.contains_key("env") || !safe_mode() || in_trusted_templates() {
return std::borrow::Cow::Borrowed(context);
}
let mut context = context.clone();
context.insert("env", &EnvMap::new());
std::borrow::Cow::Owned(context)
}
fn tera_err(message: impl ToString) -> tera::Error {
tera::Error::message(message)
}
fn posix_shell_quote(value: &str) -> String {
format!("'{}'", value.replace('\'', "'\\''"))
}
fn use_tera_v1() -> bool {
Settings::try_get().is_ok_and(|settings| settings.tera_v1)
}
fn tera1_err(message: impl ToString) -> tera1::Error {
tera1::Error::msg(message.to_string())
}
fn json_arg<'a>(args: &'a HashMap<String, JsonValue>, name: &str) -> tera1::Result<&'a JsonValue> {
args.get(name)
.ok_or_else(|| tera1_err(format!("missing required argument: {name}")))
}
fn json_str_arg<'a>(args: &'a HashMap<String, JsonValue>, name: &str) -> tera1::Result<&'a str> {
json_arg(args, name)?
.as_str()
.ok_or_else(|| tera1_err(format!("argument `{name}` must be a string")))
}
fn json_path(value: &JsonValue) -> tera1::Result<&str> {
value
.as_str()
.ok_or_else(|| tera1_err("filter input must be a string"))
}
fn insert_tera1_context_value(
data: &mut JsonMap<String, JsonValue>,
context: &Context,
key: &str,
) -> TeraResult<()> {
if data.contains_key(key) {
return Ok(());
}
if let Some(value) = context.get(key) {
data.insert(
key.to_string(),
serde_json::to_value(value).map_err(|e| tera_err(e.to_string()))?,
);
}
Ok(())
}
fn tera1_context(input: &str, context: &Context) -> TeraResult<tera1::Context> {
static IDENT_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"[A-Za-z_][A-Za-z0-9_]*").expect("valid ident regex"));
static RESERVED: Lazy<HashSet<&'static str>> = Lazy::new(|| {
HashSet::from([
"and",
"as",
"block",
"break",
"continue",
"elif",
"else",
"endblock",
"endfilter",
"endif",
"endfor",
"endmacro",
"endraw",
"endset",
"extends",
"false",
"filter",
"for",
"if",
"import",
"in",
"include",
"is",
"macro",
"not",
"or",
"raw",
"set",
"set_global",
"true",
])
});
let mut data = JsonMap::new();
for key in ["env", "vars", "tools"] {
insert_tera1_context_value(&mut data, context, key)?;
}
for m in IDENT_RE.find_iter(input) {
let key = m.as_str();
if RESERVED.contains(key) || data.contains_key(key) {
continue;
}
insert_tera1_context_value(&mut data, context, key)?;
}
tera1::Context::from_value(JsonValue::Object(data)).map_err(|e| tera_err(e.to_string()))
}
thread_local! {
static TEMPLATE_SOURCE: std::cell::RefCell<Option<PathBuf>> =
const { std::cell::RefCell::new(None) };
}
pub struct TemplateSourceGuard(Option<PathBuf>);
impl Drop for TemplateSourceGuard {
fn drop(&mut self) {
TEMPLATE_SOURCE.with(|source| *source.borrow_mut() = self.0.take());
}
}
pub fn template_source(path: &Path) -> TemplateSourceGuard {
TemplateSourceGuard(TEMPLATE_SOURCE.with(|source| source.replace(Some(path.to_path_buf()))))
}
fn template_source_suffix() -> String {
TEMPLATE_SOURCE.with(|source| match &*source.borrow() {
Some(path) => format!(" (in {})", crate::file::display_path(path)),
None => String::new(),
})
}
fn warn_tera_v1_filter(id: &'static str, name: &str, replacement: &str) {
let source = template_source_suffix();
deprecated_at!(
"2026.10.0",
"2027.4.0",
id,
"Tera v1 template helper `{name}` is deprecated in mise templates{source}. {replacement}"
);
}
fn tera_v1_slice_index(index: i64, len: usize) -> usize {
if index < 0 {
len.saturating_sub(index.unsigned_abs() as usize)
} else {
(index as usize).min(len)
}
}
fn escape_html(s: &str) -> String {
let mut output = String::with_capacity(s.len() * 2);
for c in s.chars() {
match c {
'&' => output.push_str("&"),
'<' => output.push_str("<"),
'>' => output.push_str(">"),
'"' => output.push_str("""),
'\'' => output.push_str("'"),
_ => output.push(c),
}
}
output
}
fn tera_v1_truthy(value: &Value) -> bool {
if value.is_none() {
false
} else if let Some(b) = value.as_bool() {
b
} else if let Some(s) = value.as_str() {
!s.is_empty()
} else if let Some(arr) = value.as_array() {
!arr.is_empty()
} else if let Some(map) = value.as_map() {
!map.is_empty()
} else if let Some(n) = value.as_number() {
n.as_integer().is_some_and(|n| n != 0) || value.as_f64().is_some_and(|n| n != 0.0)
} else {
true
}
}
fn tera_v1_int(value: Value, args: Kwargs) -> TeraResult<Value> {
let default = args.get::<i64>("default")?;
let base = args.get::<u32>("base")?.unwrap_or(10);
if !(2..=36).contains(&base) {
return Err(tera_err(format!(
"int filter `base` must be between 2 and 36, got {base}"
)));
}
let fallback = || {
warn_tera_v1_filter(
"tera-v1-int-default",
"int(default=...)",
"Invalid integer conversions should be handled explicitly.",
);
Ok(Value::from(default.unwrap_or_default()))
};
if let Some(s) = value.as_str() {
let s = s.trim();
let s = match base {
2 => s.trim_start_matches("0b"),
8 => s.trim_start_matches("0o"),
16 => s.trim_start_matches("0x"),
_ => s,
};
match i128::from_str_radix(s, base) {
Ok(v) => Ok(Value::from(v)),
Err(_) if s.contains('.') => match s.parse::<f64>() {
Ok(f) => Ok(Value::from(f as i128)),
Err(_) => fallback(),
},
Err(_) => fallback(),
}
} else {
value
.as_number()
.and_then(|n| n.as_integer())
.map(Value::from)
.ok_or_else(|| tera_err("Filter `int` received an unexpected type"))
}
}
fn tera_v1_float(value: Value, args: Kwargs) -> TeraResult<Value> {
let default = args.get::<f64>("default")?;
if let Some(s) = value.as_str() {
match s.trim().parse::<f64>() {
Ok(f) => Ok(Value::from(f)),
Err(_) => {
warn_tera_v1_filter(
"tera-v1-float-default",
"float(default=...)",
"Invalid float conversions should be handled explicitly.",
);
Ok(Value::from(default.unwrap_or_default()))
}
}
} else {
value
.as_f64()
.map(Value::from)
.ok_or_else(|| tera_err("Filter `float` received an unexpected type"))
}
}
pub static BASE_CONTEXT: Lazy<Context> = Lazy::new(|| {
let mut context = Context::new();
context.insert("env", &*env::PRISTINE_ENV);
context.insert("mise_bin", &env::MISE_BIN.to_string_lossy());
context.insert("mise_pid", &*env::MISE_PID);
let mise_env = env::mise_env();
if !mise_env.is_empty() {
context.insert("mise_env", mise_env);
}
if let Ok(dir) = env::current_dir() {
context.insert("cwd", &dir.to_string_lossy());
}
context.insert("xdg_cache_home", &env::XDG_CACHE_HOME.to_string_lossy());
context.insert("xdg_config_home", &env::XDG_CONFIG_HOME.to_string_lossy());
context.insert("xdg_data_home", &env::XDG_DATA_HOME.to_string_lossy());
context.insert("xdg_state_home", &env::XDG_STATE_HOME.to_string_lossy());
context.insert("mise_config_dir", &env::MISE_CONFIG_DIR.to_string_lossy());
context.insert("system_brew_prefix", &env::system_brew_prefix());
context
});
static TERA: Lazy<Tera> = Lazy::new(|| {
let mut tera = Tera::default();
tera.register_function("get_env", tera_get_env(env::PRISTINE_ENV.clone()));
tera.register_function(
"arch",
move |args: Kwargs, _: &State| -> TeraResult<Value> {
let arch = if cfg!(target_arch = "x86_64") {
"x64"
} else if cfg!(target_arch = "aarch64") {
"arm64"
} else {
env::consts::ARCH
};
if let Some(remapped) = args.get::<&str>(arch)? {
return Ok(Value::from(remapped));
}
Ok(Value::from(arch))
},
);
tera.register_function(
"num_cpus",
move |_: Kwargs, _: &State| -> TeraResult<Value> {
let num = num_cpus::get();
Ok(Value::from(num.to_string()))
},
);
tera.register_function("os", move |args: Kwargs, _: &State| -> TeraResult<Value> {
let os = env::consts::OS;
if let Some(remapped) = args.get::<&str>(os)? {
return Ok(Value::from(remapped));
}
Ok(Value::from(os))
});
tera.register_function(
"os_family",
move |_: Kwargs, _: &State| -> TeraResult<Value> { Ok(Value::from(env::consts::FAMILY)) },
);
tera.register_function("libc", tera2_variant_fn(host_libc_name));
tera.register_function("avx2", tera2_variant_fn(host_avx2_name));
tera.register_function(
"choice",
move |args: Kwargs, _: &State| -> TeraResult<Value> {
let n = args.must_get::<u64>("n")?;
let alphabet = args.must_get::<&str>("alphabet")?;
let alphabet = alphabet.chars().collect::<Vec<char>>();
if alphabet.is_empty() {
return Err(tera_err("choice alphabet must not be empty"));
}
let mut rng = rand::rng();
let result: String = (0..n)
.map(|_| *alphabet.choose(&mut rng).expect("alphabet non-empty"))
.collect();
Ok(Value::from(result))
},
);
tera.register_function(
"haiku",
move |args: Kwargs, _: &State| -> TeraResult<Value> {
let words = args.get::<u64>("words")?.unwrap_or(2).max(1) as usize;
let separator = args.get::<&str>("separator")?.unwrap_or("-");
let digits = args.get::<u64>("digits")?.unwrap_or(2) as usize;
let result = xx::rand::haiku(&xx::rand::HaikuOptions {
words,
separator,
digits,
});
Ok(Value::from(result))
},
);
tera.register_filter(
"hash_file",
move |s: &str, args: Kwargs, _: &State| -> TeraResult<Value> {
let path = Path::new(s);
track_tera_file(path);
let mut hash =
hash::file_hash_blake3(path, None).map_err(|e| tera_err(e.to_string()))?;
if let Some(len) = args.get::<u64>("len")? {
hash = hash.chars().take(len as usize).collect();
}
Ok(Value::from(hash))
},
);
tera.register_filter(
"hash",
move |s: &str, args: Kwargs, _: &State| -> TeraResult<Value> {
let algorithm = args.get::<&str>("algorithm")?.unwrap_or("sha256");
let mut hash = match algorithm {
"sha256" => hash::hash_sha256_to_str(s),
"blake3" => hash::hash_blake3_to_str(s),
_ => return Err(tera_err(format!("unknown hash algorithm: {algorithm}"))),
};
if let Some(len) = args.get::<u64>("len")? {
hash = hash.chars().take(len as usize).collect();
}
Ok(Value::from(hash))
},
);
tera.register_filter(
"absolute",
move |s: &str, _: Kwargs, _: &State| -> TeraResult<Value> {
let p = Path::new(s).absolutize()?;
Ok(Value::from(p.to_string_lossy().to_string()))
},
);
tera.register_filter(
"canonicalize",
move |s: &str, _: Kwargs, _: &State| -> TeraResult<Value> {
let p = Path::new(s).canonicalize()?;
Ok(Value::from(p.to_string_lossy().to_string()))
},
);
fn path_filter<F>(input: &str, _name: &'static str, f: F) -> TeraResult<Value>
where
F: FnOnce(&Path) -> Option<String>,
{
if input.is_empty() {
Ok(Value::from(String::new()))
} else {
Ok(Value::from(f(Path::new(input)).unwrap_or_default()))
}
}
tera.register_filter("dirname", move |input: &str, _: Kwargs, _: &State| {
path_filter(input, "dirname", |p| {
p.parent().map(|p| p.to_string_lossy().to_string())
})
});
tera.register_filter("basename", move |input: &str, _: Kwargs, _: &State| {
path_filter(input, "basename", |p| {
p.file_name().map(|p| p.to_string_lossy().to_string())
})
});
tera.register_filter("extname", move |input: &str, _: Kwargs, _: &State| {
path_filter(input, "extname", |p| {
p.extension().map(|p| p.to_string_lossy().to_string())
})
});
tera.register_filter("file_stem", move |input: &str, _: Kwargs, _: &State| {
path_filter(input, "file_stem", |p| {
p.file_stem().map(|p| p.to_string_lossy().to_string())
})
});
tera.register_filter(
"file_size",
move |s: &str, _: Kwargs, _: &State| -> TeraResult<Value> {
let p = Path::new(s);
track_tera_file(p);
let metadata = p.metadata()?;
let size = metadata.len();
Ok(Value::from(size))
},
);
tera.register_filter(
"last_modified",
move |s: &str, _: Kwargs, _: &State| -> TeraResult<Value> {
let p = Path::new(s);
track_tera_file(p);
let metadata = p.metadata()?;
let modified = metadata.modified()?;
let modified = modified
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| tera_err(e.to_string()))?;
Ok(Value::from(modified.as_secs()))
},
);
tera.register_filter(
"join_path",
move |arr: &[Value], _: Kwargs, _: &State| -> TeraResult<Value> {
arr.iter()
.map(Value::as_str)
.collect::<Option<PathBuf>>()
.ok_or_else(|| tera_err("join_path input must be an array of strings"))
.map(|p| Value::from(p.to_string_lossy().to_string()))
},
);
tera.register_filter(
"quote",
move |s: &str, _: Kwargs, _: &State| -> TeraResult<Value> {
Ok(Value::from(posix_shell_quote(s)))
},
);
tera.register_filter("as_str", move |value: Value, _: Kwargs, _: &State| {
warn_tera_v1_filter("tera-v1-as-str", "as_str", "Use `str` instead.");
value.to_string()
});
tera.register_filter("escape", move |s: &str, _: Kwargs, _: &State| {
warn_tera_v1_filter("tera-v1-escape", "escape", "Use `escape_html` instead.");
Value::from(escape_html(s))
});
tera.register_filter("linebreaksbr", move |s: &str, _: Kwargs, _: &State| {
warn_tera_v1_filter(
"tera-v1-linebreaksbr",
"linebreaksbr",
"Use `newlines_to_br` instead.",
);
Value::from(s.replace("\r\n", "<br>").replace(['\n', '\r'], "<br>"))
});
tera.register_filter("addslashes", move |s: &str, _: Kwargs, _: &State| {
warn_tera_v1_filter(
"tera-v1-addslashes",
"addslashes",
"Use an explicit string replacement instead.",
);
Value::from(
s.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('\'', "\\'"),
)
});
tera.register_filter(
"truncate",
move |s: &str, args: Kwargs, _: &State| -> TeraResult<Value> {
let length = match args.get::<usize>("length")? {
Some(length) => length,
None => {
warn_tera_v1_filter(
"tera-v1-truncate-default-length",
"truncate without length",
"Pass `length=...` explicitly.",
);
255
}
};
let end = args.get::<&str>("end")?.unwrap_or("…");
match s.char_indices().nth(length) {
Some((byte_idx, _)) => Ok(Value::from(s[..byte_idx].to_string() + end)),
None => Ok(Value::from(s)),
}
},
);
tera.register_filter(
"indent",
move |s: &str, args: Kwargs, _: &State| -> TeraResult<Value> {
let prefix = match args.get::<&str>("prefix")? {
Some(prefix) => {
warn_tera_v1_filter(
"tera-v1-indent-prefix",
"indent(prefix=...)",
"Use `indent(width=...)` instead.",
);
prefix.to_string()
}
None => " ".repeat(args.get::<usize>("width")?.unwrap_or(4).min(1000)),
};
let first = args.get::<bool>("first")?.unwrap_or(false);
let blank = args.get::<bool>("blank")?.unwrap_or(false);
let mut out = String::with_capacity(s.len() + prefix.len() * 2);
let mut first_line = true;
for line in s.lines() {
if first_line {
if first {
out.push_str(&prefix);
}
first_line = false;
} else {
out.push('\n');
if blank || !line.is_empty() {
out.push_str(&prefix);
}
}
out.push_str(line);
}
if s.ends_with('\n') {
out.push('\n');
}
Ok(Value::from(out))
},
);
tera.register_filter(
"int",
move |value: Value, args: Kwargs, _: &State| -> TeraResult<Value> {
tera_v1_int(value, args)
},
);
tera.register_filter(
"float",
move |value: Value, args: Kwargs, _: &State| -> TeraResult<Value> {
tera_v1_float(value, args)
},
);
tera.register_filter("first", move |value: Value, _: Kwargs, _: &State| {
if let Some(arr) = value.as_array() {
if arr.is_empty() {
warn_tera_v1_filter(
"tera-v1-first-empty-string",
"first on an empty array",
"Tera 2 returns null for empty arrays.",
);
Value::from("")
} else {
arr[0].clone()
}
} else if let Some(s) = value.as_str() {
Value::from(s.chars().next().map(String::from).unwrap_or_default())
} else {
Value::from("")
}
});
tera.register_filter("last", move |value: Value, _: Kwargs, _: &State| {
if let Some(arr) = value.as_array() {
if arr.is_empty() {
warn_tera_v1_filter(
"tera-v1-last-empty-string",
"last on an empty array",
"Tera 2 returns null for empty arrays.",
);
Value::from("")
} else {
arr[arr.len() - 1].clone()
}
} else if let Some(s) = value.as_str() {
Value::from(s.chars().next_back().map(String::from).unwrap_or_default())
} else {
Value::from("")
}
});
tera.register_filter(
"nth",
move |arr: &[Value], args: Kwargs, _: &State| -> TeraResult<Value> {
let n = args.must_get::<usize>("n")?;
if let Some(value) = arr.get(n) {
Ok(value.clone())
} else {
warn_tera_v1_filter(
"tera-v1-nth-empty-string",
"nth outside array bounds",
"Tera 2 returns null for missing array elements.",
);
Ok(Value::from(""))
}
},
);
tera.register_filter(
"unique",
move |arr: &[Value], args: Kwargs, _: &State| -> TeraResult<Value> {
let case_sensitive = args.get::<bool>("case_sensitive")?.unwrap_or(false);
if args.get::<bool>("case_sensitive")?.is_some() {
warn_tera_v1_filter(
"tera-v1-unique-case-sensitive",
"unique(case_sensitive=...)",
"Tera 2 `unique` no longer accepts arguments.",
);
}
let mut out = Vec::new();
for value in arr {
let duplicate = out.iter().any(|existing: &Value| {
if case_sensitive {
existing == value
} else {
existing.to_string().to_lowercase() == value.to_string().to_lowercase()
}
});
if !duplicate {
out.push(value.clone());
}
}
Ok(Value::from(out))
},
);
tera.register_filter(
"trim_start_matches",
move |s: &str, args: Kwargs, _: &State| -> TeraResult<Value> {
warn_tera_v1_filter(
"tera-v1-trim-start-matches",
"trim_start_matches",
"Use `trim_start(pat=...)` instead.",
);
let pat = args.must_get::<&str>("pat")?;
Ok(Value::from(s.trim_start_matches(pat)))
},
);
tera.register_filter(
"trim_end_matches",
move |s: &str, args: Kwargs, _: &State| -> TeraResult<Value> {
warn_tera_v1_filter(
"tera-v1-trim-end-matches",
"trim_end_matches",
"Use `trim_end(pat=...)` instead.",
);
let pat = args.must_get::<&str>("pat")?;
Ok(Value::from(s.trim_end_matches(pat)))
},
);
tera.register_filter(
"slice",
move |arr: &[Value], args: Kwargs, _: &State| -> TeraResult<Value> {
warn_tera_v1_filter(
"tera-v1-slice",
"slice",
"Use Tera 2 slice syntax like `array[start:end]` instead.",
);
let len = arr.len();
let start = args
.get::<i64>("start")?
.map(|start| tera_v1_slice_index(start, len))
.unwrap_or_default();
let end = args
.get::<i64>("end")?
.map(|end| tera_v1_slice_index(end, len))
.unwrap_or(len);
if start >= end {
Ok(Value::from(Vec::<Value>::new()))
} else {
Ok(Value::from(arr[start..end].to_vec()))
}
},
);
tera.register_filter(
"concat",
move |arr: &[Value], args: Kwargs, _: &State| -> TeraResult<Value> {
warn_tera_v1_filter(
"tera-v1-concat",
"concat",
"Use Tera 2 spread syntax instead.",
);
let mut out = arr.to_vec();
let value = args.must_get::<Value>("with")?;
if let Some(values) = value.as_array() {
out.extend_from_slice(values);
} else {
out.push(value);
}
Ok(Value::from(out))
},
);
tera.register_filter(
"map",
move |arr: &[Value], args: Kwargs, _: &State| -> TeraResult<Value> {
warn_tera_v1_filter(
"tera-v1-map",
"map",
"Use Tera 2 list comprehension instead.",
);
let attribute = args.must_get::<&str>("attribute")?;
Ok(Value::from(
arr.iter()
.filter_map(|v| v.get_from_path(attribute))
.filter(|v| !v.is_none())
.cloned()
.collect::<Vec<_>>(),
))
},
);
tera.register_filter(
"filter",
move |arr: &[Value], args: Kwargs, _: &State| -> TeraResult<Value> {
warn_tera_v1_filter(
"tera-v1-filter",
"filter",
"Use Tera 2 list comprehension instead.",
);
let attribute = args.must_get::<&str>("attribute")?;
let expected = args.get::<Value>("value")?;
Ok(Value::from(
arr.iter()
.filter(|v| {
let Some(actual) = v.get_from_path(attribute) else {
return false;
};
match &expected {
Some(expected) => actual == expected,
None => tera_v1_truthy(actual),
}
})
.cloned()
.collect::<Vec<_>>(),
))
},
);
tera.register_filter("kebabcase", move |s: &str, _: Kwargs, _: &State| {
Value::from(s.to_kebab_case())
});
tera.register_filter("lowercamelcase", move |s: &str, _: Kwargs, _: &State| {
Value::from(s.to_lower_camel_case())
});
tera.register_filter("shoutykebabcase", move |s: &str, _: Kwargs, _: &State| {
Value::from(s.to_shouty_kebab_case())
});
tera.register_filter("shoutysnakecase", move |s: &str, _: Kwargs, _: &State| {
Value::from(s.to_shouty_snake_case())
});
tera.register_filter("snakecase", move |s: &str, _: Kwargs, _: &State| {
Value::from(s.to_snake_case())
});
tera.register_filter("uppercamelcase", move |s: &str, _: Kwargs, _: &State| {
Value::from(s.to_upper_camel_case())
});
tera.register_test("dir", move |s: &str, _: Kwargs, _: &State| {
Path::new(s).is_dir()
});
tera.register_test("file", move |s: &str, _: Kwargs, _: &State| {
Path::new(s).is_file()
});
tera.register_test("exists", move |s: &str, _: Kwargs, _: &State| {
Path::new(s).exists()
});
tera.register_test("object", move |value: &Value, _: Kwargs, _: &State| {
warn_tera_v1_filter("tera-v1-object-test", "object test", "Use `map` instead.");
value.is_map()
});
tera.register_test(
"divisibleby",
move |value: Value, args: Kwargs, _: &State| -> TeraResult<bool> {
warn_tera_v1_filter(
"tera-v1-divisibleby-test",
"divisibleby test",
"Use `divisible_by` instead.",
);
let divisor = args.must_get::<i128>("divisor")?;
if divisor == 0 {
return Ok(false);
}
let value = value
.as_number()
.and_then(|n| n.as_integer())
.ok_or_else(|| tera_err("divisibleby test expects an integer"))?;
Ok(value.checked_rem_euclid(divisor).is_some_and(|r| r == 0))
},
);
tera.register_test(
"semver_matching",
move |version: &str, args: Kwargs, _: &State| -> TeraResult<bool> {
let requirement = args.must_get::<&str>("requirement")?;
let requirement = Requirement::new(requirement).ok_or_else(|| {
tera_err(format!(
"semver_matching requirement is invalid: {requirement}"
))
})?;
let version = Versioning::new(version).ok_or_else(|| {
tera_err(format!("semver_matching version is invalid: {version}"))
})?;
let result = requirement.matches(&version);
Ok(result)
},
);
tera.register_filter("b64_encode", tera_contrib::base64::b64_encode);
tera.register_filter("b64_decode", tera_contrib::base64::b64_decode);
tera.register_function("now", tera_contrib::dates::now);
tera.register_filter("date", tera_contrib::dates::date);
tera.register_test("before", tera_contrib::dates::is_before);
tera.register_test("after", tera_contrib::dates::is_after);
tera.register_filter(
"filesize_format",
tera_contrib::filesize_format::filesize_format,
);
tera.register_filter(
"filesizeformat",
tera_contrib::filesize_format::filesize_format,
);
tera.register_filter("format", tera_contrib::format::format);
tera.register_filter("json_encode", tera_contrib::json::json_encode);
tera.register_function("get_random", tera_contrib::rand::get_random);
tera.register_filter("shuffle", tera_contrib::rand::shuffle);
tera.register_filter("striptags", tera_contrib::regex::striptags);
tera.register_filter("spaceless", tera_contrib::regex::spaceless);
tera.register_filter(
"regex_replace",
tera_contrib::regex::RegexReplace::default(),
);
tera.register_test("matching", tera_contrib::regex::Matching::default());
tera.register_filter("slug", tera_contrib::slug::slug);
tera.register_filter("slugify", tera_contrib::slug::slug);
tera.register_filter("urlencode", tera_contrib::urlencode::urlencode);
tera.register_filter(
"urlencode_strict",
tera_contrib::urlencode::urlencode_strict,
);
tera
});
fn tera_get_env(env: EnvMap) -> impl Fn(Kwargs, &State) -> TeraResult<Value> {
move |args: Kwargs, _: &State| -> TeraResult<Value> {
let name = args.must_get::<&str>("name")?;
if let Some(value) = env.get(name) {
return Ok(Value::from(value.clone()));
}
if let Some(default) = args.get::<&str>("default")? {
return Ok(Value::from(default));
}
Err(tera_err(format!("Environment variable `{name}` not found")))
}
}
static TERA1: Lazy<tera1::Tera> = Lazy::new(|| {
let mut tera = tera1::Tera::default();
tera.register_function("get_env", tera1_get_env(env::PRISTINE_ENV.clone()));
tera.register_function("arch", tera1_host_fn(host_arch_name));
tera.register_function("os", tera1_host_fn(|| env::consts::OS));
tera.register_function("libc", tera1_variant_fn(host_libc_name));
tera.register_function("avx2", tera1_variant_fn(host_avx2_name));
tera.register_function("os_family", move |_: &HashMap<String, JsonValue>| {
Ok(json!(env::consts::FAMILY))
});
tera.register_function("num_cpus", move |_: &HashMap<String, JsonValue>| {
Ok(json!(num_cpus::get().to_string()))
});
tera.register_function("choice", move |args: &HashMap<String, JsonValue>| {
let n = json_arg(args, "n")?
.as_u64()
.ok_or_else(|| tera1_err("choice n must be an integer"))?;
let alphabet = json_str_arg(args, "alphabet")?
.chars()
.collect::<Vec<char>>();
if alphabet.is_empty() {
return Err(tera1_err("choice alphabet must not be empty"));
}
let mut rng = rand::rng();
let result: String = (0..n)
.map(|_| *alphabet.choose(&mut rng).expect("alphabet non-empty"))
.collect();
Ok(json!(result))
});
tera.register_function("haiku", move |args: &HashMap<String, JsonValue>| {
let words = args
.get("words")
.and_then(JsonValue::as_u64)
.unwrap_or(2)
.max(1) as usize;
let separator = args
.get("separator")
.and_then(JsonValue::as_str)
.unwrap_or("-");
let digits = args.get("digits").and_then(JsonValue::as_u64).unwrap_or(2) as usize;
Ok(json!(xx::rand::haiku(&xx::rand::HaikuOptions {
words,
separator,
digits,
})))
});
tera.register_filter(
"hash_file",
move |value: &JsonValue, args: &HashMap<String, JsonValue>| {
let path = Path::new(json_path(value)?);
track_tera_file(path);
let mut hash =
hash::file_hash_blake3(path, None).map_err(|e| tera1_err(e.to_string()))?;
if let Some(len) = args.get("len").and_then(JsonValue::as_u64) {
hash = hash.chars().take(len as usize).collect();
}
Ok(json!(hash))
},
);
tera.register_filter(
"hash",
move |value: &JsonValue, args: &HashMap<String, JsonValue>| {
let s = json_path(value)?;
let algorithm = args
.get("algorithm")
.and_then(JsonValue::as_str)
.unwrap_or("sha256");
let mut hash = match algorithm {
"sha256" => hash::hash_sha256_to_str(s),
"blake3" => hash::hash_blake3_to_str(s),
_ => return Err(tera1_err(format!("unknown hash algorithm: {algorithm}"))),
};
if let Some(len) = args.get("len").and_then(JsonValue::as_u64) {
hash = hash.chars().take(len as usize).collect();
}
Ok(json!(hash))
},
);
tera.register_filter(
"absolute",
tera1_path_filter(|p| Ok(p.absolutize()?.to_path_buf())),
);
tera.register_filter("canonicalize", tera1_path_filter(|p| p.canonicalize()));
tera.register_filter(
"dirname",
move |value: &JsonValue, _: &HashMap<String, JsonValue>| {
let p = Path::new(json_path(value)?);
Ok(json!(
p.parent()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default()
))
},
);
tera.register_filter(
"basename",
move |value: &JsonValue, _: &HashMap<String, JsonValue>| {
let p = Path::new(json_path(value)?);
Ok(json!(
p.file_name()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default()
))
},
);
tera.register_filter(
"extname",
move |value: &JsonValue, _: &HashMap<String, JsonValue>| {
let p = Path::new(json_path(value)?);
Ok(json!(
p.extension()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default()
))
},
);
tera.register_filter(
"file_stem",
move |value: &JsonValue, _: &HashMap<String, JsonValue>| {
let p = Path::new(json_path(value)?);
Ok(json!(
p.file_stem()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default()
))
},
);
tera.register_filter(
"file_size",
move |value: &JsonValue, _: &HashMap<String, JsonValue>| {
let path = Path::new(json_path(value)?);
track_tera_file(path);
Ok(json!(
path.metadata().map_err(|e| tera1_err(e.to_string()))?.len()
))
},
);
tera.register_filter("trim_start", tera1_trim_filter(TrimSide::Start));
tera.register_filter("trim_end", tera1_trim_filter(TrimSide::End));
tera.register_filter(
"last_modified",
move |value: &JsonValue, _: &HashMap<String, JsonValue>| {
let path = Path::new(json_path(value)?);
track_tera_file(path);
Ok(json!(
path.metadata()
.map_err(|e| tera1_err(e.to_string()))?
.modified()
.map_err(|e| tera1_err(e.to_string()))?
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| tera1_err(e.to_string()))?
.as_secs()
))
},
);
tera.register_filter(
"join_path",
move |value: &JsonValue, _: &HashMap<String, JsonValue>| {
let arr = value
.as_array()
.ok_or_else(|| tera1_err("join_path input must be an array of strings"))?;
let mut path = PathBuf::new();
for value in arr {
path.push(
value
.as_str()
.ok_or_else(|| tera1_err("join_path input must be an array of strings"))?,
);
}
Ok(json!(path.to_string_lossy().to_string()))
},
);
tera.register_filter(
"quote",
move |value: &JsonValue, _: &HashMap<String, JsonValue>| {
Ok(json!(posix_shell_quote(json_path(value)?)))
},
);
tera.register_filter("kebabcase", tera1_string_filter(|s| s.to_kebab_case()));
tera.register_filter(
"lowercamelcase",
tera1_string_filter(|s| s.to_lower_camel_case()),
);
tera.register_filter(
"shoutykebabcase",
tera1_string_filter(|s| s.to_shouty_kebab_case()),
);
tera.register_filter(
"shoutysnakecase",
tera1_string_filter(|s| s.to_shouty_snake_case()),
);
tera.register_filter("snakecase", tera1_string_filter(|s| s.to_snake_case()));
tera.register_filter(
"uppercamelcase",
tera1_string_filter(|s| s.to_upper_camel_case()),
);
tera.register_tester("dir", move |value: Option<&JsonValue>, _: &[JsonValue]| {
Ok(value
.and_then(JsonValue::as_str)
.is_some_and(|s| Path::new(s).is_dir()))
});
tera.register_tester("file", move |value: Option<&JsonValue>, _: &[JsonValue]| {
Ok(value
.and_then(JsonValue::as_str)
.is_some_and(|s| Path::new(s).is_file()))
});
tera.register_tester(
"exists",
move |value: Option<&JsonValue>, _: &[JsonValue]| {
Ok(value
.and_then(JsonValue::as_str)
.is_some_and(|s| Path::new(s).exists()))
},
);
tera.register_tester(
"semver_matching",
move |value: Option<&JsonValue>, args: &[JsonValue]| {
let version = value
.and_then(JsonValue::as_str)
.ok_or_else(|| tera1_err("semver_matching value must be a string"))?;
let requirement = args
.first()
.and_then(JsonValue::as_str)
.ok_or_else(|| tera1_err("semver_matching requirement must be a string"))?;
let requirement = Requirement::new(requirement).ok_or_else(|| {
tera1_err(format!(
"semver_matching requirement is invalid: {requirement}"
))
})?;
let version = Versioning::new(version).ok_or_else(|| {
tera1_err(format!("semver_matching version is invalid: {version}"))
})?;
Ok(requirement.matches(&version))
},
);
tera
});
fn host_libc_name() -> String {
match crate::platform::Platform::current().libc() {
Some("musl") => "musl",
_ => "gnu",
}
.to_string()
}
fn host_avx2_name() -> String {
let avx2 = crate::platform::host_has_avx2();
if avx2 { "yes" } else { "no" }.to_string()
}
fn target_libc_name(qualifier: Option<&str>) -> String {
let musl = qualifier.is_some_and(|q| q.split('-').any(|part| part == "musl"));
if musl { "musl" } else { "gnu" }.to_string()
}
fn target_avx2_name(qualifier: Option<&str>) -> String {
let baseline = qualifier.is_some_and(|q| q.split('-').any(|part| part == "baseline"));
if baseline { "no" } else { "yes" }.to_string()
}
fn tera2_variant_fn(
value: impl Fn() -> String + Send + Sync + 'static,
) -> impl Fn(Kwargs, &State) -> TeraResult<Value> + Send + Sync + 'static {
move |args: Kwargs, _: &State| -> TeraResult<Value> {
let value = value();
if let Some(remapped) = args.get::<&str>(&value)? {
return Ok(Value::from(remapped));
}
Ok(Value::from(value))
}
}
fn tera1_variant_fn(
value: impl Fn() -> String + Send + Sync + 'static,
) -> impl Fn(&HashMap<String, JsonValue>) -> tera1::Result<JsonValue> + Send + Sync + 'static {
move |args| {
let value = value();
Ok(args
.get(&value)
.and_then(JsonValue::as_str)
.map_or_else(|| json!(value), |remapped| json!(remapped)))
}
}
fn host_arch_name() -> &'static str {
if cfg!(target_arch = "x86_64") {
"x64"
} else if cfg!(target_arch = "aarch64") {
"arm64"
} else {
env::consts::ARCH
}
}
fn tera1_host_fn(
default: fn() -> &'static str,
) -> impl Fn(&HashMap<String, JsonValue>) -> tera1::Result<JsonValue> {
move |args| {
let value = default();
Ok(args
.get(value)
.and_then(JsonValue::as_str)
.map_or_else(|| json!(value), |remapped| json!(remapped)))
}
}
fn tera1_string_filter(
f: fn(&str) -> String,
) -> impl Fn(&JsonValue, &HashMap<String, JsonValue>) -> tera1::Result<JsonValue> {
move |value, _| Ok(json!(f(json_path(value)?)))
}
fn tera1_path_filter(
f: fn(&Path) -> std::io::Result<PathBuf>,
) -> impl Fn(&JsonValue, &HashMap<String, JsonValue>) -> tera1::Result<JsonValue> {
move |value, _| {
let p = f(Path::new(json_path(value)?)).map_err(|e| tera1_err(e.to_string()))?;
Ok(json!(p.to_string_lossy().to_string()))
}
}
#[derive(Clone, Copy)]
enum TrimSide {
Start,
End,
}
fn tera1_trim_filter(
side: TrimSide,
) -> impl Fn(&JsonValue, &HashMap<String, JsonValue>) -> tera1::Result<JsonValue> {
move |value, args| {
let s = value
.as_str()
.ok_or_else(|| tera1_err("trim filters expect a string"))?;
let trimmed = match (args.get("pat").and_then(JsonValue::as_str), side) {
(Some(pat), TrimSide::Start) => s.trim_start_matches(pat),
(Some(pat), TrimSide::End) => s.trim_end_matches(pat),
(None, TrimSide::Start) => s.trim_start(),
(None, TrimSide::End) => s.trim_end(),
};
Ok(json!(trimmed))
}
}
pub fn get_tera_v2(dir: Option<&Path>) -> Tera {
let mut tera = TERA.clone();
let dir = dir.map(PathBuf::from);
if Settings::get().safe {
disable_in_safe_mode(&mut tera);
} else {
tera.register_function("exec", tera_exec(dir.clone(), env::PRISTINE_ENV.clone()));
tera.register_function("read_file", tera_read_file(dir.clone()));
for (name, format) in STRUCTURED_FORMATS {
tera.register_function(name, tera_read_structured(name, format, dir.clone()));
}
}
tera
}
fn get_tera_v1(dir: Option<&Path>) -> tera1::Tera {
let mut tera = TERA1.clone();
let dir = dir.map(PathBuf::from);
if Settings::get().safe {
disable_in_safe_mode_v1(&mut tera);
} else {
tera.register_function("exec", tera1_exec(dir.clone(), env::PRISTINE_ENV.clone()));
tera.register_function("read_file", tera1_read_file(dir.clone()));
for (name, format) in STRUCTURED_FORMATS {
tera.register_function(name, tera1_read_structured(name, format, dir.clone()));
}
}
tera
}
const SAFE_DISABLED_FUNCTIONS: [&str; 3] = ["exec", "read_file", "get_env"];
const SAFE_DISABLED_FILTERS: [&str; 4] =
["hash_file", "file_size", "last_modified", "canonicalize"];
const SAFE_DISABLED_TESTS: [&str; 3] = ["dir", "file", "exists"];
fn disable_in_safe_mode(tera: &mut Tera) {
let structured = STRUCTURED_FORMATS.iter().map(|(name, _)| *name);
for name in SAFE_DISABLED_FUNCTIONS.into_iter().chain(structured) {
tera.register_function(name, safe_disabled_fn(name));
}
for name in SAFE_DISABLED_FILTERS {
tera.register_filter(name, safe_disabled_filter(name));
}
for name in SAFE_DISABLED_TESTS {
tera.register_test(name, safe_disabled_test(name));
}
}
fn disable_in_safe_mode_v1(tera: &mut tera1::Tera) {
let structured = STRUCTURED_FORMATS.iter().map(|(name, _)| *name);
for name in SAFE_DISABLED_FUNCTIONS.into_iter().chain(structured) {
tera.register_function(name, safe_disabled_fn_v1(name));
}
for name in SAFE_DISABLED_FILTERS {
tera.register_filter(name, safe_disabled_filter_v1(name));
}
for name in SAFE_DISABLED_TESTS {
tera.register_tester(name, safe_disabled_test_v1(name));
}
}
fn safe_disabled_test(name: &'static str) -> impl Fn(Value, Kwargs, &State) -> TeraResult<bool> {
move |_: Value, _: Kwargs, _: &State| -> TeraResult<bool> {
Err(tera_err(format!(
"the {name} test is disabled in safe mode (MISE_SAFE=1)"
)))
}
}
fn safe_disabled_test_v1(
name: &'static str,
) -> impl Fn(Option<&JsonValue>, &[JsonValue]) -> tera1::Result<bool> {
move |_: Option<&JsonValue>, _: &[JsonValue]| -> tera1::Result<bool> {
Err(tera1_err(format!(
"the {name} test is disabled in safe mode (MISE_SAFE=1)"
)))
}
}
fn safe_disabled_filter(name: &'static str) -> impl Fn(Value, Kwargs, &State) -> TeraResult<Value> {
move |_: Value, _: Kwargs, _: &State| -> TeraResult<Value> {
Err(tera_err(format!(
"the {name} filter is disabled in safe mode (MISE_SAFE=1)"
)))
}
}
fn safe_disabled_filter_v1(
name: &'static str,
) -> impl Fn(&JsonValue, &HashMap<String, JsonValue>) -> tera1::Result<JsonValue> {
move |_: &JsonValue, _: &HashMap<String, JsonValue>| -> tera1::Result<JsonValue> {
Err(tera1_err(format!(
"the {name} filter is disabled in safe mode (MISE_SAFE=1)"
)))
}
}
fn safe_disabled_fn(name: &'static str) -> impl Fn(Kwargs, &State) -> TeraResult<Value> {
move |_args: Kwargs, _: &State| -> TeraResult<Value> {
Err(tera_err(format!(
"{name}() is disabled in safe mode (MISE_SAFE=1)"
)))
}
}
fn safe_disabled_fn_v1(
name: &'static str,
) -> impl Fn(&HashMap<String, JsonValue>) -> tera1::Result<JsonValue> {
move |_args: &HashMap<String, JsonValue>| -> tera1::Result<JsonValue> {
Err(tera1_err(format!(
"{name}() is disabled in safe mode (MISE_SAFE=1)"
)))
}
}
pub fn get_miserc_tera() -> TeraEngine {
let mut tera = TERA.clone();
if safe_mode() {
disable_in_safe_mode(&mut tera);
}
TeraEngine::V2(Box::new(tera))
}
pub fn get_empty_tera() -> TeraEngine {
if use_tera_v1() {
TeraEngine::V1(Box::default())
} else {
TeraEngine::V2(Box::default())
}
}
pub fn get_tera(dir: Option<&Path>) -> TeraEngine {
if use_tera_v1() {
TeraEngine::V1(Box::new(get_tera_v1(dir)))
} else {
TeraEngine::V2(Box::new(get_tera_v2(dir)))
}
}
pub fn get_tera_for_oci(dir: Option<&Path>) -> TeraEngine {
const ENV_MESSAGE: &str = "environment access is disabled for OCI dotfile templates";
const FILE_MESSAGE: &str = "host file access is disabled for OCI dotfile templates";
if use_tera_v1() {
let mut tera = get_tera_v1(dir);
tera.register_function("get_env", move |_: &HashMap<String, JsonValue>| {
Err(tera1_err(ENV_MESSAGE))
});
tera.register_function("exec", move |_: &HashMap<String, JsonValue>| {
Err(tera1_err(ENV_MESSAGE))
});
tera.register_function("read_file", move |_: &HashMap<String, JsonValue>| {
Err(tera1_err(FILE_MESSAGE))
});
for (name, _) in STRUCTURED_FORMATS {
tera.register_function(name, move |_: &HashMap<String, JsonValue>| {
Err(tera1_err(FILE_MESSAGE))
});
}
TeraEngine::V1(Box::new(tera))
} else {
let mut tera = get_tera_v2(dir);
tera.register_function(
"get_env",
move |_: Kwargs, _: &State| -> TeraResult<Value> { Err(tera_err(ENV_MESSAGE)) },
);
tera.register_function("exec", move |_: Kwargs, _: &State| -> TeraResult<Value> {
Err(tera_err(ENV_MESSAGE))
});
tera.register_function(
"read_file",
move |_: Kwargs, _: &State| -> TeraResult<Value> { Err(tera_err(FILE_MESSAGE)) },
);
for (name, _) in STRUCTURED_FORMATS {
tera.register_function(name, move |_: Kwargs, _: &State| -> TeraResult<Value> {
Err(tera_err(FILE_MESSAGE))
});
}
TeraEngine::V2(Box::new(tera))
}
}
pub fn get_tera_without_exec(dir: Option<&Path>) -> TeraEngine {
const MESSAGE: &str = "exec() is not available in [bootstrap] resource values";
if use_tera_v1() {
let mut tera = get_tera_v1(dir);
tera.register_function("exec", move |_: &HashMap<String, JsonValue>| {
Err(tera1_err(MESSAGE))
});
TeraEngine::V1(Box::new(tera))
} else {
let mut tera = get_tera_v2(dir);
tera.register_function("exec", move |_: Kwargs, _: &State| -> TeraResult<Value> {
Err(tera_err(MESSAGE))
});
TeraEngine::V2(Box::new(tera))
}
}
pub fn get_tera_for_cmd(dir: Option<&Path>) -> TeraEngine {
if use_tera_v1() {
quote_for_cmd(TeraEngine::V1(Box::new(get_tera_v1(dir))))
} else {
quote_for_cmd(TeraEngine::V2(Box::new(get_tera_v2(dir))))
}
}
fn quote_for_cmd(mut engine: TeraEngine) -> TeraEngine {
match &mut engine {
TeraEngine::V1(tera) => tera.register_filter(
"quote",
move |value: &JsonValue, _: &HashMap<String, JsonValue>| {
Ok(json!(crate::path::escape_arg_for_cmd_line(json_path(
value
)?)))
},
),
TeraEngine::V2(tera) => tera.register_filter(
"quote",
move |s: &str, _: Kwargs, _: &State| -> TeraResult<Value> {
Ok(Value::from(crate::path::escape_arg_for_cmd_line(s)))
},
),
}
engine
}
#[derive(Debug)]
pub enum DryRunRender {
Rendered(String),
Unrendered(tera::Error),
Failed(tera::Error),
}
pub fn render_for_dry_run(
dir: Option<&Path>,
input: &str,
context: &Context,
unresolved: &IndexSet<String>,
) -> DryRunRender {
if !unresolved.is_empty() && reads_whole_vars_map(input) {
let names = unresolved.iter().map(String::as_str).collect::<Vec<_>>();
return DryRunRender::Unrendered(tera_err(format!(
"the template reads the whole vars map, which leaves out vars the dry run could not compute: {}",
names.join(", ")
)));
}
let reached_exec = Arc::new(AtomicBool::new(false));
let mut tera = dry_run_tera(dir, reached_exec.clone());
match render_str(&mut tera, input, context) {
Ok(out) => DryRunRender::Rendered(out),
Err(err) if reached_exec.load(Ordering::Relaxed) || !unresolved.is_empty() => {
DryRunRender::Unrendered(err)
}
Err(err) => DryRunRender::Failed(err),
}
}
fn reads_whole_vars_map(input: &str) -> bool {
let s = input.as_bytes();
let is_ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
let mut i = 0;
while i < s.len() {
if !is_ident(s[i]) {
i += 1;
continue;
}
let start = i;
while i < s.len() && is_ident(s[i]) {
i += 1;
}
let attribute = start > 0 && s[start - 1] == b'.' && !s[..start].ends_with(b"...");
if &s[start..i] == b"vars" && !attribute {
let next = s[i..].iter().find(|b| !b.is_ascii_whitespace());
if !matches!(next, Some(b'.' | b'[')) {
return true;
}
}
}
false
}
pub fn error_chain(err: &tera::Error) -> String {
let mut chain = vec![err.to_string()];
let mut source = std::error::Error::source(err);
while let Some(err) = source {
chain.push(err.to_string());
source = err.source();
}
chain.dedup();
chain.join(": ")
}
fn dry_run_tera(dir: Option<&Path>, reached_exec: Arc<AtomicBool>) -> TeraEngine {
if use_tera_v1() {
let mut tera = get_tera_v1(dir);
tera.register_function("exec", dry_run_disabled_fn_v1("exec", reached_exec));
TeraEngine::V1(Box::new(tera))
} else {
let mut tera = get_tera_v2(dir);
tera.register_function("exec", dry_run_disabled_fn("exec", reached_exec));
TeraEngine::V2(Box::new(tera))
}
}
fn dry_run_disabled_fn(
name: &'static str,
reached: Arc<AtomicBool>,
) -> impl Fn(Kwargs, &State) -> TeraResult<Value> {
move |_args: Kwargs, _: &State| -> TeraResult<Value> {
reached.store(true, Ordering::Relaxed);
Err(tera_err(format!("{name}() is disabled during dry run")))
}
}
fn dry_run_disabled_fn_v1(
name: &'static str,
reached: Arc<AtomicBool>,
) -> impl Fn(&HashMap<String, JsonValue>) -> tera1::Result<JsonValue> {
move |_args: &HashMap<String, JsonValue>| -> tera1::Result<JsonValue> {
reached.store(true, Ordering::Relaxed);
Err(tera1_err(format!("{name}() is disabled during dry run")))
}
}
pub fn get_tera_for_target(
dir: Option<&Path>,
os: &str,
arch: &str,
qualifier: Option<&str>,
) -> TeraEngine {
let family = if os == "windows" { "windows" } else { "unix" };
if use_tera_v1() {
let mut tera = get_tera_v1(dir);
let os = os.to_string();
tera.register_function("os", move |args: &HashMap<String, JsonValue>| {
Ok(args
.get(&os)
.and_then(JsonValue::as_str)
.map_or_else(|| json!(os), |remapped| json!(remapped)))
});
let arch = arch.to_string();
tera.register_function("arch", move |args: &HashMap<String, JsonValue>| {
Ok(args
.get(&arch)
.and_then(JsonValue::as_str)
.map_or_else(|| json!(arch), |remapped| json!(remapped)))
});
tera.register_function("os_family", move |_: &HashMap<String, JsonValue>| {
Ok(json!(family))
});
let libc = target_libc_name(qualifier);
tera.register_function("libc", tera1_variant_fn(move || libc.clone()));
let avx2 = target_avx2_name(qualifier);
tera.register_function("avx2", tera1_variant_fn(move || avx2.clone()));
TeraEngine::V1(Box::new(tera))
} else {
let mut tera = get_tera_v2(dir);
let os = os.to_string();
tera.register_function("os", move |args: Kwargs, _: &State| -> TeraResult<Value> {
if let Some(remapped) = args.get::<&str>(&os)? {
return Ok(Value::from(remapped));
}
Ok(Value::from(os.clone()))
});
let arch = arch.to_string();
tera.register_function(
"arch",
move |args: Kwargs, _: &State| -> TeraResult<Value> {
if let Some(remapped) = args.get::<&str>(&arch)? {
return Ok(Value::from(remapped));
}
Ok(Value::from(arch.clone()))
},
);
tera.register_function(
"os_family",
move |_: Kwargs, _: &State| -> TeraResult<Value> { Ok(Value::from(family)) },
);
let libc = target_libc_name(qualifier);
tera.register_function("libc", tera2_variant_fn(move || libc.clone()));
let avx2 = target_avx2_name(qualifier);
tera.register_function("avx2", tera2_variant_fn(move || avx2.clone()));
TeraEngine::V2(Box::new(tera))
}
}
pub fn get_tera_preserving_os_arch(dir: Option<&Path>) -> TeraEngine {
if use_tera_v1() {
let mut tera = get_tera_v1(dir);
tera.register_function("os", reemit_template_fn_v1("os"));
tera.register_function("arch", reemit_template_fn_v1("arch"));
tera.register_function("os_family", reemit_template_fn_v1("os_family"));
tera.register_function("libc", reemit_template_fn_v1("libc"));
tera.register_function("avx2", reemit_template_fn_v1("avx2"));
TeraEngine::V1(Box::new(tera))
} else {
let mut tera = get_tera_v2(dir);
tera.register_function("os", reemit_template_fn("os"));
tera.register_function("arch", reemit_template_fn("arch"));
tera.register_function("os_family", reemit_template_fn("os_family"));
tera.register_function("libc", reemit_template_fn("libc"));
tera.register_function("avx2", reemit_template_fn("avx2"));
TeraEngine::V2(Box::new(tera))
}
}
fn reemit_template_fn_v1(
name: &'static str,
) -> impl Fn(&HashMap<String, JsonValue>) -> tera1::Result<JsonValue> {
move |args| {
let mut parts: Vec<String> = args
.iter()
.filter_map(|(k, v)| reemit_arg_literal(v).map(|lit| format!("{k}={lit}")))
.collect();
let rendered = if parts.is_empty() {
format!("{{{{ {name}() }}}}")
} else {
parts.sort();
format!("{{{{ {name}({}) }}}}", parts.join(", "))
};
Ok(json!(rendered))
}
}
fn tera1_get_env(env: EnvMap) -> impl Fn(&HashMap<String, JsonValue>) -> tera1::Result<JsonValue> {
move |args: &HashMap<String, JsonValue>| -> tera1::Result<JsonValue> {
let name = json_str_arg(args, "name")?;
if let Some(value) = env.get(name) {
return Ok(json!(value));
}
match args.get("default") {
Some(default) => Ok(default.clone()),
None => Err(tera1_err(format!(
"Environment variable `{name}` not found"
))),
}
}
}
pub fn tera1_exec(
dir: Option<PathBuf>,
env: EnvMap,
) -> impl Fn(&HashMap<String, JsonValue>) -> tera1::Result<JsonValue> {
move |args: &HashMap<String, JsonValue>| -> tera1::Result<JsonValue> {
let command = json_str_arg(args, "command")?;
let shell = crate::shells::default_inline_shell(&Settings::get())
.map_err(|e| tera1_err(e.to_string()))?;
let shell_args = shell
.iter()
.skip(1)
.chain(once(&command.to_string()))
.cloned()
.collect::<Vec<String>>();
let mut env_no_shims = env.clone();
if let Some(path_val) = env_no_shims.get(&*env::PATH_KEY).cloned() {
env_no_shims.insert(env::PATH_KEY.to_string(), strip_shims_from_path(&path_val));
}
let run_once = || -> eyre::Result<String> {
#[cfg(windows)]
{
if let Some(mut c) =
crate::path::cmd_verbatim_command(&shell[0], &shell[1..], command)
{
c.env_clear();
c.envs(env_no_shims.iter());
if let Some(dir) = &dir {
c.current_dir(dir);
}
let out = c.output()?;
if !out.status.success() {
eyre::bail!(
"exec command failed: {}",
String::from_utf8_lossy(&out.stderr)
);
}
let mut s = String::from_utf8(out.stdout)?;
while s.ends_with('\n') || s.ends_with('\r') {
s.pop();
}
return Ok(s);
}
}
let mut expr: duct::Expression = cmd(&shell[0], &shell_args).full_env(&env_no_shims);
if let Some(dir) = &dir {
expr = expr.dir(dir);
}
Ok(crate::inline_command::optimize_expression(
expr,
command,
&env_no_shims,
dir.as_deref(),
crate::shells::implicit_inline_shell(),
)
.read()?)
};
Ok(json!(
run_once().map_err(|e| tera1_err(format!("exec command: {e}")))?
))
}
}
pub fn tera1_read_file(
dir: Option<PathBuf>,
) -> impl Fn(&HashMap<String, JsonValue>) -> tera1::Result<JsonValue> {
move |args: &HashMap<String, JsonValue>| -> tera1::Result<JsonValue> {
let path_str = json_str_arg(args, "path")?;
let path = if let Some(ref base_dir) = dir {
base_dir.join(path_str)
} else {
PathBuf::from(path_str)
};
track_tera_file(&path);
Ok(json!(std::fs::read_to_string(&path).map_err(|e| {
tera1_err(format!("read_file({}): {e}", path.display()))
})?))
}
}
fn reemit_template_fn(name: &'static str) -> impl Fn(Kwargs, &State) -> TeraResult<Value> {
move |args: Kwargs, _: &State| {
let args = args.deserialize::<std::collections::BTreeMap<String, serde_json::Value>>()?;
let mut parts: Vec<String> = args
.iter()
.filter_map(|(k, v)| reemit_arg_literal(v).map(|lit| format!("{k}={lit}")))
.collect();
let rendered = if parts.is_empty() {
format!("{{{{ {name}() }}}}")
} else {
parts.sort();
format!("{{{{ {name}({}) }}}}", parts.join(", "))
};
Ok(Value::from(rendered))
}
}
fn reemit_arg_literal(v: &serde_json::Value) -> Option<String> {
match v {
serde_json::Value::String(s) => Some(format!("\"{s}\"")),
serde_json::Value::Number(n) => Some(n.to_string()),
serde_json::Value::Bool(b) => Some(b.to_string()),
_ => None,
}
}
pub fn tera_exec(
dir: Option<PathBuf>,
env: EnvMap,
) -> impl Fn(Kwargs, &State) -> TeraResult<Value> {
move |args: Kwargs, _: &State| -> TeraResult<Value> {
let cache = args.get::<String>("cache_key")?;
let cache_duration = match args.get::<String>("cache_duration")? {
Some(duration) => match duration::parse_duration(&duration) {
Ok(duration) => Some(duration),
Err(e) => return Err(tera_err(format!("exec cache_duration: {e}"))),
},
None => None,
};
match args.get::<String>("command")? {
Some(command) => {
let shell = crate::shells::default_inline_shell(&Settings::get())
.map_err(|e| tera_err(e.to_string()))?;
let args = shell
.iter()
.skip(1)
.chain(once(&command))
.collect::<Vec<&String>>();
let mut env_no_shims = env.clone();
if let Some(path_val) = env_no_shims.get(&*env::PATH_KEY).cloned() {
env_no_shims
.insert(env::PATH_KEY.to_string(), strip_shims_from_path(&path_val));
}
let run_once = || -> eyre::Result<String> {
#[cfg(windows)]
{
if let Some(mut c) =
crate::path::cmd_verbatim_command(&shell[0], &shell[1..], &command)
{
c.env_clear();
c.envs(env_no_shims.iter());
if let Some(dir) = &dir {
c.current_dir(dir);
}
let out = c.output()?;
if !out.status.success() {
eyre::bail!(
"exec command failed: {}",
String::from_utf8_lossy(&out.stderr)
);
}
let mut s = String::from_utf8(out.stdout)?;
while s.ends_with('\n') || s.ends_with('\r') {
s.pop();
}
return Ok(s);
}
}
let mut expr: duct::Expression = cmd(&shell[0], args).full_env(&env_no_shims);
if let Some(dir) = &dir {
expr = expr.dir(dir);
}
Ok(crate::inline_command::optimize_expression(
expr,
&command,
&env_no_shims,
dir.as_deref(),
crate::shells::implicit_inline_shell(),
)
.read()?)
};
let result = if cache.is_some() || cache_duration.is_some() {
let cachehash = hash::hash_blake3_to_str(
&(dir
.as_ref()
.map(|d| d.to_string_lossy().to_string())
.unwrap_or_default()
+ &command),
)[..8]
.to_string();
let mut cacheman =
CacheManagerBuilder::new(dirs::CACHE.join("exec").join(cachehash));
if let Some(cache) = cache {
cacheman = cacheman.with_cache_key(cache);
}
if let Some(cache_duration) = cache_duration {
cacheman = cacheman.with_fresh_duration(Some(cache_duration));
}
let cache = cacheman.build();
match cache.get_or_try_init(run_once) {
Ok(result) => result.clone(),
Err(e) => return Err(tera_err(format!("exec command: {e}"))),
}
} else {
run_once().map_err(|e| tera_err(format!("exec command: {e}")))?
};
Ok(Value::from(result))
}
_ => Err(tera_err("exec command must be a string")),
}
}
}
pub fn tera_read_file(dir: Option<PathBuf>) -> impl Fn(Kwargs, &State) -> TeraResult<Value> {
move |args: Kwargs, _: &State| -> TeraResult<Value> {
match args.get::<String>("path")? {
Some(path_str) => {
let path = if let Some(ref base_dir) = dir {
base_dir.join(&path_str)
} else {
PathBuf::from(&path_str)
};
track_tera_file(&path);
match std::fs::read_to_string(&path) {
Ok(contents) => Ok(Value::from(contents)),
Err(e) => Err(tera_err(format!(
"Failed to read file '{}': {}",
path.display(),
e
))),
}
}
_ => Err(tera_err("read_file path must be a string")),
}
}
}
#[derive(Clone, Copy)]
enum StructuredFormat {
Json,
Yaml,
Toml,
}
const STRUCTURED_FORMATS: [(&str, StructuredFormat); 3] = [
("read_json", StructuredFormat::Json),
("read_yaml", StructuredFormat::Yaml),
("read_toml", StructuredFormat::Toml),
];
fn read_structured(
name: &str,
format: StructuredFormat,
dir: Option<&Path>,
path_str: &str,
) -> Result<JsonValue, String> {
let path = match dir {
Some(base_dir) => base_dir.join(path_str),
None => PathBuf::from(path_str),
};
track_tera_file(&path);
let text = std::fs::read_to_string(&path)
.map_err(|e| format!("{name}({}): failed to read file: {e}", path.display()))?;
let parsed = match format {
StructuredFormat::Json => serde_json::from_str(&text).map_err(|e| e.to_string()),
StructuredFormat::Yaml => crate::yaml::from_str(&text).map_err(|e| e.to_string()),
StructuredFormat::Toml => toml::from_str::<toml::Value>(&text)
.map(toml_to_json)
.map_err(|e| e.to_string()),
};
parsed.map_err(|e| format!("{name}({}): failed to parse file: {e}", path.display()))
}
fn toml_to_json(value: toml::Value) -> JsonValue {
match value {
toml::Value::String(s) => json!(s),
toml::Value::Integer(i) => json!(i),
toml::Value::Float(f) => json!(f),
toml::Value::Boolean(b) => json!(b),
toml::Value::Datetime(d) => json!(d.to_string()),
toml::Value::Array(a) => JsonValue::Array(a.into_iter().map(toml_to_json).collect()),
toml::Value::Table(t) => {
JsonValue::Object(t.into_iter().map(|(k, v)| (k, toml_to_json(v))).collect())
}
}
}
fn tera_read_structured(
name: &'static str,
format: StructuredFormat,
dir: Option<PathBuf>,
) -> impl Fn(Kwargs, &State) -> TeraResult<Value> {
move |args: Kwargs, _: &State| -> TeraResult<Value> {
let Some(path_str) = args.get::<String>("path")? else {
return Err(tera_err(format!("{name} path must be a string")));
};
let value = read_structured(name, format, dir.as_deref(), &path_str).map_err(tera_err)?;
Ok(Value::from_serializable(&value))
}
}
fn tera1_read_structured(
name: &'static str,
format: StructuredFormat,
dir: Option<PathBuf>,
) -> impl Fn(&HashMap<String, JsonValue>) -> tera1::Result<JsonValue> {
move |args: &HashMap<String, JsonValue>| -> tera1::Result<JsonValue> {
let path_str = json_str_arg(args, "path")?;
read_structured(name, format, dir.as_deref(), path_str).map_err(tera1_err)
}
}
#[cfg(test)]
mod tests;