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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! Serialization functions that support both function and filter syntax.
//!
//! # Function Syntax
//! ```jinja
//! {{ to_json(object=config) }}
//! {{ to_yaml(object=config) }}
//! {{ parse_json(string='{"key": "value"}') }}
//! ```
//!
//! # Filter Syntax
//! ```jinja
//! {{ config | to_json }}
//! {{ config | to_yaml }}
//! {{ '{"key": "value"}' | parse_json }}
//! ```
//!
//! # Chaining
//! ```jinja
//! {{ config | to_json | base64_encode }}
//! ```

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

/// Common metadata for object argument (serialization)
const OBJECT_ARG: ArgumentMetadata = ArgumentMetadata {
    name: "object",
    arg_type: "any",
    required: true,
    default: None,
    description: "The value to serialize",
};

/// Common metadata for string argument (parsing)
const STRING_ARG: ArgumentMetadata = ArgumentMetadata {
    name: "string",
    arg_type: "string",
    required: true,
    default: None,
    description: "The string to parse",
};

// ============================================
// Serialization (Object -> String)
// ============================================

/// Convert object to JSON string.
///
/// # Function Syntax
/// ```jinja
/// {{ to_json(object=config) }}
/// {{ to_json(object=config, pretty=true) }}
/// ```
///
/// # Filter Syntax
/// ```jinja
/// {{ config | to_json }}
/// {{ config | to_json(pretty=true) }}
/// ```
pub struct ToJson;

impl ToJson {
    fn serialize(value: &Value, pretty: bool) -> Result<String, Error> {
        // Convert MiniJinja Value to serde_json::Value
        let json_value: serde_json::Value = serde_json::to_value(value).map_err(|e| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("Failed to convert to JSON: {}", e),
            )
        })?;

        // Serialize to JSON string
        if pretty {
            serde_json::to_string_pretty(&json_value).map_err(|e| {
                Error::new(
                    ErrorKind::InvalidOperation,
                    format!("Failed to serialize to JSON: {}", e),
                )
            })
        } else {
            serde_json::to_string(&json_value).map_err(|e| {
                Error::new(
                    ErrorKind::InvalidOperation,
                    format!("Failed to serialize to JSON: {}", e),
                )
            })
        }
    }
}

impl FilterFunction for ToJson {
    const NAME: &'static str = "to_json";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "to_json",
        category: "serialization",
        description: "Convert object to JSON string",
        arguments: &[
            OBJECT_ARG,
            ArgumentMetadata {
                name: "pretty",
                arg_type: "boolean",
                required: false,
                default: Some("false"),
                description: "Pretty-print the JSON output",
            },
        ],
        return_type: "string",
        examples: &[
            "{{ to_json(object=config) }}",
            "{{ config | to_json(pretty=true) }}",
        ],
        syntax: SyntaxVariants::FUNCTION_AND_FILTER,
    };

    fn call_as_function(kwargs: Kwargs) -> Result<Value, Error> {
        let object: Value = kwargs.get("object")?;
        let pretty: bool = kwargs.get("pretty").unwrap_or(false);
        Ok(Value::from(Self::serialize(&object, pretty)?))
    }

    fn call_as_filter(value: &Value, kwargs: Kwargs) -> Result<Value, Error> {
        let pretty: bool = kwargs.get("pretty").unwrap_or(false);
        Ok(Value::from(Self::serialize(value, pretty)?))
    }
}

/// Convert object to YAML string.
///
/// # Function Syntax
/// ```jinja
/// {{ to_yaml(object=config) }}
/// ```
///
/// # Filter Syntax
/// ```jinja
/// {{ config | to_yaml }}
/// ```
pub struct ToYaml;

impl ToYaml {
    fn serialize(value: &Value) -> Result<String, Error> {
        // Convert MiniJinja Value to serde_yaml::Value
        let yaml_value: serde_yaml::Value = serde_yaml::to_value(value).map_err(|e| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("Failed to convert to YAML: {}", e),
            )
        })?;

        // Serialize to YAML string
        serde_yaml::to_string(&yaml_value).map_err(|e| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("Failed to serialize to YAML: {}", e),
            )
        })
    }
}

impl FilterFunction for ToYaml {
    const NAME: &'static str = "to_yaml";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "to_yaml",
        category: "serialization",
        description: "Convert object to YAML string",
        arguments: &[OBJECT_ARG],
        return_type: "string",
        examples: &["{{ to_yaml(object=config) }}", "{{ config | to_yaml }}"],
        syntax: SyntaxVariants::FUNCTION_AND_FILTER,
    };

    fn call_as_function(kwargs: Kwargs) -> Result<Value, Error> {
        let object: Value = kwargs.get("object")?;
        Ok(Value::from(Self::serialize(&object)?))
    }

    fn call_as_filter(value: &Value, _kwargs: Kwargs) -> Result<Value, Error> {
        Ok(Value::from(Self::serialize(value)?))
    }
}

