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
#![allow(clippy::needless_doctest_main)]
//! ![Rust](https://github.com/IMI-eRnD-Be/twine/workflows/Rust/badge.svg)
//! [![Latest Version](https://img.shields.io/crates/v/twine.svg)](https://crates.io/crates/twine)
//! [![Docs.rs](https://docs.rs/twine/badge.svg)](https://docs.rs/twine)
//! [![LOC](https://tokei.rs/b1/github/IMI-eRnD-Be/twine)](https://github.com/IMI-eRnD-Be/twine)
//! [![Dependency Status](https://deps.rs/repo/github/IMI-eRnD-Be/twine/status.svg)](https://deps.rs/repo/github/IMI-eRnD-Be/twine)
//!
//! Library for internationalization using the [Twine](https://github.com/scelis/twine) file
//! format.
//!
//! # Usage
//!
//! 1.  You need to add twine to your `[build-dependencies]` in `Cargo.toml`.
//!
//! 2.  Create (or edit) your `build.rs` file:
//!
//! ```no_run
//! fn main() {
//!     println!("cargo:rerun-if-changed=build.rs");
//!     twine::build_translations(&["translations.ini"], "i18n.rs");
//! }
//! ```
//!
//! 3.  You need an INI file with your translations. Example with `translations.ini`:
//!
//! ```text
//! [app_ruin_the_band]
//!     en = Ruin a band name by translating it in French
//!     fr = Ruiner le nom d'un groupe en le traduisant en français
//! [band_tool]
//!     en = Tool
//!     fr = Outil
//! [band_the_doors]
//!     en = The Doors
//!     fr = Les portes
//! [band_rage_against_the_machine]
//!     en = Rage Against the Machine
//!     en-gb = Wrath Against the Machine
//!     fr = Colère contre la machine
//! [band_the_jackson_5]
//!     en = The Jackson 5
//!     fr = Les 5 fils de Jack
//! [format_string]
//!     en = %s, %@!
//!     fr = %s, %@ !
//! [format_percentage]
//!     en = %.0f%
//!     fr = %.0f %
//! [format_hexadecimal]
//!     en = %x
//!     fr = %#X
//! ```
//!
//! 4.  Now in your project you can use the macro `t!` to translate anything:
//!
//! ```ignore
//! # enum Lang { Fr(&'static str) }
//! # macro_rules! t {
//! # ($($tokens:tt)+) => {{
//! # }};
//! # }
//! // you need to include the generated file somewhere
//! include!(concat!(env!("OUT_DIR"), "/i18n.rs"));
//!
//! fn main() {
//!     // use "" if there is no localization
//!     let lang = Lang::Fr("be");
//!
//!     // will output "Ruiner le nom d'un groupe en le traduisant en français"
//!     t!(app_ruin_the_band => lang);
//!
//!     // using formatted arguments, this will output "73 %"
//!     t!(format_percentage, 73.02f32 => lang);
//! }
//! ```
//!
//! # Implementation Notes
//!
//! All translation keys must have all the languages of all the keys. For example, if all your keys
//! have translations for `en` and `fr`, if one key has only `en`, it will fail to compile.
//!
//! Localized translation can be provided and will be used if available. Otherwise it will
//! fallback to the default translation for that language.
//!
//! Any typo in the key will make the compilation fail. Missing format arguments will also make
//! the compilation fail.
//!
//! # Features
//!
//!  *  `serde`: when this feature is activated you will need to add `serde` to your dependencies
//!     and the `Lang` enum generated implements `Serialize` and `Deserialize`.
//!
//! # License
//!
//! This work is dual-licensed under Apache 2.0 and MIT.
//! You can choose between one of them if you use this work.

use heck::{CamelCase, SnakeCase};
use indenter::CodeFormatter;
use once_cell::sync::Lazy;
use regex::Regex;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::fmt::Write as FmtWrite;
use std::fs;
use std::io;
use std::io::{Read, Write};
use std::path::Path;

