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
//! <h2>lo<span style="color:Silver;">calizati</span>on</h2>
//!
//! A very simple localization/internationalization provider, inspired by `ruby-i18n`.
//!
//! ## Usage:
//!
//! ```rust
//! fn main() {
//!
//!     use loon::*;
//!     
//!     set_config(PathPattern("examples/locales/*.yml")).unwrap();
//!
//!     assert_eq!(
//!         t("custom.greeting", Var("name", "Jacob")).unwrap(),
//!         String::from("Hello, Jacob!!!")
//!     );
//!
//!     assert_eq!(
//!         t("greeting", Opts::default().locale("de")).unwrap(),
//!         String::from("Hallo Welt!")
//!     );
//! }
//! ```
//!
//! ## Features
//!
//! Translation files can be:
//! * JSON
//! * YAML (enabled by default, disable with `default-features = false`), or
//! * TOML (enable with `features = ["toml"]`).

/// Error management
pub mod err {

    /// Error container
    #[derive(thiserror::Error, Debug)]
    pub enum Error {
        #[error("IO error: `{0}`")]
        Io(#[from] std::io::Error),
        #[error("strfmt error: `{0}`")]
        Strfmt(#[from] strfmt::FmtError),
        #[cfg(feature = "yaml")]
        #[error("YAML error: {0}")]
        Yaml(#[from] serde_yaml::Error),
        #[error("JSON error: {0}")]
        Json(#[from] serde_json::Error),
        #[cfg(feature = "toml")]
        #[error("TOML error: {0}")]
        Toml(#[from] toml::de::Error),
        #[error("Error: {0}")]
        Custom(Box<str>),
        #[error("Unknown locale: {0}")]
        UnknownLocale(Box<str>),
        #[error("Unknown key: {0}")]
        UnknownKey(Box<str>),
    }

    /// Create a custom error.
    pub fn custom<T: std::fmt::Display>(t: T) -> Error {
        Error::Custom(t.to_string().into_boxed_str())
    }

    pub type Result<T> = std::result::Result<T, Error>;
}

mod config;
mod key;
mod opts;

use once_cell::sync::{Lazy, OnceCell};
use std::collections::HashMap;

pub use config::{Config, DefaultLocale, LocalizedPath, PathPattern};
pub use key::Key;
pub use opts::{Count, DefaultKey, Locale, Opts, Var};

/// Container for translation messages
#[derive(Debug)]
pub struct Dictionary {
    inner: HashMap<String, serde_json::Value>,
    default_locale: String,
}

impl Default for Dictionary {
    fn default() -> Self {
        Self { inner: HashMap::new(), default_locale: "en".into() }
    }
}

impl Dictionary {
    /// Get the translated message.
    ///
    /// `key` can be a dot-delimited `&str` or a `&[&str]` path.
    ///
    /// `opts` can be an `Opts` object, `None`, or `Var, `Count`, `Locale`, or `DefaultKey` (or up
    /// to a `4-tuple` of these items).
    ///
    /// Examples:
    /// ```rust, norun
    /// use loon::*;
    /// let dict = Dictionary::default();
    /// let _ = dict.translate("custom.greeting", Opts::default().var("name", "Jacob"));
    /// let _ = dict.translate(&["custom", "greeting"], Var("name", "Jacob"));    
    /// let _ = dict.translate("greeting", None);
    /// let _ = dict.translate("greeting", (Locale("de"), (DefaultKey("missing.message"))));
    /// ```
    pub fn translate<'a, K: Into<Key<'a>>, I: Into<Opts<'a>>>(
        &self,
        key: K,
        opts: I,
    ) -> err::Result<String> {
        let opts = opts.into();

        let mut key = key.into();

        let alt_key;

        match opts.count {
            Some(0) => {
                alt_key = key.chain(["zero"].as_ref());
                key = alt_key;
            }
            Some(1) => {
                alt_key = key.chain(["one"].as_ref());
                key = alt_key;
            }
            Some(_) => {
                alt_key = key.chain(["other"].as_ref());
                key = alt_key;
            }
            _ => {}
        }

        let locale = opts.locale.unwrap_or_else(|| &self.default_locale);

        let localized = self
            .inner
            .get(locale)
            .ok_or_else(|| err::Error::UnknownLocale(String::from(locale).into_boxed_str()))?;

        let entry = |key: Key| {
            key.find(localized)
                .and_then(|val| val.as_str())
                .map(String::from)
                .ok_or_else(|| err::Error::UnknownKey(key.to_string().into_boxed_str()))
        };

        let value = match entry(key) {
            Ok(value) => value,
            Err(e) => match opts.default_key {
                Some(default_key) => {
                    return entry(default_key);
                }
                _ => {
                    return Err(e);
                }
            },
        };

        match opts.vars {
            Some(vars) => Ok(strfmt::strfmt(&value, &vars)?),
            None => Ok(value),
        }
    }
}

static CONFIG: OnceCell<Config> = OnceCell::new();

/// Sets the `Config` to use for the global `translate` call.
///
/// `config` can be a `Config` object, or `DefaultLocale`, `PathPattern`, or `LocalizedPath` (or up
/// to a `6-tuple` of these items).
///
/// Examples:
/// ```rust, norun
/// loon::set_config(loon::Config::default().with_path_pattern("examples/locales/*.yml"));
/// loon::set_config(loon::PathPattern("examples/locales/*.yml"));
/// loon::set_config((loon::PathPattern("examples/locales/*.yml"), loon::DefaultLocale("en")));
/// ```
pub fn set_config<I: Into<Config>>(config: I) -> err::Result<()> {
    Ok(CONFIG.set(config.into()).map_err(|_| err::custom("`CONFIG` already set"))?)
}

/// Get the translated message, using the global configuration.
///
/// `key` can be a dot-delimited `&str` or a `&[&str]` path.
///
/// `opts` can be an `Opts` object, `None`, or `Var`, `Count`, `Locale`, or `DefaultKey` (or up
/// to a `4-tuple` of these items).
///
/// Examples:
/// ```rust, norun
/// use loon::*;
/// let _ = translate("custom.greeting", Opts::default().var("name", "Jacob"));
/// let _ = translate(&["custom", "greeting"], Var("name", "Jacob"));    
/// let _ = translate("greeting", None);
/// let _ = translate("greeting", (Locale("de"), (DefaultKey("missing.message"))));
/// ```
pub fn translate<'a, K: Into<Key<'a>>, I: Into<Opts<'a>>>(key: K, opts: I) -> err::Result<String> {
    static DICTIONARY_RESULT: Lazy<err::Result<Dictionary>> =
        Lazy::new(|| CONFIG.get_or_init(Config::global).clone().finish());

    DICTIONARY_RESULT.as_ref().map_err(err::custom).and_then(|dict| dict.translate(key, opts))
}

/// Shortcut for `translate`.
///
/// `key` can be a dot-delimited `&str` or a `&[&str]` path.
///
/// `opts` can be an `Opts` object, `None`, or `Var, `Count`, `Locale`, or `DefaultKey` (or up
/// to a `4-tuple` of these items).
///
/// Examples:
/// ```rust, norun
/// use loon::*;
/// let _ = t("custom.greeting", Opts::default().var("name", "Jacob"));
/// let _ = t(&["custom", "greeting"], Var("name", "Jacob"));    
/// let _ = t("greeting", None);
/// let _ = t("greeting", (Locale("de"), (DefaultKey("missing.message"))));
/// ```
pub fn t<'a, K: Into<Key<'a>>, I: Into<Opts<'a>>>(key: K, opts: I) -> err::Result<String> {
    translate(key, opts)
}

#[cfg(test)]
mod tests {

    use crate::*;

    #[test]
    fn it_works() {
        set_config(PathPattern("examples/locales/*.yml")).unwrap();

        assert_eq!(t(&["greeting"], None).unwrap(), String::from("Hello, World!"));

        assert_eq!(
            t("missed", DefaultKey("missing.default")).unwrap(),
            String::from("Sorry, that translation doesn't exist.")
        );

        assert_eq!(
            t(&["custom", "greeting"], Var("name", "Jacob")).unwrap(),
            String::from("Hello, Jacob!!!")
        );

        assert_eq!(
            t("greeting", Opts::default().locale("de")).unwrap(),
            String::from("Hallo Welt!")
        );

        assert_eq!(
            t("messages", Opts::default().count(1)).unwrap(),
            String::from("You have one message.")
        );

        assert_eq!(
            t("messages", Opts::default().count(0)).unwrap(),
            String::from("You have no messages.")
        );

        assert_eq!(t("messages", Count(200)).unwrap(), String::from("You have 200 messages."));

        assert_eq!(
            t(
                "a.very.nested.message",
                (Var("name", "you"), Var("message", "\"a very nested message\""))
            )
            .unwrap(),
            String::from("Hello, you. Your message is: \"a very nested message\"")
        );
    }
}