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
//! Introduction
//! ============
//!
//! This library is only a generic deserializer/API for gettext. With this you can
//! use JSON or YAML (or "any" format handled by serde) to translate text through
//! gettext and even format. It also has an API for strftime for formatting dates.
//!
//! You can use it in an API service to have a translation endpoint or in a lambda
//! to translate the input.
//!
//!  *  Example in JSON
//!
//!     ```json
//!     {
//!         "ngettext": {
//!             "singular": "One item has been deleted",
//!             "plural": "%(n)s items have been deleted",
//!             "n": 5
//!         }
//!     }
//!     ```
//!
//!  *  Example in YAML
//!
//!     ```yaml
//!     ngettext:
//!         singular: One item has been deleted
//!         plural: "%(n)s items have been deleted"
//!         n: 5
//!     ```
//!
//! When the structure is deserialized, you can simply convert it to a translated
//! `String`:
//!
//! ```rust
//! use serde_gettext::SerdeGetText;
//! use std::convert::TryFrom;
//!
//! let yaml = r#"---
//! ngettext:
//!     singular: One item has been deleted
//!     plural: "%(n)s items have been deleted"
//!     n: 5
//! "#;
//! let s: SerdeGetText = serde_yaml::from_str(yaml).unwrap();
//!
//! assert_eq!(String::try_from(s).unwrap(), "5 items have been deleted");
//! ```
//!
//! Formatting
//! ==========
//!
//!  *  Example in JSON
//!
//!     ```json
//!     {
//!         "gettext": "Hello %(name)s!",
//!         "args": {
//!             "name": "Grace"
//!         }
//!     }
//!     ```
//!
//!  *  Example in YAML
//!
//!     ```yaml
//!     gettext: "Hello %(name)s!"
//!     args:
//!         name: Grace
//!     ```
//!
//! `args` can handle many different formats and use positional arguments or
//! keyword arguments:
//!
//! ```yaml
//! gettext: "%s %s %s"
//! args:
//!     - true      # "yes" (translated)
//!     - 3.14      # "3.14"
//!     -           # "n/a" (translated)
//! ```
//!
//! Output: "yes 3.14 n/a"
//!
//! `args` can be added to any function:
//!
//! ```yaml
//! ngettext:
//!     singular: "%(n)s element deleted (success: %(success)s)"
//!     plural: "%(n)s elements deleted (success: %(success)s)"
//!     n: 1
//! args:
//!     success: true
//! ```
//!
//! Output: "1 element deleted (success: yes)"
//!
//! `args` can handle arrays by joining the items:
//!
//! ```yaml
//! gettext: "%(value)s"
//! args:
//!     value:
//!         - ", "      # The separator
//!         - true      # "yes" (translated)
//!         - 3.14      # "3.14"
//!         -           # "n/a" (translated)
//! ```
//!
//! Output: "yes, 3.14, n/a"
//!
//! `args` is recursive and can handle gettext functions:
//!
//! ```yaml
//! gettext: "Last operation status: %(status)s"
//! args:
//!     status:
//!         ngettext:
//!             singular: "%(n)s element deleted (success: %(success)s)"
//!             plural: "%(n)s elements deleted (success: %(success)s)"
//!             n: 1
//!         args:
//!             success: true
//! ```
//!
//! Output: "Last operation status: 1 element deleted (success: yes)"
//!
//! List of All Available Functions
//! ===============================
//!
//!  *  gettext:
//!
//!     ```yaml
//!     gettext: "msgid"
//!     ```
//!
//!  *  ngettext:
//!
//!     ```yaml
//!     ngettext:
//!         singular: "msgid_singular"
//!         plural: "msgid_singular"
//!         n: 5
//!     ```
//!
//!  *  pgettext:
//!
//!     ```yaml
//!     pgettext:
//!         ctx: "context"
//!         msgid: "msgid"
//!     ```
//!
//!  *  dgettext:
//!
//!     ```yaml
//!     dgettext:
//!         domain: "domain"
//!         msgid: "msgid"
//!     ```
//!
//!  *  dngettext:
//!
//!     ```yaml
//!     dngettext:
//!         domain: "domain"
//!         singular: "msgid_singular"
//!         plural: "msgid_singular"
//!         n: 5
//!     ```
//!
//!  *  npgettext:
//!
//!     ```yaml
//!     npgettext:
//!         ctx: "context"
//!         singular: "msgid_singular"
//!         plural: "msgid_singular"
//!         n: 5
//!     ```
//!
//!  *  dcngettext:
//!
//!     ```yaml
//!     dcngettext:
//!         domain: "domain"
//!         singular: "msgid_singular"
//!         plural: "msgid_singular"
//!         n: 5
//!         cateogy: "ctype|numeric|time|collate|monetary|messages|all|paper|name|address|telephone|measurement|identification"
//!     ```
//!
//! Date and Time Formatting
//! ========================
//!
//! You can format date and time in the locale of your choice using strftime:
//!
//! ```yaml
//! strftime: "It is now: %c"
//! epoch: 1565854615
//! ```
//!
//! Output: "It is now: Thu 15 Aug 2019 09:36:55 CEST"
//!
//! You will need to call `set_locale` and `tz_set` from
//! [libc-strftime](https://docs.rs/libc-strftime/) to
//! activate the locale and the timezone for your current region.
//!
//! If you want to change the locale and timezone for the current process, you
//! will need to export `TZ` and `LC_ALL` as environment variable first, then call
//! `set_locale` and `tz_set` again.