// regex that tries to parse printf's format placeholders
// see: https://docs.microsoft.com/en-us/cpp/c-runtime-library/format-specification-syntax-printf-and-wprintf-functions?view=msvc-160
static RE_PRINTF: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"%([-+#])?(\d+)?(\.\d+)?([dis@xXf])|[^%]+|%%|%$").unwrap());
static RE_LANG: Lazy<Regex> = Lazy::new(|| Regex::new(r"(\w+)(-(\w+))?").unwrap());
static RE_SECTION: Lazy<Regex> = Lazy::new(|| Regex::new(r"^\s*\[([^\]]+)\]").unwrap());
static RE_KEY_VALUE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"^\s*([^\s=;#]+)\s*=\s*(.+?)\s*$").unwrap());

type TwineData = HashMap<String, Vec<(String, String)>>;

/// Generate the `t!()` macro based on the provided list of paths to Twine INI translation files.
pub fn build_translations<P: AsRef<Path>, O: AsRef<Path>>(
    ini_files: &[P],
    output_file: O,
) -> io::Result<()> {
    let mut readers = ini_files
        .iter()
        .map(|file_path| {
            let file_path = file_path.as_ref();
            println!("cargo:rerun-if-changed={}", file_path.display());
            fs::File::open(&file_path)
        })
        .collect::<io::Result<Vec<_>>>()?;

    build_translations_from_readers(readers.as_mut_slice(), output_file)
}

/// Generate the `t!()` macro based on the provided list of `&str` containing Twine INI
/// translations.
pub fn build_translations_from_str<P: AsRef<Path>>(
    strs: &[&str],
    output_file: P,
) -> io::Result<()> {
    let mut readers = strs.iter().map(io::Cursor::new).collect::<Vec<_>>();

    build_translations_from_readers(readers.as_mut_slice(), output_file)
}

