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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
//! The commands: `laratext:scan`, `laratext:lock`, `laratext:unlock` and `make:translator`, with the
//! names, arguments and options of the PHP package, and `laratext:publish`, which Laravel Rust
//! needs for the JavaScript module.

use std::path::Path;
use std::sync::Arc;

use indexmap::{IndexMap, IndexSet};
use laravel::console::{Console, command};
use laravel::container::Inject;
use laravel::str::Str;
use serde_json::Value;
use tokio::sync::mpsc;

use crate::catalog::{Catalog, Lines};
use crate::locks::TranslationLocks;
use crate::sources::scan_project;
use crate::support::{base_path, config, lang_file, source_locale};
use crate::translator::{Texts, Translations, Translator, with_messages};
use crate::translators::Translators;

/// Scan project files and update translation files with missing keys.
#[command("laratext:scan")]
pub async fn scan(
    /// Write missing keys to lang files
    #[arg(long)]
    write: bool,
    /// Target specific language
    #[arg(long)]
    lang: Option<String>,
    /// Dry run, do not write
    #[arg(long)]
    dry: bool,
    /// Show diff of changes
    #[arg(long)]
    diff: bool,
    /// Retranslate every key from scratch, ignoring existing translations
    #[arg(long)]
    resync: bool,
    /// Only translate brand-new keys; skip keys whose source text has drifted
    #[arg(long)]
    only_missing: bool,
    /// Remove keys present in lang files but no longer found in code
    #[arg(long)]
    prune: bool,
    /// Translator service to use (optional)
    #[arg(long)]
    translator: Option<String>,
    console: &mut Console,
    translators: Inject<Translators>,
) -> laravel::Result<u8> {
    console.info("Scanning project for translation keys...");

    let scanned = scan_project();
    let texts = scanned.texts;

    if !scanned.unreadable.is_empty() {
        console.warn(format!(
            "⚠️  {} call(s) in scripts could not be read: the key and the text must be literal strings.",
            scanned.unreadable.len()
        ));

        for (path, line, call) in &scanned.unreadable {
            console.line(format!("   • {path}:{line}  {call}"));
        }
    }

    if texts.is_empty() {
        console.info("No translation keys found.");

        return Ok(0);
    }

    console.info(format!("Found {} unique keys.", texts.len()));

    let translator = if dry {
        None
    } else {
        match resolve_translator(&translators, translator.as_deref()) {
            Ok(translator) => translator,
            Err(message) => {
                console.error(message);

                return Ok(1);
            }
        }
    };

    let languages: Vec<String> = match lang.filter(|lang| !lang.is_empty()) {
        Some(lang) => vec![lang],
        None => config().languages.keys().cloned().collect(),
    };

    // The language the texts in the code are written in. It defaults to the application locale,
    // which is the same thing in most projects, but not in one that runs in Spanish while writing
    // its source texts in English.
    let default_language = source_locale();

    // Load existing translations per language.
    let mut existing: IndexMap<String, Lines> = IndexMap::new();

    for language in &languages {
        let path = lang_file(language);

        match Catalog::read(&path) {
            Ok(lines) => {
                existing.insert(language.clone(), lines.unwrap_or_default());
            }
            Err(error) => {
                console.error(format!("{} is not a valid language file: {error}", path.display()));

                return Ok(1);
            }
        }
    }

    // Determine which keys need translating.
    //   --resync       -> everything, from scratch
    //   --only-missing -> brand-new keys only, skip drifted keys (warn about them)
    //   default        -> new keys + drifted keys
    let mut missing: Texts = Texts::new();
    let mut stale: IndexMap<String, (String, String)> = IndexMap::new();
    let mut skipped_stale: IndexMap<String, (String, String)> = IndexMap::new();

    'keys: for (key, value) in &texts {
        if resync {
            missing.insert(key.clone(), value.clone());

            continue;
        }

        // Missing in any language: a new key, which must be translated.
        for language in &languages {
            if !existing.get(language).is_some_and(|lines| lines.contains_key(key)) {
                missing.insert(key.clone(), value.clone());

                continue 'keys;
            }
        }

        // It exists everywhere; check if the source changed.
        let on_disk = existing.get(&default_language).and_then(|lines| lines.get(key));

        let old = match on_disk {
            None | Some(Value::Null) => None,
            Some(Value::String(old)) if old == value => None,
            Some(Value::String(old)) => Some(old.clone()),
            Some(other) => Some(other.to_string()),
        };

        if let Some(old) = old {
            stale.insert(key.clone(), (old.clone(), value.clone()));

            if only_missing {
                skipped_stale.insert(key.clone(), (old, value.clone()));
            } else {
                missing.insert(key.clone(), value.clone());
            }
        }
    }

    // Report drifted keys that won't be retranslated this run (--only-missing).
    if !skipped_stale.is_empty() {
        let targets: Vec<&str> = languages
            .iter()
            .map(String::as_str)
            .filter(|language| *language != default_language)
            .collect();

        console.warn(format!(
            "⚠️  {} key(s) have an updated source text but stale translations in {}:",
            skipped_stale.len(),
            targets.join(", ")
        ));

        drift(console, &skipped_stale);

        console.info("Drop --only-missing to retranslate them, or edit the JSON files manually.");
    } else if !stale.is_empty() {
        // The default path: announce what is about to be retranslated because of source drift.
        console.info(format!(
            "ℹ️  {} key(s) will be retranslated because their source text changed:",
            stale.len()
        ));

        drift(console, &stale);
    }

    // Detect orphan keys present in lang files but no longer referenced in code.
    let existing_keys: IndexSet<&String> = existing.values().flat_map(IndexMap::keys).collect();
    let orphans: Vec<String> = existing_keys
        .into_iter()
        .filter(|key| !texts.contains_key(*key))
        .cloned()
        .collect();

    let mut prune_will_write = false;

    if !orphans.is_empty() {
        console.warn(format!(
            "🧹 {} key(s) found in lang files but no longer in code:",
            orphans.len()
        ));

        for key in &orphans {
            console.line(format!("   • {key}"));
        }

        if prune {
            if !write {
                console.info("Run with --write to actually remove them.");
            } else {
                for language in &languages {
                    // Locked keys survive pruning too: the scanner never writes them, and removing
                    // one is writing.
                    let removable: Vec<&String> = orphans
                        .iter()
                        .filter(|key| !TranslationLocks::is_locked(language, key))
                        .collect();

                    if let Some(lines) = existing.get_mut(language) {
                        for key in removable {
                            lines.shift_remove(key);
                        }
                    }
                }

                prune_will_write = true;

                console.info(format!(
                    "Pruned {} orphan key(s). They will be removed when files are written below.",
                    orphans.len()
                ));
            }
        } else {
            console.info("Run with --prune --write to remove them.");
        }
    }

    // A key locked in every target language would be translated and then thrown away when writing,
    // so it is dropped here and no tokens are spent on it.
    let locked_everywhere: Vec<String> = missing
        .keys()
        .filter(|key| {
            languages
                .iter()
                .all(|language| TranslationLocks::is_locked(language, key))
        })
        .cloned()
        .collect();

    if !locked_everywhere.is_empty() {
        for key in &locked_everywhere {
            missing.shift_remove(key);
        }

        console.line(format!(
            "🔒 {} key(s) not sent to the translator, they are locked in every language.",
            locked_everywhere.len()
        ));
    }

    // Everything above is comparison, and none of it calls the translator, so a dry run reports
    // what would happen and stops here.
    if dry {
        dry_run(console, &missing, &stale, &orphans);

        return Ok(0);
    }

    if missing.is_empty() && !prune_will_write {
        console.info("No new keys to translate.");

        return Ok(0);
    }

    let mut translations = Translations::new();

    if !missing.is_empty() {
        match translator {
            Some(translator) => match translate(console, translator, &missing, &default_language, &languages).await {
                Ok(translated) => translations = translated,
                Err(message) => {
                    console.error(message);

                    return Ok(1);
                }
            },
            None => {
                for (key, value) in &missing {
                    translations.insert(
                        key.clone(),
                        languages
                            .iter()
                            .map(|language| (language.clone(), value.clone()))
                            .collect(),
                    );
                }
            }
        }
    }

    for language in &languages {
        let path = lang_file(language);
        let mut current = existing.get(language).cloned().unwrap_or_default();
        let mut skipped = 0;

        for (key, translated) in &translations {
            // A locked key is never written, whoever asked for it.
            if TranslationLocks::is_locked(language, key) {
                skipped += 1;

                continue;
            }

            let text = translated.get(language).cloned().unwrap_or_else(|| key.clone());

            current.insert(key.clone(), Value::String(text));
        }

        if skipped > 0 {
            console.line(format!(
                "🔒 {language}: {skipped} key(s) kept as they are, they are locked."
            ));
        }

        if diff {
            console.info(format!("Diff for {language}:"));

            for (key, translated) in &translations {
                if let Some(text) = translated.get(language)
                    && !TranslationLocks::is_locked(language, key)
                {
                    console.line(format!("+ \"{key}\": \"{text}\""));
                }
            }
        }

        if write {
            if let Err(error) = Catalog::write(&path, &current) {
                console.error(format!("Could not write {}: {error}", path.display()));

                return Ok(1);
            }

            console.info(format!("Translation file updated: {}", path.display()));
        } else {
            console.info(format!("Run with --write to save changes for {language}."));
        }
    }

    console.info("All translations processed.");

    Ok(0)
}

