tmpltool 1.5.0

A fast and simple command-line template rendering tool using MiniJinja templates with environment variables
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! Array functions that support both function and filter syntax.
//!
//! # Function Syntax
//! ```jinja
//! {{ array_sum(array=numbers) }}
//! {{ array_unique(array=items) }}
//! ```
//!
//! # Filter Syntax
//! ```jinja
//! {{ numbers | array_sum }}
//! {{ items | array_unique }}
//! ```
//!
//! # Chaining
//! ```jinja
//! {{ items | array_unique | array_sum }}
//! ```

use super::FilterFunction;
use crate::functions::metadata::{ArgumentMetadata, FunctionMetadata, SyntaxVariants};
use minijinja::value::Kwargs;
use minijinja::{Error, ErrorKind, Value};
use std::collections::HashSet;

/// Common metadata for single-argument array functions
const ARRAY_ARG: ArgumentMetadata = ArgumentMetadata {
    name: "array",
    arg_type: "array",
    required: true,
    default: None,
    description: "The array to process",
};

/// Helper to extract array from Value
fn extract_array(value: &Value, fn_name: &str) -> Result<Value, Error> {
    if !matches!(value.kind(), minijinja::value::ValueKind::Seq) {
        return Err(Error::new(
            ErrorKind::InvalidOperation,
            format!("{} requires an array", fn_name),
        ));
    }
    Ok(value.clone())
}

/// Helper to convert Value item to f64
fn value_to_f64(item: &Value, fn_name: &str) -> Result<f64, Error> {
    let json_value: serde_json::Value = serde_json::to_value(item).map_err(|e| {
        Error::new(
            ErrorKind::InvalidOperation,
            format!("Failed to convert value: {}", e),
        )
    })?;

    json_value.as_f64().ok_or_else(|| {
        Error::new(
            ErrorKind::InvalidOperation,
            format!("{} requires numeric values, found: {}", fn_name, item),
        )
    })
}

/// Helper to format result as integer if possible
fn format_number(num: f64) -> Value {
    if num.fract() == 0.0 {
        Value::from(num as i64)
    } else {
        Value::from(num)
    }
}

// ============================================
// ArraySum
// ============================================

/// Calculate sum of array values.
pub struct ArraySum;

impl ArraySum {
    fn compute(array: &Value) -> Result<Value, Error> {
        let mut sum = 0.0_f64;

        if let Ok(seq) = array.try_iter() {
            for item in seq {
                sum += value_to_f64(&item, "array_sum")?;
            }
        }

        Ok(format_number(sum))
    }
}

impl FilterFunction for ArraySum {
    const NAME: &'static str = "array_sum";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "array_sum",
        category: "array",
        description: "Calculate sum of array values",
        arguments: &[ARRAY_ARG],
        return_type: "number",
        examples: &[
            "{{ array_sum(array=numbers) }}",
            "{{ [1, 2, 3, 4, 5] | array_sum }}",
        ],
        syntax: SyntaxVariants::FUNCTION_AND_FILTER,
    };

    fn call_as_function(kwargs: Kwargs) -> Result<Value, Error> {
        let array: Value = kwargs.get("array")?;
        extract_array(&array, "array_sum")?;
        Self::compute(&array)
    }

    fn call_as_filter(value: &Value, _kwargs: Kwargs) -> Result<Value, Error> {
        extract_array(value, "array_sum")?;
        Self::compute(value)
    }
}

// ============================================
// ArrayAvg
// ============================================

/// Calculate average of array values.
pub struct ArrayAvg;

impl ArrayAvg {
    fn compute(array: &Value) -> Result<Value, Error> {
        let mut sum = 0.0_f64;
        let mut count = 0;

        if let Ok(seq) = array.try_iter() {
            for item in seq {
                sum += value_to_f64(&item, "array_avg")?;
                count += 1;
            }
        }

        if count == 0 {
            return Ok(Value::from(0));
        }

        Ok(format_number(sum / count as f64))
    }
}

