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
//! Network-related functions for MiniJinja templates
//!
//! This module provides functions for network operations:
//! - `get_ip_address`: Get IP address of interface or primary local IP
//! - `get_interfaces`: List all network interfaces
//! - `resolve_dns`: DNS hostname resolution
//! - `cidr_contains`: Check if IP is in CIDR range
//! - `cidr_network`: Get network address from CIDR
//! - `cidr_broadcast`: Get broadcast address from CIDR
//! - `cidr_netmask`: Get netmask from CIDR
//! - `ip_to_int`: Convert IP to integer
//! - `int_to_ip`: Convert integer to IP

use super::metadata::{ArgumentMetadata, FunctionMetadata, SyntaxVariants};
use super::traits::Function;
use minijinja::value::Kwargs;
use minijinja::{Error, ErrorKind, Value};
use std::net::{Ipv4Addr, ToSocketAddrs};

/// Get IP address of a network interface or the primary local IP
pub struct GetIpAddress;

impl Function for GetIpAddress {
    const NAME: &'static str = "get_ip_address";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "get_ip_address",
        category: "network",
        description: "Get IP address of a network interface or the primary local IP",
        arguments: &[ArgumentMetadata {
            name: "interface",
            arg_type: "string",
            required: false,
            default: None,
            description: "Network interface name (e.g., eth0, en0). If not provided, returns primary local IP",
        }],
        return_type: "string",
        examples: &[
            "{{ get_ip_address() }}",
            "{{ get_ip_address(interface=\"eth0\") }}",
        ],
        syntax: SyntaxVariants::FUNCTION_ONLY,
    };

    fn call(kwargs: Kwargs) -> Result<Value, Error> {
        let interface: Option<String> = kwargs.get("interface").ok();

        if let Some(iface) = interface {
            get_interface_ip(&iface)
        } else {
            get_local_ip()
        }
    }
}

/// Get the primary local IP address
fn get_local_ip() -> Result<Value, Error> {
    let socket = std::net::UdpSocket::bind("0.0.0.0:0").map_err(|e| {
        Error::new(
            ErrorKind::InvalidOperation,
            format!("Failed to create socket: {}", e),
        )
    })?;

    socket.connect("8.8.8.8:80").map_err(|e| {
        Error::new(
            ErrorKind::InvalidOperation,
            format!("Failed to determine local IP: {}", e),
        )
    })?;

    let local_addr = socket.local_addr().map_err(|e| {
        Error::new(
            ErrorKind::InvalidOperation,
            format!("Failed to get local address: {}", e),
        )
    })?;

    Ok(Value::from(local_addr.ip().to_string()))
}

/// Get IP address for a specific network interface
fn get_interface_ip(interface: &str) -> Result<Value, Error> {
    let ifaces = if_addrs::get_if_addrs().map_err(|e| {
        Error::new(
            ErrorKind::InvalidOperation,
            format!("Failed to get network interfaces: {}", e),
        )
    })?;

    for iface in ifaces {
        if iface.name == interface {
            return Ok(Value::from(iface.ip().to_string()));
        }
    }

    Err(Error::new(
        ErrorKind::InvalidOperation,
        format!("Network interface '{}' not found", interface),
    ))
}

/// Get a list of all network interfaces with their IP addresses
pub struct GetInterfaces;

impl Function for GetInterfaces {
    const NAME: &'static str = "get_interfaces";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "get_interfaces",
        category: "network",
        description: "Get list of all network interfaces with their IP addresses",
        arguments: &[],
        return_type: "array",
        examples: &[
            "{% for iface in get_interfaces() %}{{ iface.name }}: {{ iface.ip }}{% endfor %}",
        ],
        syntax: SyntaxVariants::FUNCTION_ONLY,
    };

    fn call(_kwargs: Kwargs) -> Result<Value, Error> {
        let ifaces = if_addrs::get_if_addrs().map_err(|e| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("Failed to get network interfaces: {}", e),
            )
        })?;

        let interfaces: Vec<Value> = ifaces
            .into_iter()
            .map(|iface| {
                let mut map = std::collections::BTreeMap::new();
                map.insert("name".to_string(), Value::from(iface.name.clone()));
                map.insert("ip".to_string(), Value::from(iface.ip().to_string()));
                map.insert("is_loopback".to_string(), Value::from(iface.is_loopback()));
                Value::from_object(map)
            })
            .collect();

        Ok(Value::from(interfaces))
    }
}

/// Resolve a hostname to an IP address using DNS
pub struct ResolveDns;

