laratext 0.1.0

Laratext for Laravel Rust: translation keys with their source text, and auto-translation with OpenAI, Claude, Google Translate or Translatorio.
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
506
507
508
509
//! The scanner of `text()` calls in Rust and template files.
//!
//! PHP reads PHP and Blade; this reads `.rs` files and the MiniJinja `.html` templates, for the
//! same calls: `text("key", "Source")`, `text!("key", "Source", ...)`, `Text::get("key", Some("Source"), ...)`
//! and, in a template, `{{ text('key', 'Source') }}`. A call with a key alone gets its text from the
//! key.
//!
//! Like the PHP scanner it reads the files statically, so the key has to be a literal string. A
//! call whose key is built at run time is never seen, and so is never created or translated.

use std::path::{Path, PathBuf};

use indexmap::IndexMap;

use crate::scripts::{self, ScriptTexts};
use crate::support::{base_path, key_to_text, settings};

/// What a file is written in, which decides the quotes and escapes of its string literals.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Language {
    /// A `.rs` file: double quoted and raw string literals.
    Rust,
    /// A MiniJinja template: single or double quoted literals.
    Template,
}

/// Where a call may start.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Start {
    /// Anywhere: `Text::get(` is not part of a longer name.
    Anywhere,
    /// Not inside a longer name and not a method of another object: PHP's `(?<!->)\btext\(`.
    Call,
}

const PATTERNS: [(&str, Start, bool); 3] = [
    ("Text::get(", Start::Anywhere, true),
    ("text(", Start::Call, false),
    ("text!(", Start::Call, false),
];

/// The `[key => source text]` pairs of the calls in a file.
pub fn extract_texts(content: &str, language: Language) -> IndexMap<String, String> {
    let mut pairs = IndexMap::new();

    // First, the calls with a source text, which win over the calls with a key alone.
    for (needle, start, accepts_option) in PATTERNS {
        for call in calls(content, needle, start) {
            if let Some((key, Some(value))) = read_call(content, call, language, accepts_option) {
                pairs.insert(key, value);
            }
        }
    }

    // Then the calls with a key alone, only for the keys not read yet.
    for (needle, start, accepts_option) in PATTERNS {
        for call in calls(content, needle, start) {
            if let Some((key, None)) = read_call(content, call, language, accepts_option)
                && !pairs.contains_key(&key)
            {
                let text = key_to_text(&key);

                pairs.insert(key, text);
            }
        }
    }

    pairs
}

/// The offsets after the opening parenthesis of every call of a pattern.
fn calls(content: &str, needle: &str, start: Start) -> Vec<usize> {
    let mut offsets = Vec::new();

    for (index, _) in content.match_indices(needle) {
        let allowed = match start {
            Start::Anywhere => true,
            Start::Call => !content[..index]
                .chars()
                .next_back()
                .is_some_and(|before| before == '.' || before.is_alphanumeric() || before == '_'),
        };

        if allowed {
            offsets.push(index + needle.len());
        }
    }

    offsets
}

fn skip_whitespace(content: &str, at: usize) -> usize {
    content.len() - content[at..].trim_start_matches(char::is_whitespace).len()
}

/// A call at the offset after its parenthesis: its key, and its source text when it has one.
fn read_call(
    content: &str,
    after_paren: usize,
    language: Language,
    accepts_option: bool,
) -> Option<(String, Option<String>)> {
    let key_at = skip_whitespace(content, after_paren);
    let (key, after_key) = key_literal(content, key_at, language)?;
    let next = skip_whitespace(content, after_key);

    if content[next..].starts_with(')') {
        return Some((key, None));
    }

    if !content[next..].starts_with(',') {
        return None;
    }

    let value_at = skip_whitespace(content, next + 1);

    // `Text::get("key", None, ...)` is a key alone.
    if accepts_option && let Some(after) = content[value_at..].strip_prefix("None") {
        let following = skip_whitespace(content, content.len() - after.len());

        return matches!(content[following..].chars().next(), Some(',' | ')')).then_some((key, None));
    }

    // `Text::get("key", Some("Source"), ...)`.
    let (value_at, wrapped) = match content[value_at..].strip_prefix("Some(") {
        Some(_) if accepts_option => (skip_whitespace(content, value_at + "Some(".len()), true),
        _ => (value_at, false),
    };

    let (value, after_value) = value_literal(content, value_at, language)?;
    let mut following = skip_whitespace(content, after_value);

    if wrapped {
        if !content[following..].starts_with(')') {
            return None;
        }

        following = skip_whitespace(content, following + 1);
    }

    // The text has to end where the call does or at the next argument, which rules out
    // `text("key", "a".to_owned() + b)`.
    matches!(content[following..].chars().next(), Some(',' | ')')).then_some((key, Some(value)))
}

