minijinja-lua 0.1.27

a minijinja lua module using the minijinja rust crate
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
// SPDX-License-Identifier: MIT

use crate::LuaEnvironment;

/// Helper to get the lua type for minijinja wrapper userdata.
///
/// Returns `environment`, `state`, `none`, or any other regular lua type name.
pub(crate) fn minijinja_types(val: &mlua::Value) -> Result<&'static str, mlua::Error> {
    match val {
        mlua::Value::UserData(ud) if ud.is::<LuaEnvironment>() => Ok("environment"),
        mlua::Value::UserData(ud) if ud.type_name()? == Some("state".to_string()) => Ok("state"),
        val if val.is_null() => Ok("none"),
        _ => Ok(val.type_name()),
    }
}

/// Helper to load templates from a directory.
///
/// The returned function can be provided to `Environment:set_loader`
pub(crate) fn minijinja_path_loader(lua: &mlua::Lua) -> Result<mlua::Function, mlua::Error> {
    lua.load(
        r#"
        local function path_loader(paths)
            if type(paths) == "string" then
                paths = { paths }
            end

            local function loader(name)
                if name:match("\\") then return nil end

                name = name:gsub("^/+", ""):gsub("/+$", "")

                local sep = package.config:sub(1,1)
                local pattern = "([^" .. sep .. "]+)"

                local splits = {}
                for piece in name:gmatch(pattern) do
                    if ".." == piece then return nil end
                    table.insert(splits, piece)
                end

                for _, path in ipairs(paths) do
                    local p = path .. sep .. table.concat(splits, sep)
                    local file = io.open(p, "r")

                    if file then
                        local source = file:read("*a")
                        file:close()

                        return source
                    end
                end
            end

            return loader
        end

        return path_loader
    "#,
    )
    .eval()
}

/// Filters to work with JSON strings and objects.
#[cfg(feature = "json")]
pub mod json {
    use minijinja::{Error as JinjaError, ErrorKind as JinjaErrorKind, State, Value as JinjaValue};

    use crate::convert::err_to_minijinja_err;

    /// Add the filters to the environment
    pub fn add_to_environment(env: &mut minijinja::Environment) {
        env.add_filter("fromjson", fromjson);
    }

    /// This filter allows loading minijinja objects from a JSON string.
    ///
    /// In lua, this allows loading a JSON object while preserving key order.
    pub fn fromjson(_: &State, json: &[u8]) -> Result<JinjaValue, JinjaError> {
        serde_json::from_slice(json)
            .map_err(|err| err_to_minijinja_err(err, JinjaErrorKind::BadSerialization))
    }
}

/// Filters to format date and time strings.
#[cfg(feature = "datetime")]
pub mod datetime {
    use jiff::civil::{Date, Time};
    use minijinja::{
        Error as JinjaError,
        ErrorKind as JinjaErrorKind,
        State,
        Value as JinjaValue,
        value::Kwargs,
    };

    use crate::convert::err_to_minijinja_err;

    /// Add the filters to the environment
    pub fn add_to_environment(env: &mut minijinja::Environment) {
        env.add_filter("datefmt", datefmt);
        env.add_filter("timefmt", timefmt);
    }

    /// Formats a string into a date using the [`jiff`] crate.
    ///
    /// If the `format` keyword is provided, the date will be formatted according to the `strftime`
    /// format. Otherwise, the value from [`date.to_string`](jiff::civil::Date) is returned.
    ///
    /// If the `patterns` keyword is provided, it must be a list of `strptime` format strings to
    /// parse the input. Multiple patterns can be provided to allow support for various date
    /// formats. If no patterns are provided or matched, then the default [`jiff`] formatting is
    /// used by calling `.parse()`
    ///
    /// See here for available formatting patterns: <https://docs.rs/jiff/latest/jiff/fmt/strtime/index.html>
    pub fn datefmt(_: &State, value: JinjaValue, kwargs: Kwargs) -> Result<String, JinjaError> {
        let format = kwargs.get::<Option<&str>>("format")?;
        let patterns = kwargs.get::<Option<Vec<String>>>("patterns")?;
        kwargs.assert_all_used()?;

        let date = match value.as_str() {
            Some(s) => {
                // Try the provided patterns
                if let Some(date) = patterns
                    .iter()
                    .flatten()
                    .find_map(|f| Date::strptime(f, s).ok())
                {
                    Ok(date)
                } else {
                    // Or fallback to the `jiff` parser
                    s.parse::<Date>()
                        .map_err(|err| err_to_minijinja_err(err, JinjaErrorKind::CannotDeserialize))
                }
            },
            None => Err(JinjaError::new(
                JinjaErrorKind::CannotDeserialize,
                "could not parse value as a string",
            )),
        }?;

        Ok(match format {
            Some(f) => date.strftime(f).to_string(),
            None => date.to_string(),
        })
    }

