oxblade 0.1.0

Blade templates for Laravel for Rust: Blade's markup and directives, Laravel's helpers, Rust's expressions. Community package, not affiliated with Laravel.
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
//! The loaded translation lines: Laravel's `Translator::$loaded`, filled from JSON files where
//! its `FileLoader` reads PHP.

use std::{collections::BTreeMap, fs, io, path::Path};

use serde_json::Value;

use crate::error::{Error, ErrorKind, Result};

/// Every line of one `lang` directory.
#[derive(Debug, Default)]
pub(super) struct Table {
    /// `lang/<locale>.json`: Laravel's group `*` of that locale, always an object.
    json: BTreeMap<String, Value>,
    /// `lang/<locale>/<group>.json`: the lines of each group for each locale.
    groups: BTreeMap<String, BTreeMap<String, Value>>,
}

/// What a group holds for an item, as far as a translation goes.
#[derive(Debug, PartialEq)]
pub(super) enum Line<'a> {
    /// A string.
    Text(&'a str),
    /// A non-empty array or object: Laravel returns it as it is, and a template cannot print it.
    Table,
    /// Nothing, an empty array or object, or another scalar: Laravel looks at the next locale.
    Missing,
}

impl Table {
    /// Reads `dir`: `<locale>.json` and `<locale>/<group>.json` at any depth. A directory that is
    /// not there holds no lines, as in Laravel, where a missing file is never an error.
    pub(super) fn load(dir: &Path) -> Result<Self> {
        let mut table = Self::default();
        for entry in entries(dir)? {
            let path = entry.path();
            let file_name = entry.file_name();
            let Some(name) = file_name.to_str() else {
                continue;
            };
            let kind = entry
                .file_type()
                .map_err(|error| unreadable(&path, &error))?;
            if kind.is_dir() {
                // `lang/vendor/<namespace>/` holds package translations, which Laravel loads by
                // namespace only, never as a locale.
                if name != "vendor" && is_locale_path_segment(name) {
                    table.read_groups(&path, name, "")?;
                }
            } else if kind.is_file()
                && let Some(locale) = name
                    .strip_suffix(".json")
                    .filter(|locale| is_locale_path_segment(locale))
            {
                let value = match read(&path)? {
                    value @ Value::Object(_) => value,
                    // PHP decodes an array with integer keys, which a numeric string reaches.
                    Value::Array(lines) => Value::Object(
                        lines
                            .into_iter()
                            .enumerate()
                            .map(|(index, line)| (index.to_string(), line))
                            .collect(),
                    ),
                    _ => return Err(invalid(&path)),
                };
                table.json.insert(locale.to_owned(), value);
            }
        }
        Ok(table)
    }

    fn read_groups(&mut self, dir: &Path, locale: &str, prefix: &str) -> Result<()> {
        for entry in entries(dir)? {
            let path = entry.path();
            let file_name = entry.file_name();
            let Some(name) = file_name.to_str() else {
                continue;
            };
            let kind = entry
                .file_type()
                .map_err(|error| unreadable(&path, &error))?;
            if kind.is_dir() && is_safe_path_segment(name) {
                self.read_groups(&path, locale, &format!("{prefix}{name}/"))?;
            } else if kind.is_file()
                && let Some(group) = name
                    .strip_suffix(".json")
                    .filter(|group| is_safe_path_segment(group))
            {
                let lines = read(&path)?;
                if !matches!(lines, Value::Object(_) | Value::Array(_)) {
                    return Err(invalid(&path));
                }
                self.groups
                    .entry(format!("{prefix}{group}"))
                    .or_default()
                    .insert(locale.to_owned(), lines);
            }
        }
        Ok(())
    }

    /// The JSON translation of `locale` for `key`, where Laravel's `isset` finds it: a value that
    /// is not null.
    pub(super) fn json_line(&self, locale: &str, key: &str) -> Option<&Value> {
        self.json
            .get(locale)?
            .as_object()?
            .get(key)
            .filter(|value| !value.is_null())
    }

    /// Laravel's `Translator::getLine` for one locale. Group `*` is the JSON translation.
    pub(super) fn group(&self, group: &str, locale: &str, item: Option<&str>) -> Line<'_> {
        let lines = match group {
            "*" => self.json.get(locale),
            group => self
                .groups
                .get(group)
                .and_then(|locales| locales.get(locale)),
        };
        match arr_get(lines, item) {
            Some(Value::String(text)) => Line::Text(text),
            Some(value) if is_table(value) => Line::Table,
            _ => Line::Missing,
        }
    }
}

