roneocratesroneo-coresrcrenderer.rs
98ff76d5794bbd1480ad719803187d2c40e42403- use std::collections::HashMap;
- use std::fmt::Write as _;
- use std::path::{Component, Path, PathBuf};
- use std::sync::RwLock;
- use indexmap::IndexMap;
- use minijinja::syntax::SyntaxConfig;
- use minijinja::{Environment, Value as MjValue};
- use serde_json::Value as JsonValue;
- use crate::config::EnvOps;
- use crate::error::{Result, RoneoError};
- use crate::plugin::{ExtensionInitContext, ExtensionRegistry, TemplateFileReader};
- /// Sentinel global matching Copier's `{{ UNSET }}` in question `default:` templates.
- pub const UNSET_SENTINEL: &str = "__RONEO_COPIER_UNSET_SENTINEL__";
- /// Metadata exposed as `_copier_conf` inside templates (Copier-compatible).
- #[derive(Debug, Clone, serde::Serialize)]
- pub struct CopierConf {
- pub src_path: String,
- pub dst_path: String,
- pub answers_file: String,
- pub vcs_ref: Option<String>,
- pub vcs_ref_hash: Option<String>,
- pub sep: String,
- pub os: String,
- pub stage: String,
- pub overwrite: bool,
- pub pretend: bool,
- pub quiet: bool,
- #[serde(rename = "unsafe")]
- pub r#unsafe: bool,
- pub cleanup_on_error: bool,
- pub context_lines: usize,
- pub exclude: Vec<String>,
- pub skip_if_exists: Vec<String>,
- }
- /// Result of rendering one path segment (supports Copier's `{% yield var from list %}`
- /// expanding a single template file or directory into multiple rendered destinations).
- #[derive(Debug, Clone)]
- pub struct RenderedSegment {
- pub name: String,
- pub is_template_file: bool,
- pub yield_binding: Option<(String, JsonValue)>,
- }
- /// Jinja2-compatible template rendering engine powered by `MiniJinja` + `pycompat`.
- pub struct TemplateRenderer {
- env: Environment<'static>,
- var_start: String,
- block_start: String,
- block_end: String,
- comment_start: String,
- keep_trailing_newline: bool,
- }
- impl TemplateRenderer {
- pub fn new(envops: &EnvOps) -> Result<Self> {
- Self::with_extensions(envops, None, None, None)
- }
- /// Create a renderer that supports `{% include "..." %}` via a cached file reader
- /// (works for both disk checkouts and in-memory `gix` trees) and optional extensions.
- pub fn with_extensions(
- envops: &EnvOps,
- file_reader: Option<TemplateFileReader>,
- extensions: Option<&ExtensionRegistry>,
- init_ctx: Option<&ExtensionInitContext>,
- ) -> Result<Self> {
- let mut env = Environment::new();
- let syntax = SyntaxConfig::builder()
- .block_delimiters(
- envops.block_start_string.clone(),
- envops.block_end_string.clone(),
- )
- .variable_delimiters(
- envops.variable_start_string.clone(),
- envops.variable_end_string.clone(),
- )
- .comment_delimiters(
- envops.comment_start_string.clone(),
- envops.comment_end_string.clone(),
- )
- .keep_trailing_newline(envops.keep_trailing_newline)
- .trim_blocks(envops.trim_blocks)
- .lstrip_blocks(envops.lstrip_blocks)
- .build()
- .map_err(|e| RoneoError::InvalidConfig(format!("Invalid `_envops`: {e}")))?;
- env.set_syntax(syntax);
- // Copier never auto-escapes template outputs (MiniJinja defaults to JSON-escaping `.yml`/`.yaml`).
- env.set_auto_escape_callback(|_| minijinja::AutoEscape::None);
- if let Some(reader) = file_reader {
- let cache: RwLock<HashMap<String, Option<String>>> = RwLock::new(HashMap::new());
- env.set_loader(move |name| {
- if let Ok(guard) = cache.read()
- && let Some(cached) = guard.get(name)
- {
- return Ok(cached.clone());
- }
- let loaded = reader(name);
- if let Ok(mut guard) = cache.write() {
- guard.insert(name.to_string(), loaded.clone());
- }
- Ok(loaded)
- });
- }
- // Enable Python-compatible string/list/dict methods & extra Jinja2 utilities.
- minijinja_contrib::add_to_environment(&mut env);
- env.set_unknown_method_callback(minijinja_contrib::pycompat::unknown_method_callback);
- // Register Copier-specific filters & globals.
- env.add_global("UNSET", UNSET_SENTINEL);
- env.add_function("pathjoin", func_pathjoin);
- env.add_function("now", func_now);
- env.add_filter("format", filter_printf_format);
- env.add_filter("to_nice_yaml", filter_to_nice_yaml);
- env.add_filter("to_yaml", filter_to_nice_yaml);
- env.add_filter("from_yaml", filter_from_yaml);
- env.add_filter("to_json", filter_to_json);
- env.add_filter("to_nice_json", filter_to_nice_json);
- env.add_filter("from_json", filter_from_json);
- env.add_filter("slugify", filter_slugify);
- env.add_filter("to_snake", filter_to_snake);
- env.add_filter("snake_case", filter_to_snake);
- env.add_filter("to_kebab", filter_to_kebab);
- env.add_filter("kebab_case", filter_to_kebab);
- env.add_filter("to_camel", filter_to_camel);
- env.add_filter("camel_case", filter_to_camel);
- env.add_filter("to_pascal", filter_to_pascal);
- env.add_filter("pascal_case", filter_to_pascal);
- env.add_filter("b64encode", filter_b64encode);
- env.add_filter("b64decode", filter_b64decode);
- env.add_filter("to_bool", filter_to_bool);
- env.add_filter("basename", filter_basename);
- env.add_filter("dirname", filter_dirname);
- env.add_filter("quote", filter_shell_quote);
- if let (Some(reg), Some(init)) = (extensions, init_ctx) {
- reg.register_all(&mut env, init)?;
- }
- Ok(Self {
- env,
- var_start: envops.variable_start_string.clone(),
- block_start: envops.block_start_string.clone(),
- block_end: envops.block_end_string.clone(),
- comment_start: envops.comment_start_string.clone(),
- keep_trailing_newline: envops.keep_trailing_newline,
- })
- }
- /// Fast check: returns `true` when `template` contains none of the configured Jinja
- /// opening delimiters and therefore requires no parsing or evaluation.
- #[inline]
- fn is_plain_text(&self, template: &str) -> bool {
- !template.contains(self.var_start.as_str())
- && !template.contains(self.block_start.as_str())
- && !template.contains(self.comment_start.as_str())
- }
- /// Pre-convert a JSON context map into a reusable, thread-safe `minijinja::Value`
- /// (avoids re-converting large contexts on every file/path render).
- pub fn compile_context(ctx: &IndexMap<String, JsonValue>) -> MjValue {
- MjValue::from(minijinja::value::Serde(ctx))
- }
- /// Render a Jinja template string with the given context.
- pub fn render_str(
- &self,
- template: &str,
- ctx: &IndexMap<String, JsonValue>,
- label: &str,
- ) -> Result<String> {
- if self.is_plain_text(template) {
- return Ok(self.apply_plain_trailing_newline(template));
- }
- let normalized = normalize_jinja2_printf_modulo(template);
- self.env
- .render_named_str(label, normalized.as_ref(), minijinja::value::Serde(ctx))
- .map_err(|source| RoneoError::TemplateRender {
- context: label.to_string(),
- source,
- })
- }
- /// Render a Jinja template string using a pre-converted `minijinja::Value` context.
- pub fn render_str_value(&self, template: &str, ctx: &MjValue, label: &str) -> Result<String> {
- if self.is_plain_text(template) {
- return Ok(self.apply_plain_trailing_newline(template));
- }
- let normalized = normalize_jinja2_printf_modulo(template);
- self.env
- .render_named_str(label, normalized.as_ref(), ctx)
- .map_err(|source| RoneoError::TemplateRender {
- context: label.to_string(),
- source,
- })
- }
- #[inline]
- fn apply_plain_trailing_newline(&self, template: &str) -> String {
- if self.keep_trailing_newline {
- template.to_string()
- } else {
- template
- .strip_suffix("\r\n")
- .or_else(|| template.strip_suffix('\n'))
- .unwrap_or(template)
- .to_string()
- }
- }
- /// Evaluate a `when` condition (boolean literal or Jinja template string).
- pub fn eval_condition(
- &self,
- when: &JsonValue,
- ctx: &IndexMap<String, JsonValue>,
- label: &str,
- ) -> Result<bool> {
- match when {
- JsonValue::Bool(b) => Ok(*b),
- JsonValue::Null => Ok(true),
- JsonValue::String(s) => self.eval_condition_str(s, ctx, label),
- other => Ok(is_truthy_json(other)),
- }
- }
- pub fn eval_condition_str(
- &self,
- expr: &str,
- ctx: &IndexMap<String, JsonValue>,
- label: &str,
- ) -> Result<bool> {
- let rendered = self.render_str(expr, ctx, label)?;
- Ok(parse_truthy_str(&rendered))
- }
- /// Expand a single path segment, supporting Copier 9's `{% yield var from iterable %}...{% endyield %}`
- /// tag to generate multiple files/directories from one template entry.
- ///
- /// On ordinary segments (no `yield`), takes the zero-overhead single-segment fast path.
- #[allow(clippy::too_many_arguments)]
- pub fn render_segment_expanded_value(
- &self,
- raw_segment: &str,
- is_dir: bool,
- templates_suffix: &str,
- base_ctx: &IndexMap<String, JsonValue>,
- extra_vars: &[(String, JsonValue)],
- compiled_ctx: &MjValue,
- label: &str,
- ) -> Result<Vec<RenderedSegment>> {
- // Fast path: no `yield` keyword in segment.
- if !raw_segment.contains("yield") || !raw_segment.contains(self.block_start.as_str()) {
- let eff_ctx = if extra_vars.is_empty() {
- None
- } else {
- Some(Self::compile_context_with_extra(base_ctx, extra_vars))
- };
- let ctx_ref = eff_ctx.as_ref().unwrap_or(compiled_ctx);
- return match self.render_segment_value(
- raw_segment,
- is_dir,
- templates_suffix,
- ctx_ref,
- label,
- )? {
- Some((name, is_template_file)) => Ok(vec![RenderedSegment {
- name,
- is_template_file,
- yield_binding: None,
- }]),
- None => Ok(Vec::new()),
- };
- }
- let Some(parsed) = parse_yield_segment(raw_segment, &self.block_start, &self.block_end)?
- else {
- let eff_ctx = if extra_vars.is_empty() {
- None
- } else {
- Some(Self::compile_context_with_extra(base_ctx, extra_vars))
- };
- let ctx_ref = eff_ctx.as_ref().unwrap_or(compiled_ctx);
- return match self.render_segment_value(
- raw_segment,
- is_dir,
- templates_suffix,
- ctx_ref,
- label,
- )? {
- Some((name, is_template_file)) => Ok(vec![RenderedSegment {
- name,
- is_template_file,
- yield_binding: None,
- }]),
- None => Ok(Vec::new()),
- };
- };
- let eval_ctx = if extra_vars.is_empty() {
- None
- } else {
- Some(Self::compile_context_with_extra(base_ctx, extra_vars))
- };
- let iter_mj = self
- .env
- .compile_expression(parsed.iterable_expr)
- .and_then(|expr| expr.eval(eval_ctx.as_ref().unwrap_or(compiled_ctx)))
- .map_err(|source| RoneoError::TemplateRender {
- context: label.to_string(),
- source,
- })?;
- let iter = iter_mj
- .try_iter()
- .map_err(|source| RoneoError::TemplateRender {
- context: label.to_string(),
- source,
- })?;
- let item_template = format!("{}{}{}", parsed.prefix, parsed.body, parsed.suffix);
- let mut results = Vec::new();
- for item in iter {
- let item_json = serde_json::to_value(&item)?;
- let mut item_extra = extra_vars.to_vec();
- item_extra.push((parsed.var_name.to_string(), item_json.clone()));
- let item_ctx = Self::compile_context_with_extra(base_ctx, &item_extra);
- if let Some((name, is_template_file)) = self.render_segment_value(
- &item_template,
- is_dir,
- templates_suffix,
- &item_ctx,
- label,
- )? {
- results.push(RenderedSegment {
- name,
- is_template_file,
- yield_binding: Some((parsed.var_name.to_string(), item_json)),
- });
- }
- }
- Ok(results)
- }
- /// Build a `minijinja::Value` context overlaying `extra_vars` (from `{% yield %}`) onto `base_ctx`.
- pub fn compile_context_with_extra(
- base_ctx: &IndexMap<String, JsonValue>,
- extra_vars: &[(String, JsonValue)],
- ) -> MjValue {
- let mut merged = base_ctx.clone();
- for (k, v) in extra_vars {
- merged.insert(k.clone(), v.clone());
- }
- Self::compile_context(&merged)
- }
- /// Fast single-segment path renderer used during tree walks where parent directories
- /// have already been rendered once (avoids `O(files * depth)` re-rendering).
- pub fn render_segment_value(
- &self,
- raw_segment: &str,
- is_dir: bool,
- templates_suffix: &str,
- ctx: &MjValue,
- label: &str,
- ) -> Result<Option<(String, bool)>> {
- let mut rendered = if self.is_plain_text(raw_segment) {
- raw_segment.to_string()
- } else {
- self.render_str_value(raw_segment, ctx, label)?
- };
- let mut is_template_file = false;
- if !is_dir
- && !templates_suffix.is_empty()
- && let Some(stripped) = rendered.strip_suffix(templates_suffix)
- {
- rendered = stripped.to_string();
- is_template_file = true;
- }
- if rendered.is_empty() {
- return Ok(None);
- }
- // Security: never allow a rendered path segment to escape the destination directory.
- if rendered.contains('\0') {
- return Err(RoneoError::InvalidConfig(format!(
- "Rendered path '{rendered}' ({label}) contains a NUL byte"
- )));
- }
- let seg_path = Path::new(&rendered);
- if seg_path.is_absolute()
- || seg_path.components().any(|c| {
- matches!(
- c,
- Component::ParentDir | Component::RootDir | Component::Prefix(_)
- )
- })
- {
- return Err(RoneoError::InvalidConfig(format!(
- "Rendered path '{rendered}' ({label}) escapes destination directory"
- )));
- }
- Ok(Some((rendered, is_template_file)))
- }
- /// Render a relative template path segment-by-segment.
- ///
- /// Returns `Ok(None)` if any path component renders to an empty string (Copier convention
- /// for conditional files/directories like `{% if use_ci %}.github{% endif %}`).
- /// Also returns whether the final file had `templates_suffix` stripped.
- pub fn render_rel_path(
- &self,
- rel_path: &Path,
- is_dir: bool,
- templates_suffix: &str,
- ctx: &IndexMap<String, JsonValue>,
- ) -> Result<Option<(PathBuf, bool)>> {
- let compiled = Self::compile_context(ctx);
- self.render_rel_path_value(rel_path, is_dir, templates_suffix, &compiled)
- }
- /// Fast variant of `render_rel_path` accepting a pre-converted `minijinja::Value` context.
- pub fn render_rel_path_value(
- &self,
- rel_path: &Path,
- is_dir: bool,
- templates_suffix: &str,
- ctx: &MjValue,
- ) -> Result<Option<(PathBuf, bool)>> {
- let mut out = PathBuf::new();
- let components: Vec<_> = rel_path.components().collect();
- let last_idx = components.len().saturating_sub(1);
- let mut is_template_file = false;
- for (idx, comp) in components.iter().enumerate() {
- let Component::Normal(os_str) = comp else {
- continue;
- };
- let raw = os_str.to_string_lossy();
- let mut rendered = if self.is_plain_text(&raw) {
- raw.into_owned()
- } else {
- self.render_str_value(&raw, ctx, &format!("path:{}", rel_path.display()))?
- };
- if !is_dir
- && idx == last_idx
- && !templates_suffix.is_empty()
- && let Some(stripped) = rendered.strip_suffix(templates_suffix)
- {
- rendered = stripped.to_string();
- is_template_file = true;
- }
- if rendered.is_empty() {
- return Ok(None);
- }
- // A single rendered segment may itself expand to nested segments (e.g. `a/b`).
- out.push(rendered);
- }
- Ok(Some((out, is_template_file)))
- }
- }
- /// Build the full rendering context including `_copier_answers` and `_copier_conf`.
- pub fn build_render_context(
- combined_answers: &IndexMap<String, JsonValue>,
- persistable_answers: &IndexMap<String, JsonValue>,
- conf: &CopierConf,
- ) -> IndexMap<String, JsonValue> {
- let mut ctx = combined_answers.clone();
- if let Ok(val) = serde_json::to_value(persistable_answers) {
- ctx.insert("_copier_answers".into(), val);
- }
- if let Ok(val) = serde_json::to_value(conf) {
- ctx.insert("_copier_conf".into(), val);
- }
- ctx
- }
- #[allow(clippy::needless_pass_by_value)]
- fn filter_printf_format(fmt: &str, args: minijinja::value::Rest<MjValue>) -> String {
- let mut out = String::with_capacity(fmt.len());
- let mut chars = fmt.chars().peekable();
- let mut arg_idx = 0usize;
- while let Some(ch) = chars.next() {
- if ch == '%' {
- match chars.peek().copied() {
- Some('%') => {
- chars.next();
- out.push('%');
- }
- Some('s' | 'd' | 'i' | 'f' | 'r') => {
- chars.next();
- if let Some(val) = args.0.get(arg_idx) {
- out.push_str(&val.to_string());
- }
- arg_idx += 1;
- }
- _ => out.push('%'),
- }
- } else {
- out.push(ch);
- }
- }
- out
- }
- /// Lightweight compatibility rewrite for Python-style string `%` formatting inside Jinja expressions
- /// (e.g. `'25m %dMi' % openfga_memory_mib` -> `('25m %dMi' | format(openfga_memory_mib))`),
- /// which Jinja2 inherits from Python but `MiniJinja` does not overload on strings.
- fn normalize_jinja2_printf_modulo(src: &str) -> std::borrow::Cow<'_, str> {
- if !src.contains("% ") {
- return std::borrow::Cow::Borrowed(src);
- }
- let bytes = src.as_bytes();
- let mut out = String::with_capacity(src.len());
- let mut i = 0usize;
- let mut changed = false;
- while i < bytes.len() {
- if (bytes[i] == b'\'' || bytes[i] == b'"')
- && let Some((lit_end, has_spec)) = scan_quoted_literal(src, i)
- && has_spec
- {
- let mut j = lit_end;
- while j < bytes.len() && bytes[j].is_ascii_whitespace() {
- j += 1;
- }
- if j < bytes.len() && bytes[j] == b'%' && bytes.get(j + 1) != Some(&b'}') {
- let mut k = j + 1;
- while k < bytes.len() && bytes[k].is_ascii_whitespace() {
- k += 1;
- }
- let expr_start = k;
- while k < bytes.len()
- && (bytes[k].is_ascii_alphanumeric() || matches!(bytes[k], b'_' | b'.'))
- {
- k += 1;
- }
- if k > expr_start {
- out.push('(');
- out.push_str(&src[i..lit_end]);
- out.push_str(" | format(");
- out.push_str(&src[expr_start..k]);
- out.push_str("))");
- i = k;
- changed = true;
- continue;
- }
- }
- }
- let Some(ch) = src[i..].chars().next() else {
- break;
- };
- out.push(ch);
- i += ch.len_utf8();
- }
- if changed {
- std::borrow::Cow::Owned(out)
- } else {
- std::borrow::Cow::Borrowed(src)
- }
- }
- fn scan_quoted_literal(src: &str, start: usize) -> Option<(usize, bool)> {
- let bytes = src.as_bytes();
- let quote = bytes[start];
- let mut i = start + 1;
- let mut has_spec = false;
- while i < bytes.len() {
- let b = bytes[i];
- if b == b'\\' {
- i += 2;
- continue;
- }
- if b == b'%' && matches!(bytes.get(i + 1), Some(b's' | b'd' | b'i' | b'f' | b'r')) {
- has_spec = true;
- }
- if b == quote {
- return Some((i + 1, has_spec));
- }
- if b == b'\n' {
- return None;
- }
- i += 1;
- }
- None
- }
- fn func_pathjoin(parts: minijinja::value::Rest<String>) -> String {
- let mut path = PathBuf::new();
- for part in parts.0 {
- path.push(part);
- }
- path.to_string_lossy().into_owned()
- }
- #[allow(clippy::needless_pass_by_value)]
- fn filter_to_nice_yaml(
- value: &MjValue,
- kwargs: minijinja::value::Kwargs,
- ) -> std::result::Result<String, minijinja::Error> {
- let indent: usize = kwargs.get::<Option<usize>>("indent")?.unwrap_or(2);
- let _sort_keys: Option<bool> = kwargs.get("sort_keys")?;
- let json_val = serde_json::to_value(value).map_err(|e| {
- minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string())
- })?;
- let yaml = serde_yaml_ng::to_string(&json_val)
- .map(|s| s.trim_end().to_string())
- .map_err(|e| {
- minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string())
- })?;
- if indent == 2 || indent == 0 {
- return Ok(yaml);
- }
- // Scale 2-space leading indentation to custom `indent` (matches Copier `to_nice_yaml(indent=4)`).
- let mut scaled = String::with_capacity(yaml.len());
- for (idx, line) in yaml.lines().enumerate() {
- if idx > 0 {
- scaled.push('\n');
- }
- let spaces = line.bytes().take_while(|&b| b == b' ').count();
- let levels = spaces / 2;
- let rem = spaces % 2;
- for _ in 0..(levels * indent + rem) {
- scaled.push(' ');
- }
- scaled.push_str(&line[spaces..]);
- }
- Ok(scaled)
- }
- fn filter_from_yaml(value: &str) -> std::result::Result<MjValue, minijinja::Error> {
- let y: serde_yaml_ng::Value = serde_yaml_ng::from_str(value).map_err(|e| {
- minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string())
- })?;
- let j = serde_json::to_value(y).map_err(|e| {
- minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string())
- })?;
- Ok(MjValue::from(minijinja::value::Serde(&j)))
- }
- fn filter_to_json(value: &MjValue) -> std::result::Result<String, minijinja::Error> {
- serde_json::to_string(value)
- .map_err(|e| minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string()))
- }
- fn filter_to_nice_json(value: &MjValue) -> std::result::Result<String, minijinja::Error> {
- serde_json::to_string_pretty(value)
- .map_err(|e| minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string()))
- }
- fn filter_from_json(value: &str) -> std::result::Result<MjValue, minijinja::Error> {
- let j: JsonValue = serde_json::from_str(value).map_err(|e| {
- minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string())
- })?;
- Ok(MjValue::from(minijinja::value::Serde(&j)))
- }
- fn filter_slugify(value: &str) -> String {
- let mut out = String::with_capacity(value.len());
- let mut prev_dash = true;
- for ch in value.chars() {
- if ch.is_ascii_alphanumeric() {
- out.push(ch.to_ascii_lowercase());
- prev_dash = false;
- } else if !prev_dash {
- out.push('-');
- prev_dash = true;
- }
- }
- while out.ends_with('-') {
- out.pop();
- }
- out
- }
- fn filter_to_bool(value: &MjValue) -> bool {
- if let Ok(jv) = serde_json::to_value(value) {
- is_truthy_json(&jv)
- } else {
- value.is_true()
- }
- }
- fn filter_basename(value: String) -> String {
- Path::new(&value)
- .file_name()
- .map(|s| s.to_string_lossy().into_owned())
- .unwrap_or(value)
- }
- fn filter_dirname(value: &str) -> String {
- Path::new(value)
- .parent()
- .map_or_default(|s| s.to_string_lossy().into_owned())
- }
- fn filter_shell_quote(value: String) -> String {
- if value.is_empty() {
- return "''".to_string();
- }
- if value
- .chars()
- .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | ':' | '@' | '+'))
- {
- return value;
- }
- format!("'{}'", value.replace('\'', "'\"'\"'"))
- }
- pub fn parse_truthy_str(s: &str) -> bool {
- let normalized = s.trim().to_ascii_lowercase();
- !matches!(
- normalized.as_str(),
- "" | "0" | "false" | "no" | "n" | "off" | "none" | "null"
- )
- }
- pub fn is_truthy_json(v: &JsonValue) -> bool {
- match v {
- JsonValue::Null => false,
- JsonValue::Bool(b) => *b,
- JsonValue::Number(n) => n.as_f64().is_some_and(|f| f != 0.0),
- JsonValue::String(s) => parse_truthy_str(s),
- JsonValue::Array(a) => !a.is_empty(),
- JsonValue::Object(m) => !m.is_empty(),
- }
- }
- struct ParsedYield<'a> {
- prefix: &'a str,
- var_name: &'a str,
- iterable_expr: &'a str,
- body: &'a str,
- suffix: &'a str,
- }
- /// Parse Copier's `{% yield <var> from <iterable> %}<body>{% endyield %}` tag in a path segment.
- fn parse_yield_segment<'a>(
- segment: &'a str,
- block_start: &str,
- block_end: &str,
- ) -> Result<Option<ParsedYield<'a>>> {
- let mut search_from = 0usize;
- let mut found: Option<ParsedYield<'a>> = None;
- while let Some(rel_open) = segment[search_from..].find(block_start) {
- let open_pos = search_from + rel_open;
- let inner_start = open_pos + block_start.len();
- let Some(rel_close) = segment[inner_start..].find(block_end) else {
- break;
- };
- let close_pos = inner_start + rel_close;
- let tag_body = segment[inner_start..close_pos]
- .trim()
- .trim_start_matches('-')
- .trim_end_matches('-')
- .trim();
- let after_open = close_pos + block_end.len();
- if let Some(rest) = tag_body.strip_prefix("yield")
- && rest.starts_with(char::is_whitespace)
- {
- if found.is_some() {
- return Err(RoneoError::InvalidConfig(format!(
- "Only one `yield` tag is allowed per path segment: '{segment}'"
- )));
- }
- let rest = rest.trim();
- let Some((var_part, iter_part)) = rest.split_once(" from ") else {
- return Err(RoneoError::InvalidConfig(format!(
- "Invalid `yield` syntax in '{segment}': expected `yield <var> from <iterable>`"
- )));
- };
- let var_name = var_part.trim();
- let iterable_expr = iter_part.trim();
- if var_name.is_empty() || iterable_expr.is_empty() {
- return Err(RoneoError::InvalidConfig(format!(
- "Invalid `yield` syntax in '{segment}': missing variable or iterable"
- )));
- }
- // Locate matching `endyield` block.
- let mut end_search = after_open;
- let mut end_match: Option<(usize, usize)> = None;
- while let Some(end_open_offset) = segment[end_search..].find(block_start) {
- let end_open = end_search + end_open_offset;
- let end_inner = end_open + block_start.len();
- let Some(end_close_offset) = segment[end_inner..].find(block_end) else {
- break;
- };
- let end_close = end_inner + end_close_offset;
- let end_tag = segment[end_inner..end_close]
- .trim()
- .trim_start_matches('-')
- .trim_end_matches('-')
- .trim();
- let end_after = end_close + block_end.len();
- if end_tag == "endyield" {
- end_match = Some((end_open, end_after));
- break;
- }
- end_search = end_after;
- }
- let Some((body_end, suffix_start)) = end_match else {
- return Err(RoneoError::InvalidConfig(format!(
- "Unclosed `yield` tag in path segment '{segment}' (missing `endyield`)"
- )));
- };
- found = Some(ParsedYield {
- prefix: &segment[..open_pos],
- var_name,
- iterable_expr,
- body: &segment[after_open..body_end],
- suffix: &segment[suffix_start..],
- });
- search_from = suffix_start;
- continue;
- }
- search_from = after_open;
- }
- Ok(found)
- }
- fn split_words(input: &str) -> Vec<String> {
- let mut words = Vec::new();
- let mut current = String::new();
- let chars: Vec<char> = input.chars().collect();
- for (i, &ch) in chars.iter().enumerate() {
- if !ch.is_alphanumeric() {
- if !current.is_empty() {
- words.push(std::mem::take(&mut current));
- }
- continue;
- }
- let prev_lower = i > 0 && chars[i - 1].is_lowercase();
- let next_lower = i + 1 < chars.len() && chars[i + 1].is_lowercase();
- if ch.is_uppercase() && !current.is_empty() && (prev_lower || next_lower) {
- words.push(std::mem::take(&mut current));
- }
- current.extend(ch.to_lowercase());
- }
- if !current.is_empty() {
- words.push(current);
- }
- words
- }
- fn filter_to_snake(value: &str) -> String {
- split_words(value).join("_")
- }
- fn filter_to_kebab(value: &str) -> String {
- split_words(value).join("-")
- }
- fn filter_to_pascal(value: &str) -> String {
- let mut out = String::with_capacity(value.len());
- for word in split_words(value) {
- let mut chars = word.chars();
- if let Some(first) = chars.next() {
- out.extend(first.to_uppercase());
- out.push_str(chars.as_str());
- }
- }
- out
- }
- fn filter_to_camel(value: &str) -> String {
- let mut out = String::with_capacity(value.len());
- for (idx, word) in split_words(value).into_iter().enumerate() {
- if idx == 0 {
- out.push_str(&word);
- } else {
- let mut chars = word.chars();
- if let Some(first) = chars.next() {
- out.extend(first.to_uppercase());
- out.push_str(chars.as_str());
- }
- }
- }
- out
- }
- fn filter_b64encode(value: &str) -> String {
- const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- let bytes = value.as_bytes();
- let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
- for chunk in bytes.chunks(3) {
- let b0 = u32::from(chunk[0]);
- let b1 = chunk.get(1).copied().map_or(0, u32::from);
- let b2 = chunk.get(2).copied().map_or(0, u32::from);
- let triple = (b0 << 16) | (b1 << 8) | b2;
- out.push(TABLE[((triple >> 18) & 0x3f) as usize] as char);
- out.push(TABLE[((triple >> 12) & 0x3f) as usize] as char);
- if chunk.len() > 1 {
- out.push(TABLE[((triple >> 6) & 0x3f) as usize] as char);
- } else {
- out.push('=');
- }
- if chunk.len() > 2 {
- out.push(TABLE[(triple & 0x3f) as usize] as char);
- } else {
- out.push('=');
- }
- }
- out
- }
- fn filter_b64decode(value: &str) -> std::result::Result<String, minijinja::Error> {
- let mut buf = Vec::with_capacity(value.len() * 3 / 4);
- let mut accum = 0u32;
- let mut bits = 0u8;
- for b in value.bytes() {
- if b.is_ascii_whitespace() || b == b'=' {
- continue;
- }
- let val = match b {
- b'A'..=b'Z' => b - b'A',
- b'a'..=b'z' => b - b'a' + 26,
- b'0'..=b'9' => b - b'0' + 52,
- b'+' => 62,
- b'/' => 63,
- _ => {
- return Err(minijinja::Error::new(
- minijinja::ErrorKind::InvalidOperation,
- format!("Invalid base64 byte: {b}"),
- ));
- }
- };
- accum = (accum << 6) | u32::from(val);
- bits += 6;
- if bits >= 8 {
- bits -= 8;
- #[allow(clippy::cast_possible_truncation)]
- buf.push((accum >> bits) as u8);
- }
- }
- String::from_utf8(buf)
- .map_err(|e| minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string()))
- }
- /// Zero-dependency UTC `now(fmt="%Y-%m-%dT%H:%M:%SZ")` global using Howard Hinnant's
- /// civil-from-days algorithm.
- fn func_now(fmt: Option<&str>) -> String {
- let secs = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map_or(0, |d| d.as_secs());
- #[allow(clippy::cast_possible_wrap)]
- let days = (secs / 86_400) as i64;
- let day_secs = secs % 86_400;
- let hour = day_secs / 3_600;
- let minute = (day_secs % 3_600) / 60;
- let second = day_secs % 60;
- // Civil date from Unix epoch days (Howard Hinnant, public domain).
- let z = days + 719_468;
- let era = z.div_euclid(146_097);
- let doe = z.rem_euclid(146_097);
- let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
- let y = yoe + era * 400;
- let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
- let mp = (5 * doy + 2) / 153;
- let day = doy - (153 * mp + 2) / 5 + 1;
- let month = if mp < 10 { mp + 3 } else { mp - 9 };
- let year = if month <= 2 { y + 1 } else { y };
- let pattern = fmt.unwrap_or("%Y-%m-%dT%H:%M:%SZ");
- let mut out = String::with_capacity(pattern.len() + 8);
- let mut chars = pattern.chars().peekable();
- while let Some(ch) = chars.next() {
- if ch == '%' {
- match chars.peek().copied() {
- Some('Y') => {
- chars.next();
- let _ = write!(out, "{year:04}");
- }
- Some('m') => {
- chars.next();
- let _ = write!(out, "{month:02}");
- }
- Some('d') => {
- chars.next();
- let _ = write!(out, "{day:02}");
- }
- Some('H') => {
- chars.next();
- let _ = write!(out, "{hour:02}");
- }
- Some('M') => {
- chars.next();
- let _ = write!(out, "{minute:02}");
- }
- Some('S') => {
- chars.next();
- let _ = write!(out, "{second:02}");
- }
- Some('%') => {
- chars.next();
- out.push('%');
- }
- _ => out.push('%'),
- }
- } else {
- out.push(ch);
- }
- }
- out
- }