#![deny(missing_docs)]

#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate derive_error;

use dynfmt::{Argument, Format, FormatArgs, PythonFormat};
use libc_strftime::strftime_local;
#[allow(unused_imports)]
use serde::Deserialize;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::string::ToString;

/// Runtime error that occurs when the input cannot be formatted
#[derive(Debug, Error)]
pub enum Error {
    /// Formatting error
    #[error(msg_embedded, no_from, non_std)]
    FormatError(String),
    /// Missing join separator
    #[error(non_std, no_from, display = "missing join separator")]
    MissingJoinSeparator,
}

/// A deserializable struct to translate and format
#[derive(Deserialize, Clone, Debug)]
pub struct SerdeGetText {
    #[serde(flatten)]
    value: Value,
    /// Base arguments that can be provided for keywords format
    #[serde(skip)]
    pub args: HashMap<String, String>,
}

impl TryFrom<SerdeGetText> for String {
    type Error = Error;

    fn try_from(x: SerdeGetText) -> Result<String, Error> {
        x.value.try_into_string(&x.args)
    }
}

impl TryFrom<Box<SerdeGetText>> for String {
    type Error = Error;

    fn try_from(x: Box<SerdeGetText>) -> Result<String, Error> {
        String::try_from(*x)
    }
}

#[derive(Deserialize, Clone, Debug)]
#[serde(untagged)]
enum Value {
    Text(String),
    Integer(i64),
    Float(f64),
    Bool(bool),
    Unit(()),
    Datetime(DatetimeValue),
    Array(Vec<Value>),
    FormattedText {
        text: String,
        args: Option<Formatter>,
    },
    GetText {
        gettext: ValueGetText,
        args: Option<Formatter>,
    },
    NGetText {
        ngettext: ValueNGetText,
        args: Option<Formatter>,
    },
    PGetText {
        pgettext: ValuePGetText,
        args: Option<Formatter>,
    },
    DGetText {
        dgettext: ValueDGetText,
        args: Option<Formatter>,
    },
    DNGetText {
        dngettext: ValueDNGetText,
        args: Option<Formatter>,
    },
    NPGetText {
        npgettext: ValueNPGetText,
        args: Option<Formatter>,
    },
    DCNGetText {
        dcngettext: ValueDCNGetText,
        args: Option<Formatter>,
    },
}

macro_rules! handle_gettext {
    ($s:expr, $args:expr, $map:expr, $base_map:expr) => {{
        Self::format(&$s.to_string(), $args, $map, $base_map)
    }};
}

macro_rules! handle_plural {
    ($s:expr, $args:expr, $map:expr, $base_map:expr) => {{
        $map.reserve(match $args.as_ref() {
            Some(Formatter::KeywordArgs(args)) => args.len() + 1,
            _ => 1,
        });
        $map.insert("n".to_string(), $s.n.to_string());

        Self::format(&$s.to_string(), $args, $map, $base_map)
    }};
}