/// Laravel's FileLoader rejects empty or unsafe locale names.
fn is_locale_path_segment(locale: &str) -> bool {
    is_safe_path_segment(locale) && !locale.contains('/')
}

fn is_safe_path_segment(name: &str) -> bool {
    !name.is_empty() && !name.contains(['\\', '\0']) && !name.contains("..")
}

/// Whether Laravel would return the value as an array: a non-empty array or object.
fn is_table(value: &Value) -> bool {
    matches!(value, Value::Array(items) if !items.is_empty())
        || matches!(value, Value::Object(entries) if !entries.is_empty())
}

/// Laravel's `Arr::get`: the value under a dot-notation key. A key that is literally present wins
/// over walking the path.
fn arr_get<'a>(lines: Option<&'a Value>, key: Option<&str>) -> Option<&'a Value> {
    let mut lines = lines?;
    let Some(key) = key else {
        return Some(lines);
    };
    if let Some(found) = key_get(lines, key) {
        return Some(found);
    }
    for segment in key.split('.') {
        lines = key_get(lines, segment)?;
    }
    Some(lines)
}

/// `$lines[$key]`: an object by key and an array by index. PHP turns a canonical decimal string
/// into an integer key, so `"0"` reaches the first element and `"00"` does not.
fn key_get<'a>(lines: &'a Value, key: &str) -> Option<&'a Value> {
    match lines {
        Value::Object(entries) => entries.get(key),
        Value::Array(items) => items.get(index(key)?),
        _ => None,
    }
}

fn index(key: &str) -> Option<usize> {
    let index = key.parse::<usize>().ok()?;
    (index.to_string() == key).then_some(index)
}

/// The entries of a directory by name. A directory that is not there is empty.
fn entries(dir: &Path) -> Result<Vec<fs::DirEntry>> {
    let read = match fs::read_dir(dir) {
        Ok(read) => read,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(error) => return Err(unreadable(dir, &error)),
    };
    let mut entries = read
        .collect::<std::result::Result<Vec<fs::DirEntry>, io::Error>>()
        .map_err(|error| unreadable(dir, &error))?;
    entries.sort_by_key(|entry| entry.file_name());
    Ok(entries)
}

fn read(path: &Path) -> Result<Value> {
    let bytes = fs::read(path).map_err(|error| unreadable(path, &error))?;
    serde_json::from_slice(&bytes).map_err(|_| invalid(path))
}

/// Laravel's `RuntimeException` for a JSON file it cannot use.
fn invalid(path: &Path) -> Error {
    Error::new(
        ErrorKind::Load,
        format!(
            "Translation file [{}] contains an invalid JSON structure.",
            path.display()
        ),
        None,
    )
}

fn unreadable(path: &Path, error: &io::Error) -> Error {
    Error::new(
        ErrorKind::Load,
        format!(
            "Translation path [{}] cannot be read: {error}.",
            path.display()
        ),
        None,
    )
}

/// A temporary directory for a test, removed when dropped.
#[cfg(test)]
pub(super) struct TempDir(std::path::PathBuf);

#[cfg(test)]
impl TempDir {
    pub(super) fn new(name: &str) -> Self {
        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
        let unique = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let dir = std::env::temp_dir().join(format!(
            "oxblade-translate-{}-{unique}-{name}",
            std::process::id()
        ));
        Self(dir)
    }

    pub(super) fn path(&self) -> &Path {
        &self.0
    }

    pub(super) fn write(&self, file: &str, contents: &str) -> &Self {
        let path = self.0.join(file);
        fs::create_dir_all(path.parent().expect("a temporary file has a parent"))
            .expect("create a temporary directory");
        fs::write(&path, contents).expect("write a temporary file");
        self
    }
}