/// Generate the `t!()` macro based on the provided list of readers containing Twine INI
/// translations.
pub fn build_translations_from_readers<R: Read, P: AsRef<Path>>(
    readers: &mut [R],
    output_file: P,
) -> io::Result<()> {
    let mut map = HashMap::new();

    // read all the INI files (might override existing keys)
    for reader in readers {
        match read_twine_ini(reader) {
            Err(err) => panic!("could not read Twine INI file: {}", err),
            Ok(other_map) => map.extend(other_map),
        }
    }

    let out_dir = std::env::var_os("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join(output_file);
    let _ = fs::create_dir_all(dest_path.parent().unwrap());
    let mut f = io::BufWriter::new(
        fs::OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(dest_path)?,
    );
    write!(f, "{}", TwineFormatter { map })?;

    Ok(())
}

fn read_twine_ini<R: Read>(reader: &mut R) -> io::Result<TwineData> {
    use std::io::BufRead;

    let mut map: TwineData = HashMap::new();
    let mut section = None;

    let reader = io::BufReader::new(reader);
    for (i, line) in reader.lines().enumerate() {
        let line = line?;
        if let Some(caps) = RE_SECTION.captures(line.as_str()) {
            section = Some(
                map.entry(caps.get(1).unwrap().as_str().to_owned())
                    .or_default(),
            );
        }
        if let Some(caps) = RE_KEY_VALUE.captures(line.as_str()) {
            if let Some(section) = section.as_mut() {
                section.push((
                    caps.get(1).unwrap().as_str().to_owned(),
                    caps.get(2).unwrap().as_str().to_owned(),
                ));
            } else {
                panic!("key-value outside section at line {}", i + 1);
            }
        }
    }

    Ok(map)
}

struct TwineFormatter {
    map: TwineData,
}

impl fmt::Display for TwineFormatter {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut f = CodeFormatter::new(f, "    ");
        let mut all_languages = HashSet::new();

        write!(
            f,
            r#"
            #[macro_export]
            macro_rules! t {{
            "#,
        )?;
        f.indent(1);

        let mut sorted: Vec<_> = self.map.iter().collect();
        sorted.sort_unstable_by(|(a_key, _), (b_key, _)| a_key.cmp(b_key));

        for (key, translations) in sorted {
            let key = Self::normalize_key(key.as_str());
            write!(
                f,
                r#"
                ({} $(, $fmt_args:expr)* => $lang:expr) => {{{{
                    match $lang {{
                "#,
                key,
            )?;
            f.indent(2);

            self.generate_match_arms(&mut f, translations, &mut all_languages)?;

            f.dedent(2);
            write!(
                f,
                r#"
                    }}
                }}}};
                "#,
            )?;
        }
        f.dedent(1);

        write!(
            f,
            r#"
            }}
            "#,
        )?;

        // generate the `Lang` enum and its variants
        write!(
            f,
            r#"
            #[derive(Debug, Clone, Copy, PartialEq, Hash)]
            #[allow(dead_code)]
            pub enum Lang {{
            "#,
        )?;
        f.indent(1);

        let lang_variants: HashSet<_> = all_languages
            .iter()
            .map(|(lang, _)| lang.as_str())
            .collect();
        let mut lang_variants: Vec<_> = lang_variants.into_iter().collect();
        lang_variants.sort_unstable();

        for lang in lang_variants.iter() {
            write!(
                f,
                r#"
                {}(&'static str),
                "#,
                lang,
            )?;
        }

        f.dedent(1);
        write!(
            f,
            r#"
            }}

            impl Lang {{
                pub fn all_languages() -> &'static [&'static Lang] {{
                    &[
            "#,
        )?;
        f.indent(3);

        let mut sorted_languages: Vec<_> = all_languages.iter().collect();
        sorted_languages.sort_unstable();

        for (lang, region) in sorted_languages {
            write!(
                f,
                r#"
                &Lang::{}({:?}),
                "#,
                lang,
                region.as_deref().unwrap_or(""),
            )?;
        }

        f.dedent(3);
        write!(
            f,
            r#"
                    ]
                }}
            }}
            "#,
        )?;

        #[cfg(feature = "serde")]
        {
            let mut all_regions: Vec<_> = all_languages
                .iter()
                .filter_map(|(_, region)| region.as_deref())
                .collect();
            all_regions.sort_unstable_by(|a, b| a.cmp(b).reverse());
            Self::generate_serde(&mut f, &lang_variants, &all_regions)?;
        }

        Ok(())
    }
}

impl TwineFormatter {
    #[allow(clippy::single_char_add_str)]
    fn generate_match_arms(
        &self,
        f: &mut CodeFormatter<fmt::Formatter>,
        translations: &[(String, String)],
        all_languages: &mut HashSet<(String, Option<String>)>,
    ) -> fmt::Result {
        let mut match_arms = Vec::new();
        let mut default_out = None;
        for (lang, text) in translations {
            // transform all printf's format placeholder to Rust's format
            let mut out = String::new();
            for caps in RE_PRINTF.captures_iter(text.as_str()) {
                if let Some(type_) = caps.get(4) {
                    out.push_str("{:");
                    if let Some(flag) = caps.get(1) {
                        out.push_str(flag.as_str());
                    }
                    if let Some(width) = caps.get(2) {
                        out.push_str(width.as_str());
                    }
                    if let Some(precision) = caps.get(3) {
                        out.push_str(precision.as_str());
                    }
                    match type_.as_str() {
                        x @ "x" | x @ "X" => out.push_str(x),
                        _ => {}
                    }
                    out.push_str("}");
                } else if &caps[0] == "%%" {
                    out.push_str("%");
                } else {
                    out.push_str(&caps[0]);
                }
            }

            if default_out.is_none() {
                default_out = Some(out.clone());
            }

            // parse the language and region, then push the match arm
            let caps = RE_LANG.captures(lang.as_str()).expect("lang can be parsed");
            let lang = caps
                .get(1)
                .expect("the language is always there")
                .as_str()
                .to_camel_case();
            let region = caps.get(3);
            all_languages.insert((lang.clone(), region.map(|x| x.as_str().to_string())));
            match_arms.push((lang, region.map(|x| format!("{:?}", x.as_str())), out));
        }
        match_arms.sort_unstable_by(|(a_lang, a_region, _), (b_lang, b_region, _)| {
            a_lang
                .cmp(b_lang)
                .then(a_region.is_none().cmp(&b_region.is_none()))
        });

        for (lang, region, format) in match_arms {
            write!(
                f,
                r#"
                $crate::Lang::{}({}) => format!({:?} $(, $fmt_args)*),
                "#,
                lang,
                region.as_deref().unwrap_or("_"),
                format,
            )?;
        }

        if let Some(default_out) = default_out {
            write!(
                f,
                r#"
                _ => format!({:?} $(, $fmt_args)*),
                "#,
                default_out,
            )?;
        }

        Ok(())
    }