impl Value {
    fn try_into_string(self, base_map: &HashMap<String, String>) -> Result<String, Error> {
        let mut map = HashMap::new();

        match self {
            Value::Text(x) => Ok(x.to_string()),
            Value::Integer(x) => Ok(x.to_string()),
            Value::Float(x) => Ok(x.to_string()),
            Value::Bool(x) => Ok(if x {
                gettextrs::gettext(b"yes" as &[u8])
            } else {
                gettextrs::gettext(b"no" as &[u8])
            }),
            Value::Unit(()) => Ok(gettextrs::gettext(b"n/a" as &[u8])),
            Value::Datetime(x) => Ok(x.to_string()),
            Value::Array(xs) => Ok({
                let mut it = xs.into_iter();
                let sep: String = match it.next() {
                    Some(x) => x.try_into_string(base_map),
                    None => Err(Error::MissingJoinSeparator),
                }?;

                let mut vec: Vec<String> = Vec::new();

                for value in it {
                    vec.push(value.try_into_string(base_map)?);
                }

                vec.join(&sep)
            }),
            Value::FormattedText { text, args } => Self::format(text.as_ref(), args, map, base_map),
            Value::GetText { gettext, args } => handle_gettext!(gettext, args, map, base_map),
            Value::NGetText { ngettext, args } => handle_plural!(ngettext, args, map, base_map),
            Value::PGetText { pgettext, args } => handle_gettext!(pgettext, args, map, base_map),
            Value::DGetText { dgettext, args } => handle_gettext!(dgettext, args, map, base_map),
            Value::DNGetText { dngettext, args } => handle_plural!(dngettext, args, map, base_map),
            Value::NPGetText { npgettext, args } => handle_plural!(npgettext, args, map, base_map),
            Value::DCNGetText { dcngettext, args } => {
                handle_plural!(dcngettext, args, map, base_map)
            }
        }
    }

    fn format(
        message: &str,
        formatter: Option<Formatter>,
        mut map: HashMap<String, String>,
        base_map: &HashMap<String, String>,
    ) -> Result<String, Error> {
        match formatter {
            Some(Formatter::KeywordArgs(kwargs)) => {
                for (key, value) in kwargs.into_iter() {
                    map.insert(key, value.try_into_string(base_map)?);
                }

                PythonFormat
                    .format(message, UnionMap::new(&map, base_map))
                    .map_err(|err| Error::FormatError(format!("{}", err)))
                    .map(|x| x.to_string())
            }
            Some(Formatter::PositionalArgs(args)) => PythonFormat
                .format(
                    message,
                    args.into_iter()
                        .map(|x| x.try_into_string(base_map))
                        .collect::<Result<Vec<String>, _>>()?,
                )
                .map_err(|err| Error::FormatError(format!("{}", err)))
                .map(|x| x.to_string()),
            None => PythonFormat
                .format(message, UnionMap::new(&map, base_map))
                .map_err(|err| Error::FormatError(format!("{}", err)))
                .map(|x| x.to_string()),
        }
    }
}

#[derive(Deserialize, Clone, Debug)]
#[serde(untagged)]
enum Formatter {
    KeywordArgs(HashMap<String, Value>),
    PositionalArgs(Vec<Value>),
}

struct UnionMap<'a>(&'a HashMap<String, String>, &'a HashMap<String, String>);

impl<'a> UnionMap<'a> {
    fn new(a: &'a HashMap<String, String>, b: &'a HashMap<String, String>) -> UnionMap<'a> {
        UnionMap(a, b)
    }
}

impl FormatArgs for UnionMap<'_> {
    fn get_key(&self, key: &str) -> Result<Option<Argument<'_>>, ()> {
        Ok(self
            .0
            .get(key)
            .or_else(|| self.1.get(key))
            .map(|x| x as Argument<'_>))
    }
}

#[derive(Deserialize, Clone, Debug)]
struct DatetimeValue {
    strftime: String,
    epoch: i64,
}

impl ToString for DatetimeValue {
    fn to_string(&self) -> String {
        strftime_local(&self.strftime, self.epoch)
    }
}

#[derive(Deserialize, Clone, Debug)]
struct ValueGetText(String);