    /// Formats a string into a time using the [`jiff`] crate.
    ///
    /// If `format` is provided, the time will be formatted according to the `strftime` format.
    /// Otherwise, the value from [`time.to_string()`](jiff::civil::Time) is returned.
    ///
    /// If `patterns` is provided, it must be a list of `strptime` format strings to parse the
    /// input. Multiple patterns can be provided to allow support for various date formats. If no
    /// patterns are provided or matched, then the default [`jiff`] formatting is used by calling
    /// `.parse()`
    ///
    /// See here for available formatting patterns: <https://docs.rs/jiff/latest/jiff/fmt/strtime/index.html>
    pub fn timefmt(_: &State, value: JinjaValue, kwargs: Kwargs) -> Result<String, JinjaError> {
        let format = kwargs.get::<Option<&str>>("format")?;
        let patterns = kwargs.get::<Option<Vec<String>>>("patterns")?;
        kwargs.assert_all_used()?;

        let time = match value.as_str() {
            Some(s) => {
                // Try the provided patterns
                if let Some(date) = patterns
                    .iter()
                    .flatten()
                    .find_map(|f| Time::strptime(f, s).ok())
                {
                    Ok(date)
                } else {
                    // Or fallback to the `jiff` parser
                    s.parse::<Time>()
                        .map_err(|err| err_to_minijinja_err(err, JinjaErrorKind::CannotDeserialize))
                }
            },
            None => Err(JinjaError::new(
                JinjaErrorKind::CannotDeserialize,
                "could not parse value as a string",
            )),
        }?;

        Ok(match format {
            Some(f) => time.strftime(f).to_string(),
            None => time.to_string(),
        })
    }
}

#[cfg(test)]
mod test {
    use minijinja::context;
    use serde_json::json;

    use super::*;
    use crate::state::{LuaStateMut, LuaStateRef};

    #[test]
    fn test_minijinja_types_environment() {
        let lua = mlua::Lua::new();
        let env = lua.create_userdata(LuaEnvironment::new()).unwrap();

        assert_eq!(
            minijinja_types(&mlua::Value::UserData(env)).unwrap(),
            "environment"
        );
    }

    #[test]
    fn test_minijinja_types_state() {
        let lua = mlua::Lua::new();
        let env = minijinja::Environment::new();
        let state = env.empty_state();

        lua.scope(|scope| {
            let ud = scope.create_userdata(LuaStateRef::new(&state)).unwrap();
            assert_eq!(
                minijinja_types(&mlua::Value::UserData(ud)).unwrap(),
                "state"
            );
            Ok(())
        })
        .unwrap();
    }

    #[test]
    fn test_minijinja_types_state_mut() {
        let lua = mlua::Lua::new();
        let env = minijinja::Environment::new();
        let mut state = env.empty_state();

        lua.scope(|scope| {
            let ud = scope.create_userdata(LuaStateMut::new(&mut state)).unwrap();
            assert_eq!(
                minijinja_types(&mlua::Value::UserData(ud)).unwrap(),
                "state"
            );
            Ok(())
        })
        .unwrap();
    }

    #[test]
    fn test_minijinja_types_none() {
        assert_eq!(minijinja_types(&mlua::Value::NULL).unwrap(), "none");
    }

    #[test]
    fn test_minijinja_types_lua() {
        let lua = mlua::Lua::new();

        assert_eq!(minijinja_types(&mlua::Value::Nil).unwrap(), "nil");
        assert_eq!(
            minijinja_types(&mlua::Value::Boolean(true)).unwrap(),
            "boolean"
        );
        assert_eq!(
            minijinja_types(&mlua::Value::Function(
                lua.create_function(|_, _: mlua::Value| Ok(())).unwrap()
            ))
            .unwrap(),
            "function"
        );
        assert_eq!(
            minijinja_types(&mlua::Value::Integer(99)).unwrap(),
            "integer"
        );
        assert_eq!(
            minijinja_types(&mlua::Value::Number(99.99)).unwrap(),
            "number"
        );
        assert_eq!(
            minijinja_types(&mlua::Value::String(lua.create_string("foo").unwrap())).unwrap(),
            "string"
        );
        assert_eq!(
            minijinja_types(&mlua::Value::Table(lua.create_table().unwrap())).unwrap(),
            "table"
        );
        assert_eq!(
            minijinja_types(&mlua::Value::Thread(
                lua.create_thread(lua.create_function(|_, _: mlua::Value| Ok(())).unwrap())
                    .unwrap()
            ))
            .unwrap(),
            "thread"
        );
    }

