forgeFRENBrowse the repositories

roneocratesroneo-coresrcrenderer.rs

0518da6beb3fd562b82c5b5c2798b72e0d1591b2

At commit 0518da6

1 021 lines · 35.2 KiBRustRaw
  1. use std::collections::HashMap;
  2. use std::fmt::Write as _;
  3. use std::path::{Component, Path, PathBuf};
  4. use std::sync::RwLock;
  5. use indexmap::IndexMap;
  6. use minijinja::syntax::SyntaxConfig;
  7. use minijinja::{Environment, Value as MjValue};
  8. use serde_json::Value as JsonValue;
  9. use crate::config::EnvOps;
  10. use crate::error::{Result, RoneoError};
  11. use crate::plugin::{ExtensionInitContext, ExtensionRegistry, TemplateFileReader};
  12. /// Sentinel global matching Copier's `{{ UNSET }}` in question `default:` templates.
  13. pub const UNSET_SENTINEL: &str = "__RONEO_COPIER_UNSET_SENTINEL__";
  14. /// Metadata exposed as `_copier_conf` inside templates (Copier-compatible).
  15. #[derive(Debug, Clone, serde::Serialize)]
  16. pub struct CopierConf {
  17. pub src_path: String,
  18. pub dst_path: String,
  19. pub answers_file: String,
  20. pub vcs_ref: Option<String>,
  21. pub vcs_ref_hash: Option<String>,
  22. pub sep: String,
  23. pub os: String,
  24. pub stage: String,
  25. pub overwrite: bool,
  26. pub pretend: bool,
  27. pub quiet: bool,
  28. #[serde(rename = "unsafe")]
  29. pub r#unsafe: bool,
  30. pub cleanup_on_error: bool,
  31. pub context_lines: usize,
  32. pub exclude: Vec<String>,
  33. pub skip_if_exists: Vec<String>,
  34. }
  35. /// Result of rendering one path segment (supports Copier's `{% yield var from list %}`
  36. /// expanding a single template file or directory into multiple rendered destinations).
  37. #[derive(Debug, Clone)]
  38. pub struct RenderedSegment {
  39. pub name: String,
  40. pub is_template_file: bool,
  41. pub yield_binding: Option<(String, JsonValue)>,
  42. }
  43. /// Jinja2-compatible template rendering engine powered by `MiniJinja` + `pycompat`.
  44. pub struct TemplateRenderer {
  45. env: Environment<'static>,
  46. var_start: String,
  47. block_start: String,
  48. block_end: String,
  49. comment_start: String,
  50. keep_trailing_newline: bool,
  51. }
  52. impl TemplateRenderer {
  53. pub fn new(envops: &EnvOps) -> Result<Self> {
  54. Self::with_extensions(envops, None, None, None)
  55. }
  56. /// Create a renderer that supports `{% include "..." %}` via a cached file reader
  57. /// (works for both disk checkouts and in-memory `gix` trees) and optional extensions.
  58. pub fn with_extensions(
  59. envops: &EnvOps,
  60. file_reader: Option<TemplateFileReader>,
  61. extensions: Option<&ExtensionRegistry>,
  62. init_ctx: Option<&ExtensionInitContext>,
  63. ) -> Result<Self> {
  64. let mut env = Environment::new();
  65. let syntax = SyntaxConfig::builder()
  66. .block_delimiters(
  67. envops.block_start_string.clone(),
  68. envops.block_end_string.clone(),
  69. )
  70. .variable_delimiters(
  71. envops.variable_start_string.clone(),
  72. envops.variable_end_string.clone(),
  73. )
  74. .comment_delimiters(
  75. envops.comment_start_string.clone(),
  76. envops.comment_end_string.clone(),
  77. )
  78. .keep_trailing_newline(envops.keep_trailing_newline)
  79. .trim_blocks(envops.trim_blocks)
  80. .lstrip_blocks(envops.lstrip_blocks)
  81. .build()
  82. .map_err(|e| RoneoError::InvalidConfig(format!("Invalid `_envops`: {e}")))?;
  83. env.set_syntax(syntax);
  84. // Copier never auto-escapes template outputs (MiniJinja defaults to JSON-escaping `.yml`/`.yaml`).
  85. env.set_auto_escape_callback(|_| minijinja::AutoEscape::None);
  86. if let Some(reader) = file_reader {
  87. let cache: RwLock<HashMap<String, Option<String>>> = RwLock::new(HashMap::new());
  88. env.set_loader(move |name| {
  89. if let Ok(guard) = cache.read()
  90. && let Some(cached) = guard.get(name)
  91. {
  92. return Ok(cached.clone());
  93. }
  94. let loaded = reader(name);
  95. if let Ok(mut guard) = cache.write() {
  96. guard.insert(name.to_string(), loaded.clone());
  97. }
  98. Ok(loaded)
  99. });
  100. }
  101. // Enable Python-compatible string/list/dict methods & extra Jinja2 utilities.
  102. minijinja_contrib::add_to_environment(&mut env);
  103. env.set_unknown_method_callback(minijinja_contrib::pycompat::unknown_method_callback);
  104. // Register Copier-specific filters & globals.
  105. env.add_global("UNSET", UNSET_SENTINEL);
  106. env.add_function("pathjoin", func_pathjoin);
  107. env.add_function("now", func_now);
  108. env.add_filter("format", filter_printf_format);
  109. env.add_filter("to_nice_yaml", filter_to_nice_yaml);
  110. env.add_filter("to_yaml", filter_to_nice_yaml);
  111. env.add_filter("from_yaml", filter_from_yaml);
  112. env.add_filter("to_json", filter_to_json);
  113. env.add_filter("to_nice_json", filter_to_nice_json);
  114. env.add_filter("from_json", filter_from_json);
  115. env.add_filter("slugify", filter_slugify);
  116. env.add_filter("to_snake", filter_to_snake);
  117. env.add_filter("snake_case", filter_to_snake);
  118. env.add_filter("to_kebab", filter_to_kebab);
  119. env.add_filter("kebab_case", filter_to_kebab);
  120. env.add_filter("to_camel", filter_to_camel);
  121. env.add_filter("camel_case", filter_to_camel);
  122. env.add_filter("to_pascal", filter_to_pascal);
  123. env.add_filter("pascal_case", filter_to_pascal);
  124. env.add_filter("b64encode", filter_b64encode);
  125. env.add_filter("b64decode", filter_b64decode);
  126. env.add_filter("to_bool", filter_to_bool);
  127. env.add_filter("basename", filter_basename);
  128. env.add_filter("dirname", filter_dirname);
  129. env.add_filter("quote", filter_shell_quote);
  130. if let (Some(reg), Some(init)) = (extensions, init_ctx) {
  131. reg.register_all(&mut env, init)?;
  132. }
  133. Ok(Self {
  134. env,
  135. var_start: envops.variable_start_string.clone(),
  136. block_start: envops.block_start_string.clone(),
  137. block_end: envops.block_end_string.clone(),
  138. comment_start: envops.comment_start_string.clone(),
  139. keep_trailing_newline: envops.keep_trailing_newline,
  140. })
  141. }
  142. /// Fast check: returns `true` when `template` contains none of the configured Jinja
  143. /// opening delimiters and therefore requires no parsing or evaluation.
  144. #[inline]
  145. fn is_plain_text(&self, template: &str) -> bool {
  146. !template.contains(self.var_start.as_str())
  147. && !template.contains(self.block_start.as_str())
  148. && !template.contains(self.comment_start.as_str())
  149. }
  150. /// Pre-convert a JSON context map into a reusable, thread-safe `minijinja::Value`
  151. /// (avoids re-converting large contexts on every file/path render).
  152. pub fn compile_context(ctx: &IndexMap<String, JsonValue>) -> MjValue {
  153. MjValue::from(minijinja::value::Serde(ctx))
  154. }
  155. /// Render a Jinja template string with the given context.
  156. pub fn render_str(
  157. &self,
  158. template: &str,
  159. ctx: &IndexMap<String, JsonValue>,
  160. label: &str,
  161. ) -> Result<String> {
  162. if self.is_plain_text(template) {
  163. return Ok(self.apply_plain_trailing_newline(template));
  164. }
  165. let normalized = normalize_jinja2_printf_modulo(template);
  166. self.env
  167. .render_named_str(label, normalized.as_ref(), minijinja::value::Serde(ctx))
  168. .map_err(|source| RoneoError::TemplateRender {
  169. context: label.to_string(),
  170. source,
  171. })
  172. }
  173. /// Render a Jinja template string using a pre-converted `minijinja::Value` context.
  174. pub fn render_str_value(&self, template: &str, ctx: &MjValue, label: &str) -> Result<String> {
  175. if self.is_plain_text(template) {
  176. return Ok(self.apply_plain_trailing_newline(template));
  177. }
  178. let normalized = normalize_jinja2_printf_modulo(template);
  179. self.env
  180. .render_named_str(label, normalized.as_ref(), ctx)
  181. .map_err(|source| RoneoError::TemplateRender {
  182. context: label.to_string(),
  183. source,
  184. })
  185. }
  186. #[inline]
  187. fn apply_plain_trailing_newline(&self, template: &str) -> String {
  188. if self.keep_trailing_newline {
  189. template.to_string()
  190. } else {
  191. template
  192. .strip_suffix("\r\n")
  193. .or_else(|| template.strip_suffix('\n'))
  194. .unwrap_or(template)
  195. .to_string()
  196. }
  197. }
  198. /// Evaluate a `when` condition (boolean literal or Jinja template string).
  199. pub fn eval_condition(
  200. &self,
  201. when: &JsonValue,
  202. ctx: &IndexMap<String, JsonValue>,
  203. label: &str,
  204. ) -> Result<bool> {
  205. match when {
  206. JsonValue::Bool(b) => Ok(*b),
  207. JsonValue::Null => Ok(true),
  208. JsonValue::String(s) => self.eval_condition_str(s, ctx, label),
  209. other => Ok(is_truthy_json(other)),
  210. }
  211. }
  212. pub fn eval_condition_str(
  213. &self,
  214. expr: &str,
  215. ctx: &IndexMap<String, JsonValue>,
  216. label: &str,
  217. ) -> Result<bool> {
  218. let rendered = self.render_str(expr, ctx, label)?;
  219. Ok(parse_truthy_str(&rendered))
  220. }
  221. /// Expand a single path segment, supporting Copier 9's `{% yield var from iterable %}...{% endyield %}`
  222. /// tag to generate multiple files/directories from one template entry.
  223. ///
  224. /// On ordinary segments (no `yield`), takes the zero-overhead single-segment fast path.
  225. #[allow(clippy::too_many_arguments)]
  226. pub fn render_segment_expanded_value(
  227. &self,
  228. raw_segment: &str,
  229. is_dir: bool,
  230. templates_suffix: &str,
  231. base_ctx: &IndexMap<String, JsonValue>,
  232. extra_vars: &[(String, JsonValue)],
  233. compiled_ctx: &MjValue,
  234. label: &str,
  235. ) -> Result<Vec<RenderedSegment>> {
  236. // Fast path: no `yield` keyword in segment.
  237. if !raw_segment.contains("yield") || !raw_segment.contains(self.block_start.as_str()) {
  238. let eff_ctx = if extra_vars.is_empty() {
  239. None
  240. } else {
  241. Some(Self::compile_context_with_extra(base_ctx, extra_vars))
  242. };
  243. let ctx_ref = eff_ctx.as_ref().unwrap_or(compiled_ctx);
  244. return match self.render_segment_value(
  245. raw_segment,
  246. is_dir,
  247. templates_suffix,
  248. ctx_ref,
  249. label,
  250. )? {
  251. Some((name, is_template_file)) => Ok(vec![RenderedSegment {
  252. name,
  253. is_template_file,
  254. yield_binding: None,
  255. }]),
  256. None => Ok(Vec::new()),
  257. };
  258. }
  259. let Some(parsed) = parse_yield_segment(raw_segment, &self.block_start, &self.block_end)?
  260. else {
  261. let eff_ctx = if extra_vars.is_empty() {
  262. None
  263. } else {
  264. Some(Self::compile_context_with_extra(base_ctx, extra_vars))
  265. };
  266. let ctx_ref = eff_ctx.as_ref().unwrap_or(compiled_ctx);
  267. return match self.render_segment_value(
  268. raw_segment,
  269. is_dir,
  270. templates_suffix,
  271. ctx_ref,
  272. label,
  273. )? {
  274. Some((name, is_template_file)) => Ok(vec![RenderedSegment {
  275. name,
  276. is_template_file,
  277. yield_binding: None,
  278. }]),
  279. None => Ok(Vec::new()),
  280. };
  281. };
  282. let eval_ctx = if extra_vars.is_empty() {
  283. None
  284. } else {
  285. Some(Self::compile_context_with_extra(base_ctx, extra_vars))
  286. };
  287. let iter_mj = self
  288. .env
  289. .compile_expression(parsed.iterable_expr)
  290. .and_then(|expr| expr.eval(eval_ctx.as_ref().unwrap_or(compiled_ctx)))
  291. .map_err(|source| RoneoError::TemplateRender {
  292. context: label.to_string(),
  293. source,
  294. })?;
  295. let iter = iter_mj
  296. .try_iter()
  297. .map_err(|source| RoneoError::TemplateRender {
  298. context: label.to_string(),
  299. source,
  300. })?;
  301. let item_template = format!("{}{}{}", parsed.prefix, parsed.body, parsed.suffix);
  302. let mut results = Vec::new();
  303. for item in iter {
  304. let item_json = serde_json::to_value(&item)?;
  305. let mut item_extra = extra_vars.to_vec();
  306. item_extra.push((parsed.var_name.to_string(), item_json.clone()));
  307. let item_ctx = Self::compile_context_with_extra(base_ctx, &item_extra);
  308. if let Some((name, is_template_file)) = self.render_segment_value(
  309. &item_template,
  310. is_dir,
  311. templates_suffix,
  312. &item_ctx,
  313. label,
  314. )? {
  315. results.push(RenderedSegment {
  316. name,
  317. is_template_file,
  318. yield_binding: Some((parsed.var_name.to_string(), item_json)),
  319. });
  320. }
  321. }
  322. Ok(results)
  323. }
  324. /// Build a `minijinja::Value` context overlaying `extra_vars` (from `{% yield %}`) onto `base_ctx`.
  325. pub fn compile_context_with_extra(
  326. base_ctx: &IndexMap<String, JsonValue>,
  327. extra_vars: &[(String, JsonValue)],
  328. ) -> MjValue {
  329. let mut merged = base_ctx.clone();
  330. for (k, v) in extra_vars {
  331. merged.insert(k.clone(), v.clone());
  332. }
  333. Self::compile_context(&merged)
  334. }
  335. /// Fast single-segment path renderer used during tree walks where parent directories
  336. /// have already been rendered once (avoids `O(files * depth)` re-rendering).
  337. pub fn render_segment_value(
  338. &self,
  339. raw_segment: &str,
  340. is_dir: bool,
  341. templates_suffix: &str,
  342. ctx: &MjValue,
  343. label: &str,
  344. ) -> Result<Option<(String, bool)>> {
  345. let mut rendered = if self.is_plain_text(raw_segment) {
  346. raw_segment.to_string()
  347. } else {
  348. self.render_str_value(raw_segment, ctx, label)?
  349. };
  350. let mut is_template_file = false;
  351. if !is_dir
  352. && !templates_suffix.is_empty()
  353. && let Some(stripped) = rendered.strip_suffix(templates_suffix)
  354. {
  355. rendered = stripped.to_string();
  356. is_template_file = true;
  357. }
  358. if rendered.is_empty() {
  359. return Ok(None);
  360. }
  361. // Security: never allow a rendered path segment to escape the destination directory.
  362. if rendered.contains('\0') {
  363. return Err(RoneoError::InvalidConfig(format!(
  364. "Rendered path '{rendered}' ({label}) contains a NUL byte"
  365. )));
  366. }
  367. let seg_path = Path::new(&rendered);
  368. if seg_path.is_absolute()
  369. || seg_path.components().any(|c| {
  370. matches!(
  371. c,
  372. Component::ParentDir | Component::RootDir | Component::Prefix(_)
  373. )
  374. })
  375. {
  376. return Err(RoneoError::InvalidConfig(format!(
  377. "Rendered path '{rendered}' ({label}) escapes destination directory"
  378. )));
  379. }
  380. Ok(Some((rendered, is_template_file)))
  381. }
  382. /// Render a relative template path segment-by-segment.
  383. ///
  384. /// Returns `Ok(None)` if any path component renders to an empty string (Copier convention
  385. /// for conditional files/directories like `{% if use_ci %}.github{% endif %}`).
  386. /// Also returns whether the final file had `templates_suffix` stripped.
  387. pub fn render_rel_path(
  388. &self,
  389. rel_path: &Path,
  390. is_dir: bool,
  391. templates_suffix: &str,
  392. ctx: &IndexMap<String, JsonValue>,
  393. ) -> Result<Option<(PathBuf, bool)>> {
  394. let compiled = Self::compile_context(ctx);
  395. self.render_rel_path_value(rel_path, is_dir, templates_suffix, &compiled)
  396. }
  397. /// Fast variant of `render_rel_path` accepting a pre-converted `minijinja::Value` context.
  398. pub fn render_rel_path_value(
  399. &self,
  400. rel_path: &Path,
  401. is_dir: bool,
  402. templates_suffix: &str,
  403. ctx: &MjValue,
  404. ) -> Result<Option<(PathBuf, bool)>> {
  405. let mut out = PathBuf::new();
  406. let components: Vec<_> = rel_path.components().collect();
  407. let last_idx = components.len().saturating_sub(1);
  408. let mut is_template_file = false;
  409. for (idx, comp) in components.iter().enumerate() {
  410. let Component::Normal(os_str) = comp else {
  411. continue;
  412. };
  413. let raw = os_str.to_string_lossy();
  414. let mut rendered = if self.is_plain_text(&raw) {
  415. raw.into_owned()
  416. } else {
  417. self.render_str_value(&raw, ctx, &format!("path:{}", rel_path.display()))?
  418. };
  419. if !is_dir
  420. && idx == last_idx
  421. && !templates_suffix.is_empty()
  422. && let Some(stripped) = rendered.strip_suffix(templates_suffix)
  423. {
  424. rendered = stripped.to_string();
  425. is_template_file = true;
  426. }
  427. if rendered.is_empty() {
  428. return Ok(None);
  429. }
  430. // A single rendered segment may itself expand to nested segments (e.g. `a/b`).
  431. out.push(rendered);
  432. }
  433. Ok(Some((out, is_template_file)))
  434. }
  435. }
  436. /// Build the full rendering context including `_copier_answers` and `_copier_conf`.
  437. pub fn build_render_context(
  438. combined_answers: &IndexMap<String, JsonValue>,
  439. persistable_answers: &IndexMap<String, JsonValue>,
  440. conf: &CopierConf,
  441. ) -> IndexMap<String, JsonValue> {
  442. let mut ctx = combined_answers.clone();
  443. if let Ok(val) = serde_json::to_value(persistable_answers) {
  444. ctx.insert("_copier_answers".into(), val);
  445. }
  446. if let Ok(val) = serde_json::to_value(conf) {
  447. ctx.insert("_copier_conf".into(), val);
  448. }
  449. ctx
  450. }
  451. #[allow(clippy::needless_pass_by_value)]
  452. fn filter_printf_format(fmt: &str, args: minijinja::value::Rest<MjValue>) -> String {
  453. let mut out = String::with_capacity(fmt.len());
  454. let mut chars = fmt.chars().peekable();
  455. let mut arg_idx = 0usize;
  456. while let Some(ch) = chars.next() {
  457. if ch == '%' {
  458. match chars.peek().copied() {
  459. Some('%') => {
  460. chars.next();
  461. out.push('%');
  462. }
  463. Some('s' | 'd' | 'i' | 'f' | 'r') => {
  464. chars.next();
  465. if let Some(val) = args.0.get(arg_idx) {
  466. out.push_str(&val.to_string());
  467. }
  468. arg_idx += 1;
  469. }
  470. _ => out.push('%'),
  471. }
  472. } else {
  473. out.push(ch);
  474. }
  475. }
  476. out
  477. }
  478. /// Lightweight compatibility rewrite for Python-style string `%` formatting inside Jinja expressions
  479. /// (e.g. `'25m %dMi' % openfga_memory_mib` -> `('25m %dMi' | format(openfga_memory_mib))`),
  480. /// which Jinja2 inherits from Python but `MiniJinja` does not overload on strings.
  481. fn normalize_jinja2_printf_modulo(src: &str) -> std::borrow::Cow<'_, str> {
  482. if !src.contains("% ") {
  483. return std::borrow::Cow::Borrowed(src);
  484. }
  485. let bytes = src.as_bytes();
  486. let mut out = String::with_capacity(src.len());
  487. let mut i = 0usize;
  488. let mut changed = false;
  489. while i < bytes.len() {
  490. if (bytes[i] == b'\'' || bytes[i] == b'"')
  491. && let Some((lit_end, has_spec)) = scan_quoted_literal(src, i)
  492. && has_spec
  493. {
  494. let mut j = lit_end;
  495. while j < bytes.len() && bytes[j].is_ascii_whitespace() {
  496. j += 1;
  497. }
  498. if j < bytes.len() && bytes[j] == b'%' && bytes.get(j + 1) != Some(&b'}') {
  499. let mut k = j + 1;
  500. while k < bytes.len() && bytes[k].is_ascii_whitespace() {
  501. k += 1;
  502. }
  503. let expr_start = k;
  504. while k < bytes.len()
  505. && (bytes[k].is_ascii_alphanumeric() || matches!(bytes[k], b'_' | b'.'))
  506. {
  507. k += 1;
  508. }
  509. if k > expr_start {
  510. out.push('(');
  511. out.push_str(&src[i..lit_end]);
  512. out.push_str(" | format(");
  513. out.push_str(&src[expr_start..k]);
  514. out.push_str("))");
  515. i = k;
  516. changed = true;
  517. continue;
  518. }
  519. }
  520. }
  521. let Some(ch) = src[i..].chars().next() else {
  522. break;
  523. };
  524. out.push(ch);
  525. i += ch.len_utf8();
  526. }
  527. if changed {
  528. std::borrow::Cow::Owned(out)
  529. } else {
  530. std::borrow::Cow::Borrowed(src)
  531. }
  532. }
  533. fn scan_quoted_literal(src: &str, start: usize) -> Option<(usize, bool)> {
  534. let bytes = src.as_bytes();
  535. let quote = bytes[start];
  536. let mut i = start + 1;
  537. let mut has_spec = false;
  538. while i < bytes.len() {
  539. let b = bytes[i];
  540. if b == b'\\' {
  541. i += 2;
  542. continue;
  543. }
  544. if b == b'%' && matches!(bytes.get(i + 1), Some(b's' | b'd' | b'i' | b'f' | b'r')) {
  545. has_spec = true;
  546. }
  547. if b == quote {
  548. return Some((i + 1, has_spec));
  549. }
  550. if b == b'\n' {
  551. return None;
  552. }
  553. i += 1;
  554. }
  555. None
  556. }
  557. fn func_pathjoin(parts: minijinja::value::Rest<String>) -> String {
  558. let mut path = PathBuf::new();
  559. for part in parts.0 {
  560. path.push(part);
  561. }
  562. path.to_string_lossy().into_owned()
  563. }
  564. #[allow(clippy::needless_pass_by_value)]
  565. fn filter_to_nice_yaml(
  566. value: &MjValue,
  567. kwargs: minijinja::value::Kwargs,
  568. ) -> std::result::Result<String, minijinja::Error> {
  569. let indent: usize = kwargs.get::<Option<usize>>("indent")?.unwrap_or(2);
  570. let _sort_keys: Option<bool> = kwargs.get("sort_keys")?;
  571. let json_val = serde_json::to_value(value).map_err(|e| {
  572. minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string())
  573. })?;
  574. let yaml = serde_yaml_ng::to_string(&json_val)
  575. .map(|s| s.trim_end().to_string())
  576. .map_err(|e| {
  577. minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string())
  578. })?;
  579. if indent == 2 || indent == 0 {
  580. return Ok(yaml);
  581. }
  582. // Scale 2-space leading indentation to custom `indent` (matches Copier `to_nice_yaml(indent=4)`).
  583. let mut scaled = String::with_capacity(yaml.len());
  584. for (idx, line) in yaml.lines().enumerate() {
  585. if idx > 0 {
  586. scaled.push('\n');
  587. }
  588. let spaces = line.bytes().take_while(|&b| b == b' ').count();
  589. let levels = spaces / 2;
  590. let rem = spaces % 2;
  591. for _ in 0..(levels * indent + rem) {
  592. scaled.push(' ');
  593. }
  594. scaled.push_str(&line[spaces..]);
  595. }
  596. Ok(scaled)
  597. }
  598. fn filter_from_yaml(value: &str) -> std::result::Result<MjValue, minijinja::Error> {
  599. let y: serde_yaml_ng::Value = serde_yaml_ng::from_str(value).map_err(|e| {
  600. minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string())
  601. })?;
  602. let j = serde_json::to_value(y).map_err(|e| {
  603. minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string())
  604. })?;
  605. Ok(MjValue::from(minijinja::value::Serde(&j)))
  606. }
  607. fn filter_to_json(value: &MjValue) -> std::result::Result<String, minijinja::Error> {
  608. serde_json::to_string(value)
  609. .map_err(|e| minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string()))
  610. }
  611. fn filter_to_nice_json(value: &MjValue) -> std::result::Result<String, minijinja::Error> {
  612. serde_json::to_string_pretty(value)
  613. .map_err(|e| minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string()))
  614. }
  615. fn filter_from_json(value: &str) -> std::result::Result<MjValue, minijinja::Error> {
  616. let j: JsonValue = serde_json::from_str(value).map_err(|e| {
  617. minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string())
  618. })?;
  619. Ok(MjValue::from(minijinja::value::Serde(&j)))
  620. }
  621. fn filter_slugify(value: &str) -> String {
  622. let mut out = String::with_capacity(value.len());
  623. let mut prev_dash = true;
  624. for ch in value.chars() {
  625. if ch.is_ascii_alphanumeric() {
  626. out.push(ch.to_ascii_lowercase());
  627. prev_dash = false;
  628. } else if !prev_dash {
  629. out.push('-');
  630. prev_dash = true;
  631. }
  632. }
  633. while out.ends_with('-') {
  634. out.pop();
  635. }
  636. out
  637. }
  638. fn filter_to_bool(value: &MjValue) -> bool {
  639. if let Ok(jv) = serde_json::to_value(value) {
  640. is_truthy_json(&jv)
  641. } else {
  642. value.is_true()
  643. }
  644. }
  645. fn filter_basename(value: String) -> String {
  646. Path::new(&value)
  647. .file_name()
  648. .map(|s| s.to_string_lossy().into_owned())
  649. .unwrap_or(value)
  650. }
  651. fn filter_dirname(value: &str) -> String {
  652. Path::new(value)
  653. .parent()
  654. .map_or_default(|s| s.to_string_lossy().into_owned())
  655. }
  656. fn filter_shell_quote(value: String) -> String {
  657. if value.is_empty() {
  658. return "''".to_string();
  659. }
  660. if value
  661. .chars()
  662. .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | ':' | '@' | '+'))
  663. {
  664. return value;
  665. }
  666. format!("'{}'", value.replace('\'', "'\"'\"'"))
  667. }
  668. pub fn parse_truthy_str(s: &str) -> bool {
  669. let normalized = s.trim().to_ascii_lowercase();
  670. !matches!(
  671. normalized.as_str(),
  672. "" | "0" | "false" | "no" | "n" | "off" | "none" | "null"
  673. )
  674. }
  675. pub fn is_truthy_json(v: &JsonValue) -> bool {
  676. match v {
  677. JsonValue::Null => false,
  678. JsonValue::Bool(b) => *b,
  679. JsonValue::Number(n) => n.as_f64().is_some_and(|f| f != 0.0),
  680. JsonValue::String(s) => parse_truthy_str(s),
  681. JsonValue::Array(a) => !a.is_empty(),
  682. JsonValue::Object(m) => !m.is_empty(),
  683. }
  684. }
  685. struct ParsedYield<'a> {
  686. prefix: &'a str,
  687. var_name: &'a str,
  688. iterable_expr: &'a str,
  689. body: &'a str,
  690. suffix: &'a str,
  691. }
  692. /// Parse Copier's `{% yield <var> from <iterable> %}<body>{% endyield %}` tag in a path segment.
  693. fn parse_yield_segment<'a>(
  694. segment: &'a str,
  695. block_start: &str,
  696. block_end: &str,
  697. ) -> Result<Option<ParsedYield<'a>>> {
  698. let mut search_from = 0usize;
  699. let mut found: Option<ParsedYield<'a>> = None;
  700. while let Some(rel_open) = segment[search_from..].find(block_start) {
  701. let open_pos = search_from + rel_open;
  702. let inner_start = open_pos + block_start.len();
  703. let Some(rel_close) = segment[inner_start..].find(block_end) else {
  704. break;
  705. };
  706. let close_pos = inner_start + rel_close;
  707. let tag_body = segment[inner_start..close_pos]
  708. .trim()
  709. .trim_start_matches('-')
  710. .trim_end_matches('-')
  711. .trim();
  712. let after_open = close_pos + block_end.len();
  713. if let Some(rest) = tag_body.strip_prefix("yield")
  714. && rest.starts_with(char::is_whitespace)
  715. {
  716. if found.is_some() {
  717. return Err(RoneoError::InvalidConfig(format!(
  718. "Only one `yield` tag is allowed per path segment: '{segment}'"
  719. )));
  720. }
  721. let rest = rest.trim();
  722. let Some((var_part, iter_part)) = rest.split_once(" from ") else {
  723. return Err(RoneoError::InvalidConfig(format!(
  724. "Invalid `yield` syntax in '{segment}': expected `yield <var> from <iterable>`"
  725. )));
  726. };
  727. let var_name = var_part.trim();
  728. let iterable_expr = iter_part.trim();
  729. if var_name.is_empty() || iterable_expr.is_empty() {
  730. return Err(RoneoError::InvalidConfig(format!(
  731. "Invalid `yield` syntax in '{segment}': missing variable or iterable"
  732. )));
  733. }
  734. // Locate matching `endyield` block.
  735. let mut end_search = after_open;
  736. let mut end_match: Option<(usize, usize)> = None;
  737. while let Some(end_open_offset) = segment[end_search..].find(block_start) {
  738. let end_open = end_search + end_open_offset;
  739. let end_inner = end_open + block_start.len();
  740. let Some(end_close_offset) = segment[end_inner..].find(block_end) else {
  741. break;
  742. };
  743. let end_close = end_inner + end_close_offset;
  744. let end_tag = segment[end_inner..end_close]
  745. .trim()
  746. .trim_start_matches('-')
  747. .trim_end_matches('-')
  748. .trim();
  749. let end_after = end_close + block_end.len();
  750. if end_tag == "endyield" {
  751. end_match = Some((end_open, end_after));
  752. break;
  753. }
  754. end_search = end_after;
  755. }
  756. let Some((body_end, suffix_start)) = end_match else {
  757. return Err(RoneoError::InvalidConfig(format!(
  758. "Unclosed `yield` tag in path segment '{segment}' (missing `endyield`)"
  759. )));
  760. };
  761. found = Some(ParsedYield {
  762. prefix: &segment[..open_pos],
  763. var_name,
  764. iterable_expr,
  765. body: &segment[after_open..body_end],
  766. suffix: &segment[suffix_start..],
  767. });
  768. search_from = suffix_start;
  769. continue;
  770. }
  771. search_from = after_open;
  772. }
  773. Ok(found)
  774. }
  775. fn split_words(input: &str) -> Vec<String> {
  776. let mut words = Vec::new();
  777. let mut current = String::new();
  778. let chars: Vec<char> = input.chars().collect();
  779. for (i, &ch) in chars.iter().enumerate() {
  780. if !ch.is_alphanumeric() {
  781. if !current.is_empty() {
  782. words.push(std::mem::take(&mut current));
  783. }
  784. continue;
  785. }
  786. let prev_lower = i > 0 && chars[i - 1].is_lowercase();
  787. let next_lower = i + 1 < chars.len() && chars[i + 1].is_lowercase();
  788. if ch.is_uppercase() && !current.is_empty() && (prev_lower || next_lower) {
  789. words.push(std::mem::take(&mut current));
  790. }
  791. current.extend(ch.to_lowercase());
  792. }
  793. if !current.is_empty() {
  794. words.push(current);
  795. }
  796. words
  797. }
  798. fn filter_to_snake(value: &str) -> String {
  799. split_words(value).join("_")
  800. }
  801. fn filter_to_kebab(value: &str) -> String {
  802. split_words(value).join("-")
  803. }
  804. fn filter_to_pascal(value: &str) -> String {
  805. let mut out = String::with_capacity(value.len());
  806. for word in split_words(value) {
  807. let mut chars = word.chars();
  808. if let Some(first) = chars.next() {
  809. out.extend(first.to_uppercase());
  810. out.push_str(chars.as_str());
  811. }
  812. }
  813. out
  814. }
  815. fn filter_to_camel(value: &str) -> String {
  816. let mut out = String::with_capacity(value.len());
  817. for (idx, word) in split_words(value).into_iter().enumerate() {
  818. if idx == 0 {
  819. out.push_str(&word);
  820. } else {
  821. let mut chars = word.chars();
  822. if let Some(first) = chars.next() {
  823. out.extend(first.to_uppercase());
  824. out.push_str(chars.as_str());
  825. }
  826. }
  827. }
  828. out
  829. }
  830. fn filter_b64encode(value: &str) -> String {
  831. const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  832. let bytes = value.as_bytes();
  833. let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
  834. for chunk in bytes.chunks(3) {
  835. let b0 = u32::from(chunk[0]);
  836. let b1 = chunk.get(1).copied().map_or(0, u32::from);
  837. let b2 = chunk.get(2).copied().map_or(0, u32::from);
  838. let triple = (b0 << 16) | (b1 << 8) | b2;
  839. out.push(TABLE[((triple >> 18) & 0x3f) as usize] as char);
  840. out.push(TABLE[((triple >> 12) & 0x3f) as usize] as char);
  841. if chunk.len() > 1 {
  842. out.push(TABLE[((triple >> 6) & 0x3f) as usize] as char);
  843. } else {
  844. out.push('=');
  845. }
  846. if chunk.len() > 2 {
  847. out.push(TABLE[(triple & 0x3f) as usize] as char);
  848. } else {
  849. out.push('=');
  850. }
  851. }
  852. out
  853. }
  854. fn filter_b64decode(value: &str) -> std::result::Result<String, minijinja::Error> {
  855. let mut buf = Vec::with_capacity(value.len() * 3 / 4);
  856. let mut accum = 0u32;
  857. let mut bits = 0u8;
  858. for b in value.bytes() {
  859. if b.is_ascii_whitespace() || b == b'=' {
  860. continue;
  861. }
  862. let val = match b {
  863. b'A'..=b'Z' => b - b'A',
  864. b'a'..=b'z' => b - b'a' + 26,
  865. b'0'..=b'9' => b - b'0' + 52,
  866. b'+' => 62,
  867. b'/' => 63,
  868. _ => {
  869. return Err(minijinja::Error::new(
  870. minijinja::ErrorKind::InvalidOperation,
  871. format!("Invalid base64 byte: {b}"),
  872. ));
  873. }
  874. };
  875. accum = (accum << 6) | u32::from(val);
  876. bits += 6;
  877. if bits >= 8 {
  878. bits -= 8;
  879. #[allow(clippy::cast_possible_truncation)]
  880. buf.push((accum >> bits) as u8);
  881. }
  882. }
  883. String::from_utf8(buf)
  884. .map_err(|e| minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string()))
  885. }
  886. /// Zero-dependency UTC `now(fmt="%Y-%m-%dT%H:%M:%SZ")` global using Howard Hinnant's
  887. /// civil-from-days algorithm.
  888. fn func_now(fmt: Option<&str>) -> String {
  889. let secs = std::time::SystemTime::now()
  890. .duration_since(std::time::UNIX_EPOCH)
  891. .map_or(0, |d| d.as_secs());
  892. #[allow(clippy::cast_possible_wrap)]
  893. let days = (secs / 86_400) as i64;
  894. let day_secs = secs % 86_400;
  895. let hour = day_secs / 3_600;
  896. let minute = (day_secs % 3_600) / 60;
  897. let second = day_secs % 60;
  898. // Civil date from Unix epoch days (Howard Hinnant, public domain).
  899. let z = days + 719_468;
  900. let era = z.div_euclid(146_097);
  901. let doe = z.rem_euclid(146_097);
  902. let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
  903. let y = yoe + era * 400;
  904. let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
  905. let mp = (5 * doy + 2) / 153;
  906. let day = doy - (153 * mp + 2) / 5 + 1;
  907. let month = if mp < 10 { mp + 3 } else { mp - 9 };
  908. let year = if month <= 2 { y + 1 } else { y };
  909. let pattern = fmt.unwrap_or("%Y-%m-%dT%H:%M:%SZ");
  910. let mut out = String::with_capacity(pattern.len() + 8);
  911. let mut chars = pattern.chars().peekable();
  912. while let Some(ch) = chars.next() {
  913. if ch == '%' {
  914. match chars.peek().copied() {
  915. Some('Y') => {
  916. chars.next();
  917. let _ = write!(out, "{year:04}");
  918. }
  919. Some('m') => {
  920. chars.next();
  921. let _ = write!(out, "{month:02}");
  922. }
  923. Some('d') => {
  924. chars.next();
  925. let _ = write!(out, "{day:02}");
  926. }
  927. Some('H') => {
  928. chars.next();
  929. let _ = write!(out, "{hour:02}");
  930. }
  931. Some('M') => {
  932. chars.next();
  933. let _ = write!(out, "{minute:02}");
  934. }
  935. Some('S') => {
  936. chars.next();
  937. let _ = write!(out, "{second:02}");
  938. }
  939. Some('%') => {
  940. chars.next();
  941. out.push('%');
  942. }
  943. _ => out.push('%'),
  944. }
  945. } else {
  946. out.push(ch);
  947. }
  948. }
  949. out
  950. }