    // turns all the keys into snake case automatically
    fn normalize_key(key: &str) -> String {
        key.to_snake_case().replace(".", "__")
    }

    #[cfg(feature = "serde")]
    fn generate_serde(
        f: &mut CodeFormatter<fmt::Formatter>,
        all_languages: &[&str],
        all_regions: &[&str],
    ) -> fmt::Result {
        write!(
            f,
            r#"

            impl<'de> serde::Deserialize<'de> for Lang {{
                fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
                where
                    D: serde::Deserializer<'de>,
                {{
                    use serde::de;
                    use std::fmt;

                    struct LangVisitor;

                    impl<'de> de::Visitor<'de> for LangVisitor {{
                        type Value = Lang;

                        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {{
                            formatter.write_str("expected string")
                        }}

                        fn visit_str<E>(self, value: &str) -> Result<Lang, E>
                        where
                            E: de::Error,
                        {{
                            let mut it = value.splitn(2, '_');
                            let lang = it.next().unwrap();
                            let region = it.next().unwrap_or("");

                            let region = match region.to_lowercase().as_str() {{
            "#,
        )?;
        f.indent(5);

        for region in all_regions {
            write!(
                f,
                r#"
                {region:?} => {region:?},
                "#,
                region = region,
            )?;
        }

        f.dedent(1);
        write!(
            f,
            r#"
                "" => "",
                _ => {{
                    return Err(de::Error::invalid_value(
                        de::Unexpected::Str(region),
                        &"existing region",
                    ));
                }}
            }};

            match lang {{
            "#,
        )?;
        f.indent(1);

        for lang in all_languages {
            write!(
                f,
                r#"
                {:?} => Ok(Lang::{}(region)),
                "#,
                lang.to_snake_case(),
                lang,
            )?;
        }

        f.dedent(5);
        write!(
            f,
            r#"
                                _ => {{
                                    return Err(de::Error::invalid_value(
                                        de::Unexpected::Str(region),
                                        &"existing language",
                                    ));
                                }}
                            }}
                        }}
                    }}

                    deserializer.deserialize_str(LangVisitor)
                }}
            }}

            impl serde::Serialize for Lang {{
                fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
                where
                    S: serde::ser::Serializer,
                {{
                    match self {{
            "#,
        )?;
        f.indent(3);

        for lang in all_languages {
            write!(
                f,
                r#"
                Lang::{variant}(region) if region.is_empty() => serializer.serialize_str({lang:?}),
                Lang::{variant}(region) => serializer.serialize_str(
                    &format!("{{}}_{{}}", {lang:?}, region),
                ),
                "#,
                variant = lang,
                lang = lang.to_snake_case(),
            )?;
        }

        f.dedent(3);
        write!(
            f,
            r#"
                    }}
                }}
            }}
            "#,
        )?;

        Ok(())
    }
}