/// Translate with the messages of the translator shown as they arrive.
async fn translate(
    console: &mut Console,
    translator: Arc<dyn Translator>,
    missing: &Texts,
    from: &str,
    languages: &[String],
) -> Result<Translations, String> {
    let (sender, mut receiver) = mpsc::unbounded_channel::<String>();

    let work = with_messages(sender, translator.batch_translate(missing, from, languages));

    tokio::pin!(work);

    let result = loop {
        tokio::select! {
            result = &mut work => break result,
            Some(message) = receiver.recv() => {
                console.new_line();
                console.line(message);
            }
        }
    };

    // What the translator said just before it finished.
    while let Ok(message) = receiver.try_recv() {
        console.new_line();
        console.line(message);
    }

    result.map_err(|error| error.to_string())
}

/// Resolve the translator from the command option or the configuration.
///
/// Without an option the configured `default_translator` is used, and without one, the first
/// registered translator. `None` when there is none, which copies the source text into every
/// language.
fn resolve_translator(translators: &Translators, option: Option<&str>) -> Result<Option<Arc<dyn Translator>>, String> {
    let name = match option.filter(|name| !name.is_empty()) {
        Some(name) => name.to_owned(),
        None => {
            let default = config().default_translator;

            if default.is_empty() {
                return Ok(translators.first());
            }

            default
        }
    };

    match translators.make(&name) {
        Some(translator) => Ok(Some(translator)),
        None => Err(format!(
            "Unknown translator [{name}]. Registered translators: {}.",
            translators.names().join(", ")
        )),
    }
}