/// Convert object to TOML string.
///
/// # Function Syntax
/// ```jinja
/// {{ to_toml(object=config) }}
/// ```
///
/// # Filter Syntax
/// ```jinja
/// {{ config | to_toml }}
/// ```
///
/// # Note
///
/// TOML has specific requirements:
/// - Root level must be a table (object/map)
/// - Arrays must contain elements of the same type
/// - Some nested structures may not be representable in TOML
pub struct ToToml;

impl ToToml {
    fn serialize(value: &Value) -> Result<String, Error> {
        // Convert MiniJinja Value to serde_json::Value first (as intermediate format)
        let json_value: serde_json::Value = serde_json::to_value(value).map_err(|e| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("Failed to convert to TOML (intermediate conversion): {}", e),
            )
        })?;

        // Serialize JSON value directly to TOML string
        toml::to_string(&json_value).map_err(|e| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("Failed to serialize to TOML: {}", e),
            )
        })
    }
}

impl FilterFunction for ToToml {
    const NAME: &'static str = "to_toml";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "to_toml",
        category: "serialization",
        description: "Convert object to TOML string",
        arguments: &[OBJECT_ARG],
        return_type: "string",
        examples: &["{{ to_toml(object=config) }}", "{{ config | to_toml }}"],
        syntax: SyntaxVariants::FUNCTION_AND_FILTER,
    };

    fn call_as_function(kwargs: Kwargs) -> Result<Value, Error> {
        let object: Value = kwargs.get("object")?;
        Ok(Value::from(Self::serialize(&object)?))
    }

    fn call_as_filter(value: &Value, _kwargs: Kwargs) -> Result<Value, Error> {
        Ok(Value::from(Self::serialize(value)?))
    }
}

// ============================================
// Parsing (String -> Object)
// ============================================

/// Parse JSON string into object.
///
/// # Function Syntax
/// ```jinja
/// {{ parse_json(string='{"key": "value"}') }}
/// ```
///
/// # Filter Syntax
/// ```jinja
/// {{ '{"key": "value"}' | parse_json }}
/// ```
pub struct ParseJson;

impl ParseJson {
    fn parse(input: &str) -> Result<Value, Error> {
        let json_value: serde_json::Value = serde_json::from_str(input).map_err(|e| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("Failed to parse JSON: {}", e),
            )
        })?;

        Ok(Value::from_serialize(&json_value))
    }
}

impl FilterFunction for ParseJson {
    const NAME: &'static str = "parse_json";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "parse_json",
        category: "serialization",
        description: "Parse JSON string into object",
        arguments: &[STRING_ARG],
        return_type: "any",
        examples: &[
            "{{ parse_json(string='{\"key\": \"value\"}') }}",
            "{{ json_string | parse_json }}",
        ],
        syntax: SyntaxVariants::FUNCTION_AND_FILTER,
    };

    fn call_as_function(kwargs: Kwargs) -> Result<Value, Error> {
        let input: String = kwargs.get("string")?;
        Self::parse(&input)
    }

    fn call_as_filter(value: &Value, _kwargs: Kwargs) -> Result<Value, Error> {
        let input = value.as_str().ok_or_else(|| {
            Error::new(ErrorKind::InvalidOperation, "parse_json requires a string")
        })?;
        Self::parse(input)
    }
}

/// Parse YAML string into object.
///
/// # Function Syntax
/// ```jinja
/// {{ parse_yaml(string='key: value') }}
/// ```
///
/// # Filter Syntax
/// ```jinja
/// {{ 'key: value' | parse_yaml }}
/// ```
pub struct ParseYaml;

impl ParseYaml {
    fn parse(input: &str) -> Result<Value, Error> {
        // Parse YAML string to serde_yaml::Value
        let yaml_value: serde_yaml::Value = serde_yaml::from_str(input).map_err(|e| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("Failed to parse YAML: {}", e),
            )
        })?;

        // Convert serde_yaml::Value to serde_json::Value
        let json_value = serde_yaml_to_json(yaml_value).map_err(|e| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("Failed to convert YAML to JSON: {}", e),
            )
        })?;

        Ok(Value::from_serialize(&json_value))
    }
}

impl FilterFunction for ParseYaml {
    const NAME: &'static str = "parse_yaml";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "parse_yaml",
        category: "serialization",
        description: "Parse YAML string into object",
        arguments: &[STRING_ARG],
        return_type: "any",
        examples: &[
            "{{ parse_yaml(string='key: value') }}",
            "{{ yaml_string | parse_yaml }}",
        ],
        syntax: SyntaxVariants::FUNCTION_AND_FILTER,
    };

    fn call_as_function(kwargs: Kwargs) -> Result<Value, Error> {
        let input: String = kwargs.get("string")?;
        Self::parse(&input)
    }

    fn call_as_filter(value: &Value, _kwargs: Kwargs) -> Result<Value, Error> {
        let input = value.as_str().ok_or_else(|| {
            Error::new(ErrorKind::InvalidOperation, "parse_yaml requires a string")
        })?;
        Self::parse(input)
    }
}