impl Function for ResolveDns {
    const NAME: &'static str = "resolve_dns";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "resolve_dns",
        category: "network",
        description: "Resolve a hostname to an IP address using DNS",
        arguments: &[ArgumentMetadata {
            name: "hostname",
            arg_type: "string",
            required: true,
            default: None,
            description: "Hostname to resolve (e.g., google.com, localhost)",
        }],
        return_type: "string",
        examples: &[
            "{{ resolve_dns(hostname=\"google.com\") }}",
            "{{ resolve_dns(hostname=\"localhost\") }}",
        ],
        syntax: SyntaxVariants::FUNCTION_ONLY,
    };

    fn call(kwargs: Kwargs) -> Result<Value, Error> {
        let hostname: String = kwargs.get("hostname")?;

        let address = format!("{}:0", hostname);

        let addrs: Vec<_> = address
            .to_socket_addrs()
            .map_err(|e| {
                Error::new(
                    ErrorKind::InvalidOperation,
                    format!("Failed to resolve hostname '{}': {}", hostname, e),
                )
            })?
            .collect();

        if addrs.is_empty() {
            return Err(Error::new(
                ErrorKind::InvalidOperation,
                format!("No IP addresses found for hostname '{}'", hostname),
            ));
        }

        Ok(Value::from(addrs[0].ip().to_string()))
    }
}

/// Parse a CIDR string into network address and prefix length
fn parse_cidr(cidr: &str) -> Result<(Ipv4Addr, u8), Error> {
    let parts: Vec<&str> = cidr.split('/').collect();
    if parts.len() != 2 {
        return Err(Error::new(
            ErrorKind::InvalidOperation,
            format!(
                "Invalid CIDR notation '{}': expected format 'IP/prefix'",
                cidr
            ),
        ));
    }

    let ip: Ipv4Addr = parts[0].parse().map_err(|_| {
        Error::new(
            ErrorKind::InvalidOperation,
            format!("Invalid IP address in CIDR '{}': '{}'", cidr, parts[0]),
        )
    })?;

    let prefix: u8 = parts[1].parse().map_err(|_| {
        Error::new(
            ErrorKind::InvalidOperation,
            format!("Invalid prefix length in CIDR '{}': '{}'", cidr, parts[1]),
        )
    })?;

    if prefix > 32 {
        return Err(Error::new(
            ErrorKind::InvalidOperation,
            format!("Prefix length must be 0-32, got {}", prefix),
        ));
    }

    Ok((ip, prefix))
}

/// Calculate the network mask from prefix length
fn prefix_to_mask(prefix: u8) -> u32 {
    if prefix == 0 {
        0
    } else {
        !0u32 << (32 - prefix)
    }
}

/// Check if an IP address is within a CIDR range
pub struct CidrContains;

impl Function for CidrContains {
    const NAME: &'static str = "cidr_contains";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "cidr_contains",
        category: "network",
        description: "Check if an IP address is within a CIDR range",
        arguments: &[
            ArgumentMetadata {
                name: "cidr",
                arg_type: "string",
                required: true,
                default: None,
                description: "CIDR notation (e.g., 192.168.1.0/24)",
            },
            ArgumentMetadata {
                name: "ip",
                arg_type: "string",
                required: true,
                default: None,
                description: "IP address to check",
            },
        ],
        return_type: "boolean",
        examples: &[
            "{% if cidr_contains(cidr=\"192.168.1.0/24\", ip=\"192.168.1.100\") %}in subnet{% endif %}",
        ],
        syntax: SyntaxVariants::FUNCTION_ONLY,
    };

    fn call(kwargs: Kwargs) -> Result<Value, Error> {
        let cidr: String = kwargs.get("cidr")?;
        let ip_str: String = kwargs.get("ip")?;

        let (network_ip, prefix) = parse_cidr(&cidr)?;
        let check_ip: Ipv4Addr = ip_str.parse().map_err(|_| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("Invalid IP address: '{}'", ip_str),
            )
        })?;

        let mask = prefix_to_mask(prefix);
        let network_int = u32::from(network_ip);
        let check_int = u32::from(check_ip);

        let is_contained = (network_int & mask) == (check_int & mask);

        Ok(Value::from(is_contained))
    }
}

/// Get the network address from a CIDR notation
pub struct CidrNetwork;

impl Function for CidrNetwork {
    const NAME: &'static str = "cidr_network";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "cidr_network",
        category: "network",
        description: "Get the network address from a CIDR notation",
        arguments: &[ArgumentMetadata {
            name: "cidr",
            arg_type: "string",
            required: true,
            default: None,
            description: "CIDR notation (e.g., 192.168.1.100/24)",
        }],
        return_type: "string",
        examples: &["{{ cidr_network(cidr=\"192.168.1.100/24\") }}"],
        syntax: SyntaxVariants::FUNCTION_ONLY,
    };

    fn call(kwargs: Kwargs) -> Result<Value, Error> {
        let cidr: String = kwargs.get("cidr")?;

        let (ip, prefix) = parse_cidr(&cidr)?;
        let mask = prefix_to_mask(prefix);
        let network_int = u32::from(ip) & mask;
        let network_ip = Ipv4Addr::from(network_int);

        Ok(Value::from(network_ip.to_string()))
    }
}