impl FilterFunction for ArrayAvg {
    const NAME: &'static str = "array_avg";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "array_avg",
        category: "array",
        description: "Calculate average of array values",
        arguments: &[ARRAY_ARG],
        return_type: "number",
        examples: &["{{ array_avg(array=numbers) }}", "{{ scores | array_avg }}"],
        syntax: SyntaxVariants::FUNCTION_AND_FILTER,
    };

    fn call_as_function(kwargs: Kwargs) -> Result<Value, Error> {
        let array: Value = kwargs.get("array")?;
        extract_array(&array, "array_avg")?;
        Self::compute(&array)
    }

    fn call_as_filter(value: &Value, _kwargs: Kwargs) -> Result<Value, Error> {
        extract_array(value, "array_avg")?;
        Self::compute(value)
    }
}

// ============================================
// ArrayMedian
// ============================================

/// Calculate median of array values.
pub struct ArrayMedian;

impl ArrayMedian {
    fn compute(array: &Value) -> Result<Value, Error> {
        let mut numbers: Vec<f64> = Vec::new();

        if let Ok(seq) = array.try_iter() {
            for item in seq {
                numbers.push(value_to_f64(&item, "array_median")?);
            }
        }

        if numbers.is_empty() {
            return Ok(Value::from(0));
        }

        numbers.sort_by(|a, b| a.partial_cmp(b).unwrap());

        let len = numbers.len();
        let median = if len.is_multiple_of(2) {
            // Even length: average of two middle values
            (numbers[len / 2 - 1] + numbers[len / 2]) / 2.0
        } else {
            // Odd length: middle value
            numbers[len / 2]
        };

        Ok(format_number(median))
    }
}

impl FilterFunction for ArrayMedian {
    const NAME: &'static str = "array_median";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "array_median",
        category: "array",
        description: "Calculate median of array values",
        arguments: &[ARRAY_ARG],
        return_type: "number",
        examples: &[
            "{{ array_median(array=numbers) }}",
            "{{ [1, 3, 5, 7, 9] | array_median }}",
        ],
        syntax: SyntaxVariants::FUNCTION_AND_FILTER,
    };

    fn call_as_function(kwargs: Kwargs) -> Result<Value, Error> {
        let array: Value = kwargs.get("array")?;
        extract_array(&array, "array_median")?;
        Self::compute(&array)
    }

    fn call_as_filter(value: &Value, _kwargs: Kwargs) -> Result<Value, Error> {
        extract_array(value, "array_median")?;
        Self::compute(value)
    }
}

// ============================================
// ArrayMin
// ============================================

/// Find minimum value in array.
pub struct ArrayMin;

impl ArrayMin {
    fn compute(array: &Value) -> Result<Value, Error> {
        let mut min_value: Option<f64> = None;

        if let Ok(seq) = array.try_iter() {
            for item in seq {
                let num = value_to_f64(&item, "array_min")?;
                min_value = Some(match min_value {
                    None => num,
                    Some(current_min) => num.min(current_min),
                });
            }
        }

        match min_value {
            None => Err(Error::new(
                ErrorKind::InvalidOperation,
                "array_min requires a non-empty array",
            )),
            Some(min) => Ok(format_number(min)),
        }
    }
}

impl FilterFunction for ArrayMin {
    const NAME: &'static str = "array_min";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "array_min",
        category: "array",
        description: "Find minimum value in array",
        arguments: &[ARRAY_ARG],
        return_type: "number",
        examples: &["{{ array_min(array=numbers) }}", "{{ prices | array_min }}"],
        syntax: SyntaxVariants::FUNCTION_AND_FILTER,
    };

    fn call_as_function(kwargs: Kwargs) -> Result<Value, Error> {
        let array: Value = kwargs.get("array")?;
        extract_array(&array, "array_min")?;
        Self::compute(&array)
    }

    fn call_as_filter(value: &Value, _kwargs: Kwargs) -> Result<Value, Error> {
        extract_array(value, "array_min")?;
        Self::compute(value)
    }
}

// ============================================
// ArrayMax
// ============================================

/// Find maximum value in array.
pub struct ArrayMax;

impl ArrayMax {
    fn compute(array: &Value) -> Result<Value, Error> {
        let mut max_value: Option<f64> = None;

        if let Ok(seq) = array.try_iter() {
            for item in seq {
                let num = value_to_f64(&item, "array_max")?;
                max_value = Some(match max_value {
                    None => num,
                    Some(current_max) => num.max(current_max),
                });
            }
        }

        match max_value {
            None => Err(Error::new(
                ErrorKind::InvalidOperation,
                "array_max requires a non-empty array",
            )),
            Some(max) => Ok(format_number(max)),
        }
    }
}

