Skip to main content

ralph/template/variables/
substitute.rs

1//! Purpose: Apply resolved template-variable context to strings and tasks.
2//!
3//! Responsibilities:
4//! - Substitute supported variables in individual strings.
5//! - Apply substitution across all template-backed task fields.
6//!
7//! Scope:
8//! - Substitution only; no validation or context detection.
9//!
10//! Usage:
11//! - Called after validation and context detection during template loading.
12//!
13//! Invariants/Assumptions:
14//! - Unknown variables remain unchanged.
15//! - Missing context values leave their placeholders unchanged.
16//! - Field coverage remains aligned with the previous monolithic implementation.
17
18use crate::contracts::Task;
19
20use super::context::TemplateContext;
21
22/// Substitute variables in a template string.
23///
24/// Supported variables:
25/// - {{target}} - The target file/path provided by user
26/// - {{module}} - Module name derived from target
27/// - {{file}} - Filename only
28/// - {{branch}} - Current git branch name
29pub fn substitute_variables(input: &str, context: &TemplateContext) -> String {
30    let mut result = input.to_string();
31
32    if let Some(target) = &context.target {
33        result = result.replace("{{target}}", target);
34    }
35
36    if let Some(module) = &context.module {
37        result = result.replace("{{module}}", module);
38    }
39
40    if let Some(file) = &context.file {
41        result = result.replace("{{file}}", file);
42    }
43
44    if let Some(branch) = &context.branch {
45        result = result.replace("{{branch}}", branch);
46    }
47
48    result
49}
50
51/// Substitute variables in all string fields of a Task.
52pub fn substitute_variables_in_task(task: &mut Task, context: &TemplateContext) {
53    task.title = substitute_variables(&task.title, context);
54
55    for tag in &mut task.tags {
56        *tag = substitute_variables(tag, context);
57    }
58
59    for scope in &mut task.scope {
60        *scope = substitute_variables(scope, context);
61    }
62
63    for evidence in &mut task.evidence {
64        *evidence = substitute_variables(evidence, context);
65    }
66
67    for plan in &mut task.plan {
68        *plan = substitute_variables(plan, context);
69    }
70
71    for note in &mut task.notes {
72        *note = substitute_variables(note, context);
73    }
74
75    if let Some(request) = &mut task.request {
76        *request = substitute_variables(request, context);
77    }
78}