/// The key of a call: a literal string on one line, without quotes of either kind inside.
fn key_literal(content: &str, at: usize, language: Language) -> Option<(String, usize)> {
    let quote = content[at..].chars().next()?;

    let raw_prefix = if language == Language::Rust {
        raw_start(&content[at..])
    } else {
        None
    };

    if let Some((hashes, open)) = raw_prefix {
        let start = at + open;
        let close = format!("\"{}", "#".repeat(hashes));
        let end = content[start..].find(&close)? + start;
        let key = &content[start..end];

        return (!key.contains('\n') && !key.contains('\r')).then(|| (key.to_owned(), end + close.len()));
    }

    let allowed = match language {
        Language::Rust => quote == '"',
        Language::Template => matches!(quote, '"' | '\''),
    };

    if !allowed {
        return None;
    }

    let start = at + 1;
    let end = content[start..].find(quote)? + start;
    let key = &content[start..end];

    // Neither a line break nor, as in PHP, a quote of the other kind.
    let forbidden: &[char] = match language {
        Language::Rust => &['\n', '\r'],
        Language::Template => &['\n', '\r', '"', '\''],
    };

    (!key.contains(forbidden)).then(|| (key.to_owned(), end + 1))
}

/// A literal that may span lines, with its escapes read.
fn value_literal(content: &str, at: usize, language: Language) -> Option<(String, usize)> {
    if language == Language::Rust
        && let Some((hashes, open)) = raw_start(&content[at..])
    {
        let start = at + open;
        let close = format!("\"{}", "#".repeat(hashes));
        let end = content[start..].find(&close)? + start;

        return Some((content[start..end].to_owned(), end + close.len()));
    }

    let quote = content[at..].chars().next()?;

    let allowed = match language {
        Language::Rust => quote == '"',
        Language::Template => matches!(quote, '"' | '\''),
    };

    if !allowed {
        return None;
    }

    let start = at + 1;
    let mut index = start;

    loop {
        let character = content[index..].chars().next()?;

        if character == quote {
            let raw = &content[start..index];
            let value = match language {
                Language::Rust => unescape_rust(raw),
                Language::Template => scripts::unescape(raw),
            };

            return Some((value, index + 1));
        }

        if character == '\\' {
            let escaped = content[index + 1..].chars().next()?;

            index += 1 + escaped.len_utf8();

            continue;
        }

        index += character.len_utf8();
    }
}

/// `r"`, `r#"`, `r##"`: how many hashes, and how many bytes the opening takes.
fn raw_start(rest: &str) -> Option<(usize, usize)> {
    let after = rest.strip_prefix('r')?;
    let hashes = after.bytes().take_while(|byte| *byte == b'#').count();

    after[hashes..].starts_with('"').then_some((hashes, 1 + hashes + 1))
}

/// The escapes of a Rust string literal: `\n`, `\r`, `\t`, `\\`, `\0`, `\'`, `\"`, `\xNN`,
/// `\u{...}`, and a backslash before a line break, which also drops the indentation of the next
/// line.
pub fn unescape_rust(string: &str) -> String {
    let mut result = String::with_capacity(string.len());
    let mut characters = string.char_indices().peekable();

    while let Some((index, character)) = characters.next() {
        if character != '\\' {
            result.push(character);

            continue;
        }

        let Some((_, escaped)) = characters.next() else {
            result.push('\\');

            break;
        };

        match escaped {
            'n' => result.push('\n'),
            'r' => result.push('\r'),
            't' => result.push('\t'),
            '0' => result.push('\0'),
            '\\' | '\'' | '"' => result.push(escaped),
            'x' => {
                let digits = string.get(index + 2..index + 4).unwrap_or_default();

                match u8::from_str_radix(digits, 16) {
                    Ok(code) => {
                        result.push(char::from(code));
                        characters.next();
                        characters.next();
                    }
                    Err(_) => result.push('x'),
                }
            }
            'u' if string[index + 2..].starts_with('{') => {
                let close = string[index + 2..].find('}').map(|close| close + index + 2);

                match close.and_then(|close| {
                    u32::from_str_radix(&string[index + 3..close], 16)
                        .ok()
                        .map(|code| (close, code))
                }) {
                    Some((close, code)) => {
                        result.extend(char::from_u32(code));

                        while characters.peek().is_some_and(|(next, _)| *next <= close) {
                            characters.next();
                        }
                    }
                    None => result.push('u'),
                }
            }
            '\n' | '\r' => {
                while characters
                    .peek()
                    .is_some_and(|(_, next)| matches!(next, ' ' | '\t' | '\n' | '\r'))
                {
                    characters.next();
                }
            }
            other => result.push(other),
        }
    }

    result
}

/// The directories the project scan never enters, anywhere in the tree.
const EXCLUDED: [&str; 5] = ["vendor", "node_modules", "storage", "tests", "target"];