#[cfg(test)]
impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.0);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn load(files: &[(&str, &str)]) -> Result<Table> {
        let dir = TempDir::new("table");
        for (file, contents) in files {
            dir.write(file, contents);
        }
        Table::load(dir.path())
    }

    fn text<'a>(table: &'a Table, group: &str, locale: &str, item: &str) -> Option<&'a str> {
        match table.group(group, locale, Some(item)) {
            Line::Text(text) => Some(text),
            _ => None,
        }
    }

    #[test]
    fn reads_every_file_under_the_directory() {
        let table = load(&[
            ("en.json", r#" {"Welcome": "Hello", "n": 5, "nil": null} "#),
            ("nl.json", "{}"),
            ("en/messages.json", r#"{"welcome": "Hi", "nested": {"deep": {"key": "Deep"}}, "list": ["zero", "one"]}"#),
            ("en/auth/passwords.json", r#"{"reset": "Reset"}"#),
            ("en/auth/deeper/still.json", r#"{"x": "y"}"#),
            ("en.json.bak", "not json"),
            ("en/notes.txt", "not json"),
            ("vendor/pkg/en/messages.json", r#"{"welcome": "Package"}"#),
            ("vendor/pkg/en.json", r#"{"Welcome": "Package"}"#),
        ])
        .expect("a valid directory");
        assert_eq!(text(&table, "messages", "en", "welcome"), Some("Hi"));
        assert_eq!(text(&table, "messages", "nl", "welcome"), None);
        assert_eq!(text(&table, "auth/passwords", "en", "reset"), Some("Reset"));
        assert_eq!(text(&table, "auth/deeper/still", "en", "x"), Some("y"));
        // Neither `vendor` directory is a locale.
        assert_eq!(
            table.group("pkg/en/messages", "vendor", Some("welcome")),
            Line::Missing
        );
        assert_eq!(table.json_line("vendor", "Welcome"), None);
        assert_eq!(table.json_line("pkg", "Welcome"), None);
        assert!(matches!(
            table.json_line("en", "Welcome"),
            Some(Value::String(_))
        ));
        assert!(matches!(table.json_line("en", "n"), Some(Value::Number(_))));
        assert_eq!(table.json_line("en", "nil"), None, "null is not set");
        assert_eq!(table.json_line("nl", "Welcome"), None);
        assert!(
            table.json_line("en.json", "x").is_none(),
            "only `.json` is a locale file"
        );
    }

    #[test]
    fn unsafe_locale_files_are_ignored() {
        let table = load(&[
            (".json", "not json"),
            ("bad..locale.json", "not json"),
            ("bad..locale/messages.json", "not json"),
            ("en/bad..group/messages.json", "not json"),
        ])
        .expect("unsafe paths are ignored");
        assert_eq!(table.json_line("", "x"), None);
        assert_eq!(
            table.group("messages", "bad..locale", Some("x")),
            Line::Missing
        );
    }

    #[cfg(unix)]
    #[test]
    fn symlinks_inside_the_directory_are_ignored() {
        let root = TempDir::new("links");
        let external = TempDir::new("external");
        external.write("messages.json", r#"{"welcome": "External"}"#);
        root.write("en/real.json", r#"{"welcome": "Local"}"#);
        std::os::unix::fs::symlink(external.path(), root.path().join("en/external"))
            .expect("create a directory symlink");
        std::os::unix::fs::symlink(root.path(), root.path().join("en/cycle"))
            .expect("create a symlink cycle");
        std::os::unix::fs::symlink(
            external.path().join("messages.json"),
            root.path().join("en/link.json"),
        )
        .expect("create a file symlink");
        let table = Table::load(root.path()).expect("read only the translation tree");
        assert_eq!(text(&table, "real", "en", "welcome"), Some("Local"));
        assert_eq!(text(&table, "external/messages", "en", "welcome"), None);
        assert_eq!(text(&table, "link", "en", "welcome"), None);
    }

    #[test]
    fn invalid_files_are_errors() {
        for contents in ["{", "null", r#""text""#, "5", "true"] {
            assert!(load(&[("en.json", contents)]).is_err(), "{contents}");
            assert!(
                load(&[("en/messages.json", contents)]).is_err(),
                "{contents}"
            );
        }
        let error = load(&[("en.json", "{")]).unwrap_err();
        assert_eq!(error.kind, ErrorKind::Load);
        assert!(
            error.message.contains("contains an invalid JSON structure"),
            "{}",
            error.message
        );
        // Arrays are arrays, which a group file can hold in PHP.
        assert!(load(&[("en.json", "[]"), ("en/list.json", r#"["zero", "one"]"#)]).is_ok());
    }

    #[test]
    fn a_missing_directory_is_empty_and_a_path_that_is_a_file_is_an_error() {
        let missing = TempDir::new("missing");
        let table = Table::load(&missing.0.join("lang")).expect("a missing directory loads");
        assert_eq!(table.json_line("en", "x"), None);
        assert_eq!(table.group("messages", "en", Some("x")), Line::Missing);

        let file = TempDir::new("file");
        file.write("lang", "not a directory");
        let error = Table::load(&file.0.join("lang")).expect_err("a file is not a directory");
        assert_eq!(error.kind, ErrorKind::Load);
        assert!(
            error.message.contains("cannot be read"),
            "{}",
            error.message
        );
    }

    #[test]
    fn an_array_in_a_locale_file_is_reached_by_index() {
        let table = load(&[("en.json", r#"["zero", "one"]"#)]).expect("valid");
        assert_eq!(table.group("*", "en", Some("0")), Line::Text("zero"));
        assert_eq!(table.group("*", "en", Some("1")), Line::Text("one"));
        assert_eq!(table.group("*", "en", Some("00")), Line::Missing);
        assert_eq!(table.group("*", "en", Some("+1")), Line::Missing);
        assert_eq!(table.group("*", "en", Some("01")), Line::Missing);
        assert_eq!(table.group("*", "en", Some("2")), Line::Missing);
    }

    #[test]
    fn dot_notation_follows_arr_get() {
        let table = load(&[
            ("en/messages.json", r#"{"a": {"b": "nested"}, "a.b": "literal", "list": [{"x": 0}, {"x": 1}], "": {"": "blank"}, "n": null, "zero": 0, "no": false}"#),
        ])
        .expect("valid");
        let lookup = |item: &str| table.group("messages", "en", Some(item));
        // The literal key wins over the path.
        assert_eq!(lookup("a.b"), Line::Text("literal"));
        // A number is not a line.
        assert_eq!(lookup("list.0.x"), Line::Missing);
        assert_eq!(lookup("a"), Line::Table);
        assert_eq!(lookup("list"), Line::Table);
        assert_eq!(lookup("list.0"), Line::Table);
        assert_eq!(lookup("list.01.x"), Line::Missing);
        assert_eq!(lookup("list.2"), Line::Missing);
        // Empty keys are keys.
        assert_eq!(lookup(""), Line::Table);
        assert_eq!(lookup("."), Line::Text("blank"));
        assert_eq!(lookup(".."), Line::Missing);
        assert_eq!(lookup("n"), Line::Missing);
        assert_eq!(lookup("zero"), Line::Missing);
        assert_eq!(lookup("no"), Line::Missing);
        assert_eq!(
            lookup("a.b.c"),
            Line::Missing,
            "a string has no keys below it"
        );
        assert_eq!(table.group("messages", "en", None), Line::Table);
        assert_eq!(table.group("missing", "en", Some("a")), Line::Missing);
        assert_eq!(table.group("*", "en", Some("a")), Line::Missing);
    }

    #[test]
    fn a_literal_key_with_a_dot_is_only_taken_when_present() {
        let table = load(&[(
            "en/messages.json",
            r#"{"a.b": "literal", "a": {"b": "nested"}}"#,
        )])
        .expect("valid");
        assert_eq!(
            table.group("messages", "en", Some("a.b")),
            Line::Text("literal")
        );
        // Without the literal key the path is walked.
        let table = load(&[(
            "en/messages.json",
            r#"{"a": {"b": "nested"}, "a.b.c": "deep literal"}"#,
        )])
        .expect("valid");
        assert_eq!(
            table.group("messages", "en", Some("a.b")),
            Line::Text("nested")
        );
        assert_eq!(
            table.group("messages", "en", Some("a.b.c")),
            Line::Text("deep literal")
        );
    }

    #[test]
    fn an_empty_group_is_missing_whatever_its_shape() {
        let table = load(&[("en/empty.json", "{}"), ("en/none.json", "[]")]).expect("valid");
        assert_eq!(table.group("empty", "en", None), Line::Missing);
        assert_eq!(table.group("none", "en", Some("0")), Line::Missing);
    }

    #[test]
    fn a_repeated_key_takes_its_last_value_as_php_decodes_it() {
        let table = load(&[("en.json", r#"{"a": "1", "a": "2"}"#)]).expect("valid");
        assert_eq!(table.group("*", "en", Some("a")), Line::Text("2"));
    }
}