/// Parse TOML string into object.
///
/// # Function Syntax
/// ```jinja
/// {{ parse_toml(string='key = "value"') }}
/// ```
///
/// # Filter Syntax
/// ```jinja
/// {{ 'key = "value"' | parse_toml }}
/// ```
pub struct ParseToml;

impl ParseToml {
    fn parse(input: &str) -> Result<Value, Error> {
        // Parse TOML string to toml::Value
        let toml_value: toml::Value = toml::from_str(input).map_err(|e| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("Failed to parse TOML: {}", e),
            )
        })?;

        // Convert toml::Value to serde_json::Value
        let json_value = toml_to_json(toml_value).map_err(|e| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("Failed to convert TOML to JSON: {}", e),
            )
        })?;

        Ok(Value::from_serialize(&json_value))
    }
}

impl FilterFunction for ParseToml {
    const NAME: &'static str = "parse_toml";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "parse_toml",
        category: "serialization",
        description: "Parse TOML string into object",
        arguments: &[STRING_ARG],
        return_type: "any",
        examples: &[
            "{{ parse_toml(string='key = \"value\"') }}",
            "{{ toml_string | parse_toml }}",
        ],
        syntax: SyntaxVariants::FUNCTION_AND_FILTER,
    };

    fn call_as_function(kwargs: Kwargs) -> Result<Value, Error> {
        let input: String = kwargs.get("string")?;
        Self::parse(&input)
    }

    fn call_as_filter(value: &Value, _kwargs: Kwargs) -> Result<Value, Error> {
        let input = value.as_str().ok_or_else(|| {
            Error::new(ErrorKind::InvalidOperation, "parse_toml requires a string")
        })?;
        Self::parse(input)
    }
}

// ============================================
// Helper Functions
// ============================================

/// Helper function to convert serde_yaml::Value to serde_json::Value
fn serde_yaml_to_json(yaml: serde_yaml::Value) -> std::result::Result<serde_json::Value, String> {
    match yaml {
        serde_yaml::Value::Null => Ok(serde_json::Value::Null),
        serde_yaml::Value::Bool(b) => Ok(serde_json::Value::Bool(b)),
        serde_yaml::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                Ok(serde_json::Value::Number(i.into()))
            } else if let Some(u) = n.as_u64() {
                Ok(serde_json::Value::Number(u.into()))
            } else if let Some(f) = n.as_f64() {
                serde_json::Number::from_f64(f)
                    .map(serde_json::Value::Number)
                    .ok_or_else(|| format!("Invalid float value: {}", f))
            } else {
                Err("Unsupported number type".to_string())
            }
        }
        serde_yaml::Value::String(s) => Ok(serde_json::Value::String(s)),
        serde_yaml::Value::Sequence(seq) => {
            let json_array: std::result::Result<Vec<serde_json::Value>, String> =
                seq.into_iter().map(serde_yaml_to_json).collect();
            json_array.map(serde_json::Value::Array)
        }
        serde_yaml::Value::Mapping(map) => {
            let mut json_map = serde_json::Map::new();
            for (k, v) in map {
                let key = match k {
                    serde_yaml::Value::String(s) => s,
                    serde_yaml::Value::Number(n) => n.to_string(),
                    serde_yaml::Value::Bool(b) => b.to_string(),
                    _ => {
                        return Err(
                            "YAML map keys must be strings, numbers, or booleans".to_string()
                        );
                    }
                };
                json_map.insert(key, serde_yaml_to_json(v)?);
            }
            Ok(serde_json::Value::Object(json_map))
        }
        serde_yaml::Value::Tagged(tagged) => {
            // For tagged values, just convert the inner value
            serde_yaml_to_json(tagged.value)
        }
    }
}

/// Helper function to convert toml::Value to serde_json::Value
fn toml_to_json(toml: toml::Value) -> std::result::Result<serde_json::Value, String> {
    match toml {
        toml::Value::String(s) => Ok(serde_json::Value::String(s)),
        toml::Value::Integer(i) => Ok(serde_json::Value::Number(i.into())),
        toml::Value::Float(f) => serde_json::Number::from_f64(f)
            .map(serde_json::Value::Number)
            .ok_or_else(|| format!("Invalid float value: {}", f)),
        toml::Value::Boolean(b) => Ok(serde_json::Value::Bool(b)),
        toml::Value::Array(arr) => {
            let json_array: std::result::Result<Vec<serde_json::Value>, String> =
                arr.into_iter().map(toml_to_json).collect();
            json_array.map(serde_json::Value::Array)
        }
        toml::Value::Table(table) => {
            let mut json_map = serde_json::Map::new();
            for (k, v) in table {
                json_map.insert(k, toml_to_json(v)?);
            }
            Ok(serde_json::Value::Object(json_map))
        }
        toml::Value::Datetime(dt) => Ok(serde_json::Value::String(dt.to_string())),
    }
}