anodizer_core/template/render.rs
1use anyhow::{Context as _, Result};
2use serde_json::Value;
3use std::collections::{BTreeMap, HashMap};
4use tera::TeraResult;
5
6use crate::env_source::{EnvSource, ProcessEnvSource};
7use crate::template_preprocess::{
8 preprocess, protect_shell_param_length, restore_shell_param_length,
9};
10
11use super::base_tera::{BASE_TERA, translate_go_time_format};
12use super::engine_adapter::{JsonRegisterExt, double_string_literal_backslashes};
13use super::vars::{ENV_REF_RE, NUMERIC_FIELDS, TemplateVars};
14
15/// Insert a string map into the context in sorted key order.
16///
17/// tera 2.0 preserves insertion order (`preserve_order` feature), which for a
18/// `HashMap` would be a random per-process order. Sorting into a `BTreeMap`
19/// before insert guarantees `{% for k, v in Env %}` iterates keys sorted,
20/// deterministically, regardless of how `serde_json`'s own map type is
21/// configured elsewhere in the workspace.
22fn insert_sorted(ctx: &mut tera::Context, key: &'static str, map: &HashMap<String, String>) {
23 let sorted: BTreeMap<&str, &str> = map.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
24 ctx.insert(key, &sorted);
25}
26
27/// Build a `tera::Context` from `TemplateVars`, pre-populating missing env var
28/// keys referenced in the template with empty strings.
29///
30/// An empty string is returned for `{{ .Env.NONEXISTENT }}` rather than
31/// erroring. Tera's strict mode would error on a missing map key, so we scan
32/// the preprocessed template for `Env.VARNAME` references and ensure every
33/// referenced key exists in the env map (defaulting to "").
34///
35/// Fallback semantics: when an `Env.X` key is not in `TemplateVars::env`,
36/// `std::env::var(X)` is consulted before defaulting to `""`. This is
37/// intentional — these semantics let a user reference any
38/// process env var via `{{ Env.X }}`, and the `StageLogger`-level
39/// redaction layer (see `crate::redact`) prevents accidental secret
40/// prints in the rendered output. A `*_TOKEN` / `*_KEY` / `*_PASSWORD`
41/// value flowing through here is redacted before it reaches stderr.
42fn build_tera_context_for_template(
43 vars: &TemplateVars,
44 preprocessed: &str,
45 host_env: &dyn EnvSource,
46) -> tera::Context {
47 // Discover all Env.VARNAME references in the template.
48 let referenced_env_keys: Vec<String> = ENV_REF_RE
49 .captures_iter(preprocessed)
50 .map(|cap| cap[1].to_string())
51 .collect();
52
53 // Build an env map that includes all referenced keys, defaulting missing ones to "".
54 let mut env_with_defaults = HashMap::new();
55 for key in &referenced_env_keys {
56 if !vars.env.contains_key(key.as_str()) {
57 // Check the injected host env as fallback before defaulting to "".
58 let value = host_env.var(key).unwrap_or_default();
59 env_with_defaults.insert(key.clone(), value);
60 }
61 }
62 // Overlay with the actual env vars from TemplateVars.
63 for (k, v) in &vars.env {
64 env_with_defaults.insert(k.clone(), v.clone());
65 }
66
67 let mut augmented_vars = vars.clone();
68 // Replace the env map with our augmented one.
69 augmented_vars.env = env_with_defaults;
70
71 build_tera_context(&augmented_vars)
72}
73
74/// Build a `tera::Context` from `TemplateVars`.
75/// - Regular vars are inserted at the top level: `ProjectName`, `Version`, etc.
76/// - Env vars are nested under an `Env` key as a HashMap, so `{{ Env.GITHUB_TOKEN }}` works.
77/// - String values of `"true"` / `"false"` are inserted as bools so `{% if Var %}` works.
78/// - Known numeric fields (`Major`, `Minor`, `Patch`, `Timestamp`, `CommitTimestamp`)
79/// are inserted as integers so `{% if Major == 1 %}` works correctly.
80fn build_tera_context(vars: &TemplateVars) -> tera::Context {
81 let mut ctx = tera::Context::new();
82 for (k, v) in &vars.vars {
83 // For known numeric fields, parse as i64 and insert as a number so
84 // Tera comparisons like `{% if Major == 1 %}` work correctly.
85 if NUMERIC_FIELDS.contains(&k.as_str())
86 && let Ok(n) = v.parse::<i64>()
87 {
88 ctx.insert(k.clone(), &n);
89 continue;
90 }
91 match v.as_str() {
92 "true" => ctx.insert(k.clone(), &true),
93 "false" => ctx.insert(k.clone(), &false),
94 _ => ctx.insert(k.clone(), v),
95 }
96 }
97 insert_sorted(&mut ctx, "Env", &vars.env);
98
99 // Always insert Var (even when empty) so that referencing the `Var`
100 // namespace does not produce a hard Tera error. Accessing a missing key
101 // within the map still requires `| default(value="")`. This matches
102 // an empty .Var map is provided by default.
103 insert_sorted(&mut ctx, "Var", &vars.custom_vars);
104
105 // Always insert Outputs (even when empty) so that referencing the
106 // `Outputs` namespace does not produce a hard Tera error. Accessing a
107 // missing key within the map still requires `| default(value="")`.
108 insert_sorted(&mut ctx, "Outputs", &vars.outputs);
109
110 // Build a nested `Runtime` map for `Runtime.Goos` / `Runtime.Goarch`.
111 let mut runtime = HashMap::new();
112 if let Some(goos) = vars.vars.get("RuntimeGoos") {
113 runtime.insert("Goos".to_string(), goos.clone());
114 }
115 if let Some(goarch) = vars.vars.get("RuntimeGoarch") {
116 runtime.insert("Goarch".to_string(), goarch.clone());
117 }
118 if !runtime.is_empty() {
119 insert_sorted(&mut ctx, "Runtime", &runtime);
120 }
121
122 // Insert structured values (arrays, objects) directly into the context.
123 for (k, v) in &vars.structured {
124 ctx.insert(k.clone(), v);
125 }
126
127 ctx
128}
129
130/// Render a template string with the given variables.
131///
132/// Supports both Go-style (`{{ .Field }}`) and native Tera-style (`{{ Field }}`).
133/// Go-style references are preprocessed into Tera-style before rendering.
134///
135/// Because this uses Tera under the hood, all Tera features are available:
136/// conditionals (`{% if %}` / `{% else %}` / `{% endif %}`), loops (`{% for %}`),
137/// filters (`| lower`, `| upper`, `| default`, `| trim`, `| title`, `| replace`, etc.).
138///
139/// Custom filters are registered:
140/// - `tolower` / `toupper` — aliases for Tera's built-in `lower` / `upper`
141/// - `trimprefix(prefix="v")` — strip a prefix from a string
142/// - `trimsuffix(suffix=".exe")` — strip a suffix from a string
143pub fn render(template: &str, vars: &TemplateVars) -> Result<String> {
144 render_with_env(template, vars, &ProcessEnvSource)
145}
146
147/// Render `template` against `vars`, routing all env reads (Env.X fallback,
148/// `envOrDefault` / `isEnvSet` fallback, SDE-aware `time(...)` /
149/// `now_format` filters) through the injected `host_env`.
150///
151/// Production callers use [`render`] (which wires up [`ProcessEnvSource`]);
152/// tests inject a closed `MapEnvSource` so deterministic branches can be
153/// exercised without mutating the process env.
154pub fn render_with_env(
155 template: &str,
156 vars: &TemplateVars,
157 host_env: &dyn EnvSource,
158) -> Result<String> {
159 // Shield bash `${#…}` from Tera's `{#` comment-open before parsing, so it
160 // reaches the rendered output literally (GoReleaser's Go templates have no
161 // such collision); the inverse restore runs on the rendered string below.
162 let preprocessed_raw = preprocess(template);
163 let preprocessed = protect_shell_param_length(&preprocessed_raw)?;
164 // Restore 1.x raw string-literal semantics (`pattern="(\w+)"`) before
165 // tera 2.0's escape-processing lexer sees the template. Runs after the
166 // `${#…}` shield so comment-open collisions are already out of the text.
167 let preprocessed = double_string_literal_backslashes(preprocessed.as_ref());
168 let ctx = build_tera_context_for_template(vars, preprocessed.as_ref(), host_env);
169
170 // Clone the base instance (cheap — filters carry over, no templates to clone)
171 let mut tera = BASE_TERA.clone();
172
173 // Snapshot host-env entries the closures consult into an Arc<HashMap>
174 // so tera's `'static` closure requirement is met without leaking a
175 // borrow of `host_env` beyond this stack frame. The snapshot is a one-
176 // shot pull from the injected source: `MapEnvSource::vars()` returns
177 // the fixture map; `ProcessEnvSource::vars()` returns `std::env::vars()`
178 // at call time. Tera renderers run synchronously on the calling thread,
179 // so the snapshot is consistent for the lifetime of the call even if
180 // a sibling thread mutates process env between renders.
181 let host_snapshot: HashMap<String, String> = host_env.vars().into_iter().collect();
182 let host_snapshot = std::sync::Arc::new(host_snapshot);
183
184 // Override envOrDefault and isEnvSet with closures that read from the
185 // template context's Env map. This ensures .env file vars (loaded into
186 // TemplateVars via set_env) are visible, not just process env vars.
187 // Falls back to the injected `host_env` for vars that exist there but
188 // were not explicitly added to the template context.
189 let env_map = std::sync::Arc::new(vars.all_env().clone());
190 let env_map_for_default = env_map.clone();
191 let host_for_default = host_snapshot.clone();
192 tera.register_json_function(
193 "envOrDefault",
194 move |args: &HashMap<String, Value>| -> TeraResult<Value> {
195 let name = args
196 .get("name")
197 .and_then(|v| v.as_str())
198 .ok_or_else(|| tera::Error::message("envOrDefault requires `name` argument"))?;
199 let default = args.get("default").and_then(|v| v.as_str()).unwrap_or("");
200 // Check template context Env map first, then fall back to the
201 // injected host env.
202 let value = env_map_for_default
203 .get(name)
204 .cloned()
205 .or_else(|| host_for_default.get(name).cloned())
206 .unwrap_or_else(|| default.to_string());
207 Ok(Value::String(value))
208 },
209 );
210
211 let env_map_for_isset = env_map.clone();
212 let host_for_isset = host_snapshot.clone();
213 tera.register_json_function(
214 "isEnvSet",
215 move |args: &HashMap<String, Value>| -> TeraResult<Value> {
216 let name = args
217 .get("name")
218 .and_then(|v| v.as_str())
219 .ok_or_else(|| tera::Error::message("isEnvSet requires `name` argument"))?;
220 // Check template context Env map first, then fall back to the
221 // injected host env.
222 let is_set = env_map_for_isset
223 .get(name)
224 .map(|v| !v.is_empty())
225 .unwrap_or_else(|| {
226 host_for_isset
227 .get(name)
228 .map(|v| !v.is_empty())
229 .unwrap_or(false)
230 });
231 Ok(Value::Bool(is_set))
232 },
233 );
234
235 // Re-register the SDE-aware `time` / `now_format` helpers so they
236 // resolve `SOURCE_DATE_EPOCH` against the injected host env, not
237 // `std::env::var`. BASE_TERA registers placeholder shapes that read
238 // through `ProcessEnvSource` — fine for production, but tests injecting
239 // a `MapEnvSource` need the overrides to see their fixture value.
240 let host_for_time = host_snapshot.clone();
241 tera.register_json_function(
242 "time",
243 move |args: &HashMap<String, Value>| -> TeraResult<Value> {
244 let fmt = args
245 .get("format")
246 .and_then(|v| v.as_str())
247 .unwrap_or("%Y-%m-%dT%H:%M:%SZ");
248 let chrono_fmt = translate_go_time_format(fmt);
249 let sde = host_for_time.get("SOURCE_DATE_EPOCH").cloned();
250 let now = sde
251 .and_then(|s| s.parse::<i64>().ok())
252 .and_then(|secs| chrono::DateTime::<chrono::Utc>::from_timestamp(secs, 0))
253 .unwrap_or_else(chrono::Utc::now);
254 Ok(Value::String(now.format(&chrono_fmt).to_string()))
255 },
256 );
257
258 let host_for_now_format = host_snapshot.clone();
259 tera.register_json_filter(
260 "now_format",
261 move |_value: &Value, args: &HashMap<String, Value>| {
262 let fmt = args
263 .get("format")
264 .and_then(|v| v.as_str())
265 .ok_or_else(|| tera::Error::message("now_format requires a `format` argument"))?;
266 let chrono_fmt = translate_go_time_format(fmt);
267 let sde = host_for_now_format.get("SOURCE_DATE_EPOCH").cloned();
268 let now = sde
269 .and_then(|s| s.parse::<i64>().ok())
270 .and_then(|secs| chrono::DateTime::<chrono::Utc>::from_timestamp(secs, 0))
271 .unwrap_or_else(chrono::Utc::now);
272 Ok(Value::String(now.format(&chrono_fmt).to_string()))
273 },
274 );
275
276 tera.add_raw_template("__inline__", preprocessed.as_ref())
277 .with_context(|| format!("failed to parse template: {}", template))?;
278
279 let rendered = tera
280 .render("__inline__", &ctx)
281 .with_context(|| format!("failed to render template: {}", template))?;
282 Ok(restore_shell_param_length(&rendered).into_owned())
283}
284
285/// Extract the extension from an artifact filename, including compound
286/// extensions like `.tar.gz`, `.tar.xz`, `.tar.zst`, `.tar.bz2`, `.tar.lz4`,
287/// `.tar.sz`. Returns the extension with a leading dot (e.g. `.tar.gz`, `.exe`,
288/// `.dmg`), or an empty string if there is no extension.
289///
290/// This is the `.ArtifactExt` behavior.
291pub fn extract_artifact_ext(filename: &str) -> &str {
292 // Check for compound tar extensions first
293 const TAR_COMPOUND_SUFFIXES: &[&str] = &[
294 ".tar.gz", ".tar.xz", ".tar.zst", ".tar.bz2", ".tar.lz4", ".tar.sz",
295 ];
296 let lower = filename.to_ascii_lowercase();
297 for suffix in TAR_COMPOUND_SUFFIXES {
298 if lower.ends_with(suffix) {
299 // Return the slice from the original filename (preserving case)
300 return &filename[filename.len() - suffix.len()..];
301 }
302 }
303 // Fall back to the last dot-extension
304 match filename.rfind('.') {
305 Some(pos) if pos > 0 => &filename[pos..],
306 _ => "",
307 }
308}