fn drift(console: &mut Console, keys: &IndexMap<String, (String, String)>) {
    for (key, (old, new)) in keys {
        console.line(format!("   • {key}"));
        console.line(format!("       old: \"{old}\""));
        console.line(format!("       new: \"{new}\""));
    }
}

/// Report what a real run would do, without calling the translator.
fn dry_run(console: &mut Console, missing: &Texts, stale: &IndexMap<String, (String, String)>, orphans: &[String]) {
    // A drifted key is also a missing one unless --only-missing was passed, so it is reported on
    // its own to keep the counts honest.
    let new: Vec<(&String, &String)> = missing.iter().filter(|(key, _)| !stale.contains_key(*key)).collect();
    let drifted: Vec<(&String, &String)> = missing.iter().filter(|(key, _)| stale.contains_key(*key)).collect();

    console.new_line();
    console.info("Dry run, nothing was written and the translator was not called.");

    console.line(format!("   {} new key(s)", new.len()));
    console.line(format!(
        "   {} key(s) with a changed source text, {} of them would be retranslated",
        stale.len(),
        drifted.len()
    ));
    console.line(format!("   {} orphan key(s) in the language files", orphans.len()));

    if missing.is_empty() {
        console.info("Nothing would be sent to the translator.");
    } else {
        console.info(format!("{} key(s) would be sent to the translator.", missing.len()));
    }

    for (key, value) in new {
        console.line(format!("+ {key}: {value}"));
    }

    for (key, value) in drifted {
        console.line(format!("~ {key}: {value}"));
    }
}

/// Lock translation keys so laratext:scan never overwrites or prunes them.
#[command("laratext:lock")]
pub async fn lock(
    /// The key to lock, wildcards allowed (errors.*)
    key: Option<String>,
    /// Lock every key currently present in the language file
    #[arg(long)]
    all: bool,
    /// Target a single language instead of all of them
    #[arg(long)]
    lang: Option<String>,
    console: &mut Console,
) -> laravel::Result<u8> {
    let key = key.filter(|key| !key.is_empty());

    if key.is_none() && !all {
        console.error("Specify a key or use --all.");

        return Ok(1);
    }

    if key.is_some() && all {
        console.error("Use either a key or --all, not both.");

        return Ok(1);
    }

    let languages = target_languages(lang);

    if languages.is_empty() {
        console.error("No languages configured in languages.");

        return Ok(1);
    }

    for language in languages {
        let keys: Vec<String> = if all {
            keys_of(&language)
        } else {
            key.iter().cloned().collect()
        };

        if keys.is_empty() {
            console.line(format!("{language}: nothing to lock."));

            continue;
        }

        let added = TranslationLocks::lock(&language, &keys)?;

        console.info(format!(
            "{language}: {} key(s) locked, {} already were.",
            added.len(),
            keys.len() - added.len()
        ));
    }

    Ok(0)
}