/// Get the broadcast address from a CIDR notation
pub struct CidrBroadcast;

impl Function for CidrBroadcast {
    const NAME: &'static str = "cidr_broadcast";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "cidr_broadcast",
        category: "network",
        description: "Get the broadcast address from a CIDR notation",
        arguments: &[ArgumentMetadata {
            name: "cidr",
            arg_type: "string",
            required: true,
            default: None,
            description: "CIDR notation (e.g., 192.168.1.0/24)",
        }],
        return_type: "string",
        examples: &["{{ cidr_broadcast(cidr=\"192.168.1.0/24\") }}"],
        syntax: SyntaxVariants::FUNCTION_ONLY,
    };

    fn call(kwargs: Kwargs) -> Result<Value, Error> {
        let cidr: String = kwargs.get("cidr")?;

        let (ip, prefix) = parse_cidr(&cidr)?;
        let mask = prefix_to_mask(prefix);
        let network_int = u32::from(ip) & mask;
        let broadcast_int = network_int | !mask;
        let broadcast_ip = Ipv4Addr::from(broadcast_int);

        Ok(Value::from(broadcast_ip.to_string()))
    }
}

/// Get the netmask from a CIDR notation
pub struct CidrNetmask;

impl Function for CidrNetmask {
    const NAME: &'static str = "cidr_netmask";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "cidr_netmask",
        category: "network",
        description: "Get the netmask from a CIDR notation",
        arguments: &[ArgumentMetadata {
            name: "cidr",
            arg_type: "string",
            required: true,
            default: None,
            description: "CIDR notation (e.g., 192.168.1.0/24)",
        }],
        return_type: "string",
        examples: &["{{ cidr_netmask(cidr=\"192.168.1.0/24\") }}"],
        syntax: SyntaxVariants::FUNCTION_ONLY,
    };

    fn call(kwargs: Kwargs) -> Result<Value, Error> {
        let cidr: String = kwargs.get("cidr")?;

        let (_, prefix) = parse_cidr(&cidr)?;
        let mask = prefix_to_mask(prefix);
        let mask_ip = Ipv4Addr::from(mask);

        Ok(Value::from(mask_ip.to_string()))
    }
}

/// Convert an IPv4 address to its integer representation
pub struct IpToInt;

impl Function for IpToInt {
    const NAME: &'static str = "ip_to_int";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "ip_to_int",
        category: "network",
        description: "Convert an IPv4 address to its integer representation",
        arguments: &[ArgumentMetadata {
            name: "ip",
            arg_type: "string",
            required: true,
            default: None,
            description: "IPv4 address (e.g., 192.168.1.1)",
        }],
        return_type: "integer",
        examples: &["{{ ip_to_int(ip=\"192.168.1.1\") }}"],
        syntax: SyntaxVariants::FUNCTION_ONLY,
    };

    fn call(kwargs: Kwargs) -> Result<Value, Error> {
        let ip_str: String = kwargs.get("ip")?;

        let ip: Ipv4Addr = ip_str.parse().map_err(|_| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("Invalid IPv4 address: '{}'", ip_str),
            )
        })?;

        let int_value = u32::from(ip);

        Ok(Value::from(int_value as i64))
    }
}

/// Convert an integer to its IPv4 address representation
pub struct IntToIp;

impl Function for IntToIp {
    const NAME: &'static str = "int_to_ip";
    const METADATA: FunctionMetadata = FunctionMetadata {
        name: "int_to_ip",
        category: "network",
        description: "Convert an integer to its IPv4 address representation",
        arguments: &[ArgumentMetadata {
            name: "int",
            arg_type: "integer",
            required: true,
            default: None,
            description: "Integer value (0 to 4294967295)",
        }],
        return_type: "string",
        examples: &["{{ int_to_ip(int=3232235777) }}"],
        syntax: SyntaxVariants::FUNCTION_ONLY,
    };

    fn call(kwargs: Kwargs) -> Result<Value, Error> {
        let int_value: i64 = kwargs.get("int")?;

        if int_value < 0 || int_value > u32::MAX as i64 {
            return Err(Error::new(
                ErrorKind::InvalidOperation,
                format!(
                    "Integer must be between 0 and {}, got {}",
                    u32::MAX,
                    int_value
                ),
            ));
        }

        let ip = Ipv4Addr::from(int_value as u32);

        Ok(Value::from(ip.to_string()))
    }
}