impl ToString for ValueGetText {
    fn to_string(&self) -> String {
        gettextrs::gettext(self.0.as_bytes())
    }
}

#[derive(Deserialize, Clone, Debug)]
struct ValueNGetText {
    singular: String,
    plural: String,
    n: u32,
}

impl ToString for ValueNGetText {
    fn to_string(&self) -> String {
        gettextrs::ngettext(self.singular.as_bytes(), self.plural.as_bytes(), self.n)
    }
}

#[derive(Deserialize, Clone, Debug)]
struct ValuePGetText {
    ctx: String,
    msgid: String,
}

impl ToString for ValuePGetText {
    fn to_string(&self) -> String {
        gettextrs::pgettext(self.ctx.as_bytes(), self.msgid.as_bytes())
    }
}

#[derive(Deserialize, Clone, Debug)]
struct ValueDGetText {
    domain: String,
    msgid: String,
}

impl ToString for ValueDGetText {
    fn to_string(&self) -> String {
        gettextrs::dgettext(self.domain.as_bytes(), self.msgid.as_bytes())
    }
}

#[derive(Deserialize, Clone, Debug)]
struct ValueDNGetText {
    domain: String,
    singular: String,
    plural: String,
    n: u32,
}

impl ToString for ValueDNGetText {
    fn to_string(&self) -> String {
        gettextrs::dngettext(
            self.domain.as_bytes(),
            self.singular.as_bytes(),
            self.plural.as_bytes(),
            self.n,
        )
    }
}

#[derive(Deserialize, Clone, Debug)]
struct ValueNPGetText {
    ctx: String,
    singular: String,
    plural: String,
    n: u32,
}

impl ToString for ValueNPGetText {
    fn to_string(&self) -> String {
        gettextrs::npgettext(
            self.ctx.as_bytes(),
            self.singular.as_bytes(),
            self.plural.as_bytes(),
            self.n,
        )
    }
}

#[derive(Deserialize, Clone, Debug)]
struct ValueDCNGetText {
    domain: String,
    singular: String,
    plural: String,
    n: u32,
    category: LocaleCategory,
}

#[derive(Deserialize, Debug, PartialEq, Clone, Copy)]
#[allow(clippy::enum_variant_names)]
enum LocaleCategory {
    #[serde(rename = "ctype")]
    LcCType,
    #[serde(rename = "numeric")]
    LcNumeric,
    #[serde(rename = "time")]
    LcTime,
    #[serde(rename = "collate")]
    LcCollate,
    #[serde(rename = "monetary")]
    LcMonetary,
    #[serde(rename = "messages")]
    LcMessages,
    #[serde(rename = "all")]
    LcAll,
    #[serde(rename = "paper")]
    LcPaper,
    #[serde(rename = "name")]
    LcName,
    #[serde(rename = "address")]
    LcAddress,
    #[serde(rename = "telephone")]
    LcTelephone,
    #[serde(rename = "measurement")]
    LcMeasurement,
    #[serde(rename = "identification")]
    LcIdentification,
}

impl std::convert::From<LocaleCategory> for gettextrs::LocaleCategory {
    fn from(category: LocaleCategory) -> Self {
        use gettextrs::LocaleCategory::*;

        match category {
            LocaleCategory::LcCType => LcCType,
            LocaleCategory::LcNumeric => LcNumeric,
            LocaleCategory::LcTime => LcTime,
            LocaleCategory::LcCollate => LcCollate,
            LocaleCategory::LcMonetary => LcMonetary,
            LocaleCategory::LcMessages => LcMessages,
            LocaleCategory::LcAll => LcAll,
            LocaleCategory::LcPaper => LcPaper,
            LocaleCategory::LcName => LcName,
            LocaleCategory::LcAddress => LcAddress,
            LocaleCategory::LcTelephone => LcTelephone,
            LocaleCategory::LcMeasurement => LcMeasurement,
            LocaleCategory::LcIdentification => LcIdentification,
        }
    }
}

impl ToString for ValueDCNGetText {
    fn to_string(&self) -> String {
        gettextrs::dcngettext(
            self.domain.as_bytes(),
            self.singular.as_bytes(),
            self.plural.as_bytes(),
            self.n,
            self.category.into(),
        )
    }
}