/// The Rust and template files of the project, in path order.
///
/// `vendor`, `node_modules`, `storage`, `tests` and `target` are left out wherever they are, so is
/// `bootstrap/cache`, and so is anything whose name starts with a dot.
pub fn project_files(base: &Path) -> Vec<PathBuf> {
    let mut files = Vec::new();

    walk(base, base, &mut files, &|path| {
        matches!(
            path.extension().and_then(|extension| extension.to_str()),
            Some("rs" | "html")
        )
    });

    files.sort();

    files
}

/// The script files under the configured folders, in path order, or `None` when none is configured
/// or none exists.
pub fn script_files() -> Option<Vec<(PathBuf, String)>> {
    let (paths, extensions) = settings(|config| {
        (
            config.scan.scripts.paths.clone(),
            config.scan.scripts.extensions.clone(),
        )
    });
    let base = base_path();

    let roots: Vec<PathBuf> = paths
        .iter()
        .map(|path| {
            let path = Path::new(path);

            if path.is_absolute() {
                path.to_owned()
            } else {
                base.join(path)
            }
        })
        .filter(|path| path.is_dir())
        .collect();

    if roots.is_empty() {
        return None;
    }

    let extensions: Vec<String> = extensions
        .iter()
        .map(|extension| extension.trim_start_matches('.').to_owned())
        .collect();
    let mut files = Vec::new();

    for root in &roots {
        let mut found = Vec::new();

        walk_scripts(root, &mut found, &|path| {
            let name = path.file_name().and_then(|name| name.to_str()).unwrap_or_default();

            !(name.ends_with(".d.ts") || name.ends_with(".min.js"))
                && path
                    .extension()
                    .and_then(|extension| extension.to_str())
                    .is_some_and(|extension| extensions.iter().any(|wanted| wanted == extension))
        });

        for path in found {
            let relative = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().into_owned();

            files.push((path, relative));
        }
    }

    files.sort();

    Some(files)
}

fn walk(base: &Path, directory: &Path, files: &mut Vec<PathBuf>, wanted: &dyn Fn(&Path) -> bool) {
    let Ok(entries) = std::fs::read_dir(directory) else {
        return;
    };

    for entry in entries.flatten() {
        let path = entry.path();
        let name = entry.file_name().to_string_lossy().into_owned();

        if name.starts_with('.') {
            continue;
        }

        let Ok(kind) = entry.file_type() else {
            continue;
        };

        if kind.is_dir() {
            let relative = path.strip_prefix(base).unwrap_or(&path);

            if EXCLUDED.contains(&name.as_str()) || relative == Path::new("bootstrap/cache") {
                continue;
            }

            walk(base, &path, files, wanted);
        } else if kind.is_file() && wanted(&path) {
            files.push(path);
        }
    }
}

fn walk_scripts(directory: &Path, files: &mut Vec<PathBuf>, wanted: &dyn Fn(&Path) -> bool) {
    let Ok(entries) = std::fs::read_dir(directory) else {
        return;
    };

    for entry in entries.flatten() {
        let path = entry.path();
        let name = entry.file_name().to_string_lossy().into_owned();

        if name.starts_with('.') {
            continue;
        }

        let Ok(kind) = entry.file_type() else {
            continue;
        };

        if kind.is_dir() {
            if name != "node_modules" {
                walk_scripts(&path, files, wanted);
            }
        } else if kind.is_file() && wanted(&path) {
            files.push(path);
        }
    }
}

/// Everything the scanner reads in the project: the Rust and template files, in path order, then
/// the script folders.
pub struct Scan {
    /// `[key => source text]`.
    pub texts: IndexMap<String, String>,
    /// The script calls that could not be read, as `(file, line, call)`.
    pub unreadable: Vec<(String, usize, String)>,
}

/// Scan the project at its base path.
pub fn scan_project() -> Scan {
    let mut texts: IndexMap<String, String> = IndexMap::new();

    for path in project_files(&base_path()) {
        let Ok(content) = std::fs::read_to_string(&path) else {
            continue;
        };

        let language = if path.extension().is_some_and(|extension| extension == "rs") {
            Language::Rust
        } else {
            Language::Template
        };

        for (key, text) in extract_texts(&content, language) {
            texts.insert(key, text);
        }
    }

    let mut unreadable = Vec::new();

    if let Some(files) = script_files() {
        let extractor = ScriptTexts::new(settings(|config| config.scan.scripts.functions.clone()));

        for (path, relative) in files {
            let Ok(bytes) = std::fs::read(&path) else {
                continue;
            };

            let found = extractor.extract_bytes(&bytes);

            for (key, text) in found.texts {
                texts.insert(key, text);
            }

            for call in found.unreadable {
                unreadable.push((relative.clone(), call.line, call.call));
            }
        }
    }

    Scan { texts, unreadable }
}