/// Unlock translation keys so laratext:scan can overwrite them again.
#[command("laratext:unlock")]
pub async fn unlock(
    /// The key to unlock, wildcards allowed (errors.*)
    key: Option<String>,
    /// Unlock every locked key
    #[arg(long)]
    all: bool,
    /// Target a single language instead of all of them
    #[arg(long)]
    lang: Option<String>,
    /// Skip the confirmation of --all
    #[arg(long)]
    force: bool,
    console: &mut Console,
) -> laravel::Result<u8> {
    let key = key.filter(|key| !key.is_empty());

    if key.is_none() && !all {
        console.error("Specify a key or use --all.");

        return Ok(1);
    }

    if key.is_some() && all {
        console.error("Use either a key or --all, not both.");

        return Ok(1);
    }

    let languages = target_languages(lang);

    if languages.is_empty() {
        console.error("No languages configured in languages.");

        return Ok(1);
    }

    if all && !confirm_unlock_all(console, &languages, force).await? {
        console.info("Nothing was unlocked.");

        return Ok(0);
    }

    for language in languages {
        let keys: Vec<String> = if all {
            TranslationLocks::all(&language)
        } else {
            key.iter().cloned().collect()
        };

        let removed = TranslationLocks::unlock(&language, &keys)?;

        console.info(format!("{language}: {} key(s) unlocked.", removed.len()));
    }

    Ok(0)
}

/// Ask before unlocking everything, since the damage only shows up on the next scan, when the
/// translations are overwritten.
async fn confirm_unlock_all(console: &mut Console, languages: &[String], force: bool) -> laravel::Result<bool> {
    if force {
        return Ok(true);
    }

    let total: usize = languages
        .iter()
        .map(|language| TranslationLocks::all(language).len())
        .sum();

    if total == 0 {
        return Ok(true);
    }

    Ok(console
        .confirm(format!(
            "This unlocks {total} key(s) in {}. The next scan may overwrite them. Continue?",
            languages.join(", ")
        ))
        .default(false)
        .await?)
}

fn target_languages(lang: Option<String>) -> Vec<String> {
    match lang.filter(|lang| !lang.is_empty()) {
        Some(lang) => vec![lang],
        None => config().languages.keys().cloned().collect(),
    }
}

/// Keys currently present in the language file.
fn keys_of(language: &str) -> Vec<String> {
    match Catalog::read(&lang_file(language)) {
        Ok(Some(lines)) => lines.keys().cloned().collect(),
        _ => Vec::new(),
    }
}

/// Create a new translator.
#[command("make:translator")]
pub async fn make_translator(
    /// The name of the translator
    name: String,
    console: &mut Console,
) -> laravel::Result<u8> {
    let name = name.trim().to_owned();

    let valid = name.len() >= 2
        && name.chars().next().is_some_and(|first| first.is_ascii_uppercase())
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');

    if !valid {
        console.error("The name must be a valid type name (StudlyCase).");

        return Ok(1);
    }

    let path = base_path().join("src/translators").join(format!("{}.rs", name.snake()));

    if path.exists() {
        console.error("❌ Translator already exists!");

        return Ok(1);
    }

    let content = TRANSLATOR_STUB.replace("{{ class }}", &name);

    if let Some(directory) = path.parent() {
        std::fs::create_dir_all(directory)?;
    }

    std::fs::write(&path, content)?;

    console.info(format!("✅ Translator created successfully at: {}", path.display()));
    console.info(format!(
        "💡 Tip: declare the module and register it with LaratextServiceProvider::new().translator(\"{}\", || {name}) to use it!",
        name.snake().trim_end_matches("_translator")
    ));

    Ok(0)
}

const TRANSLATOR_STUB: &str = include_str!("stubs/translator.stub");

/// Copy the JavaScript module into the application, for a bundler to import.
#[command("laratext:publish")]
pub async fn publish(
    /// Where to put the module, relative to the base path
    #[arg(long, default_value = "resources/js/vendor/laratext")]
    to: String,
    /// Overwrite the files that are already there
    #[arg(long)]
    force: bool,
    console: &mut Console,
) -> laravel::Result<u8> {
    let target = base_path().join(&to);
    let mut written = 0;

    for (name, content) in crate::js::FILES {
        let path = target.join(name);

        if path.exists() && !force {
            console.warn(format!(
                "{} exists, skipped. Use --force to overwrite it.",
                relative(&path)
            ));

            continue;
        }

        if let Some(directory) = path.parent() {
            std::fs::create_dir_all(directory)?;
        }

        std::fs::write(&path, content)?;

        written += 1;
    }

    console.info(format!("{written} file(s) written to {to}."));

    Ok(0)
}

fn relative(path: &Path) -> String {
    path.display().to_string()
}