impl FilterFunction for ArrayMax {
    const NAME: &'static str = "array_max";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "array_max",
        category: "array",
        description: "Find maximum value in array",
        arguments: &[ARRAY_ARG],
        return_type: "number",
        examples: &["{{ array_max(array=numbers) }}", "{{ prices | array_max }}"],
        syntax: SyntaxVariants::FUNCTION_AND_FILTER,
    };

    fn call_as_function(kwargs: Kwargs) -> Result<Value, Error> {
        let array: Value = kwargs.get("array")?;
        extract_array(&array, "array_max")?;
        Self::compute(&array)
    }

    fn call_as_filter(value: &Value, _kwargs: Kwargs) -> Result<Value, Error> {
        extract_array(value, "array_max")?;
        Self::compute(value)
    }
}

// ============================================
// ArrayUnique
// ============================================

/// Remove duplicate values from array.
pub struct ArrayUnique;

impl ArrayUnique {
    fn compute(array: &Value) -> Result<Value, Error> {
        let mut seen: HashSet<String> = HashSet::new();
        let mut unique: Vec<serde_json::Value> = Vec::new();

        if let Ok(seq) = array.try_iter() {
            for item in seq {
                let json_value: serde_json::Value = serde_json::to_value(&item).map_err(|e| {
                    Error::new(
                        ErrorKind::InvalidOperation,
                        format!("Failed to convert item: {}", e),
                    )
                })?;

                // Create a string representation for comparison
                let item_str = serde_json::to_string(&json_value).unwrap_or_default();

                if seen.insert(item_str) {
                    unique.push(json_value);
                }
            }
        }

        Ok(Value::from_serialize(unique))
    }
}

impl FilterFunction for ArrayUnique {
    const NAME: &'static str = "array_unique";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "array_unique",
        category: "array",
        description: "Remove duplicate values from array",
        arguments: &[ARRAY_ARG],
        return_type: "array",
        examples: &[
            "{{ array_unique(array=items) }}",
            "{{ [1, 2, 2, 3, 3, 3] | array_unique }}",
        ],
        syntax: SyntaxVariants::FUNCTION_AND_FILTER,
    };

    fn call_as_function(kwargs: Kwargs) -> Result<Value, Error> {
        let array: Value = kwargs.get("array")?;
        extract_array(&array, "array_unique")?;
        Self::compute(&array)
    }

    fn call_as_filter(value: &Value, _kwargs: Kwargs) -> Result<Value, Error> {
        extract_array(value, "array_unique")?;
        Self::compute(value)
    }
}

// ============================================
// ArrayFlatten
// ============================================

/// Flatten nested arrays by one level.
pub struct ArrayFlatten;

impl ArrayFlatten {
    fn compute(array: &Value) -> Result<Value, Error> {
        let mut flattened: Vec<serde_json::Value> = Vec::new();

        if let Ok(seq) = array.try_iter() {
            for item in seq {
                let json_value: serde_json::Value = serde_json::to_value(&item).map_err(|e| {
                    Error::new(
                        ErrorKind::InvalidOperation,
                        format!("Failed to convert item: {}", e),
                    )
                })?;

                // If item is an array, flatten it one level
                if let Some(nested_array) = json_value.as_array() {
                    for nested_item in nested_array {
                        flattened.push(nested_item.clone());
                    }
                } else {
                    // Not an array, just add the item
                    flattened.push(json_value);
                }
            }
        }

        Ok(Value::from_serialize(flattened))
    }
}

impl FilterFunction for ArrayFlatten {
    const NAME: &'static str = "array_flatten";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "array_flatten",
        category: "array",
        description: "Flatten nested arrays by one level",
        arguments: &[ARRAY_ARG],
        return_type: "array",
        examples: &[
            "{{ array_flatten(array=nested) }}",
            "{{ [[1, 2], [3, 4]] | array_flatten }}",
        ],
        syntax: SyntaxVariants::FUNCTION_AND_FILTER,
    };

    fn call_as_function(kwargs: Kwargs) -> Result<Value, Error> {
        let array: Value = kwargs.get("array")?;
        extract_array(&array, "array_flatten")?;
        Self::compute(&array)
    }

    fn call_as_filter(value: &Value, _kwargs: Kwargs) -> Result<Value, Error> {
        extract_array(value, "array_flatten")?;
        Self::compute(value)
    }
}