    #[test]
    #[cfg(feature = "json")]
    fn test_minijinja_from_json_filter() {
        let mut env = minijinja::Environment::new();
        json::add_to_environment(&mut env);

        let ex = json!({"1": 1, "2": 2, "three": [1,2,3]});
        let expr = env.compile_expression("te | fromjson").unwrap();

        let res = expr.eval(context! { te => ex.to_string() }).unwrap();

        assert_eq!(res, minijinja::Value::from_serialize(ex));
    }

    #[test]
    #[cfg(feature = "datetime")]
    fn test_minijinja_datefmt_filter() {
        let mut env = minijinja::Environment::new();
        datetime::add_to_environment(&mut env);

        let date = "2000-01-01";
        let ex = "2000-01-01";

        let expr = env.compile_expression("te | datefmt").unwrap();
        let res = expr.eval(context! { te => date }).unwrap();

        assert_eq!(res.as_str().unwrap(), ex, "{} should parse to {}", date, ex);
    }

    #[test]
    #[cfg(feature = "datetime")]
    fn test_minijinja_datefmt_filter_format() {
        let mut env = minijinja::Environment::new();
        datetime::add_to_environment(&mut env);

        let date: &str = "2000-01-01T11:12:13";
        let ex = "January 1, 2000";
        let fmt = "%B %-d, %Y";

        let te = format!("te | datefmt(format='{}')", fmt);
        let expr = env.compile_expression(&te).unwrap();

        let res = expr.eval(context! { te => date }).unwrap();

        assert_eq!(res.as_str().unwrap(), ex, "{} should parse to {}", date, ex);
    }

    #[test]
    #[cfg(feature = "datetime")]
    fn test_minijinja_datefmt_filter_parse() {
        let mut env = minijinja::Environment::new();
        datetime::add_to_environment(&mut env);

        let date = "2026 1 January";
        let ex = "2026-01-01";
        let patt = "%Y %-d %B";

        let te = format!("te | datefmt(patterns=['{}'])", patt);
        let expr = env.compile_expression(&te).unwrap();

        let res = expr.eval(context! { te => date }).unwrap();

        assert_eq!(res.as_str().unwrap(), ex, "{} should parse to {}", date, ex);
    }

    #[test]
    #[cfg(feature = "datetime")]
    fn test_minijinja_timefmt_filter() {
        let mut env = minijinja::Environment::new();
        datetime::add_to_environment(&mut env);

        let time = "2000-01-01T11:12:13";
        let ex = "11:12:13";

        let expr = env.compile_expression("te | timefmt").unwrap();
        let res = expr.eval(context! { te => time }).unwrap();

        assert_eq!(res.as_str().unwrap(), ex, "{} should parse to {}", time, ex);
    }

    #[test]
    #[cfg(feature = "datetime")]
    fn test_minijinja_timefmt_filter_format() {
        let mut env = minijinja::Environment::new();
        datetime::add_to_environment(&mut env);

        let time = "12:02:31";
        let ex = "31:02:12";
        let fmt = "%S:%M:%H";

        let te = format!("te | timefmt(format='{}')", fmt);
        let expr = env.compile_expression(&te).unwrap();

        let res = expr.eval(context! { te => time }).unwrap();

        assert_eq!(res.as_str().unwrap(), ex, "{} should parse to {}", time, ex);
    }

    #[test]
    #[cfg(feature = "datetime")]
    fn test_minijinja_timefmt_filter_parse() {
        let mut env = minijinja::Environment::new();
        datetime::add_to_environment(&mut env);

        let time = "04 02 09";
        let ex = "02:04:09";
        let patt = "%M %H %S";

        let te = format!("te | timefmt(patterns=['{}'])", patt);
        let expr = env.compile_expression(&te).unwrap();

        let res = expr.eval(context! { te => time }).unwrap();

        assert_eq!(res.as_str().unwrap(), ex, "{} should parse to {}", time, ex);
    }
}