traduki 0.1.2

Integrate translated assets into your application or library
Documentation
//! Generate key-data

use std::collections::BTreeMap;

#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(crate) struct Key {
    name: String,
    value: BTreeMap<String, String>,
}

impl Key {
    pub(crate) fn new(name: &str) -> Self {
        Self {
            name: name.into(),
            value: BTreeMap::new(),
        }
    }

    /// Add a value for a specific language
    pub(crate) fn add_value<S: Into<String>>(mut self, lang: S, value: S) -> Self {
        self.value.insert(lang.into(), value.into());
        self
    }

    /// Merge another key into this one
    ///
    /// This function will panic if a key is being added that doesn't
    /// exist in the default translation language!
    pub(crate) fn merge<S: Into<String>>(&mut self, lang: S, mut other: Key) {
        let lang = lang.into();
        let value = other
            .value
            .remove(&lang)
            .expect("Assets error: failed to merge two translation keys!");
        self.value.insert(lang, value);
    }

    /// Generate code for this key
    pub(crate) fn generate(self) -> String {
        format!(
            r#"
pub(crate) fn {fun_name}() -> &'static str {{
  match std::env::var("LANG").as_ref().map(|s| s.as_str()) {{
    {lang_section}
    {default_section}
  }}
}}
"#,
            fun_name = self.name,
            lang_section = {
                self.value
                    .iter()
                    .map(|(k, v)| format!(r#"Ok("{}") => "{}""#, k, v))
                    .fold(String::new(), |acc, section| {
                        format!("{}\n{},", acc, section)
                    })
            },
            default_section = format!(
                r#"_ => "{}""#,
                self.value
                    .get(&crate::env::default())
                    .expect("Default translation language missing for key")
            )
        )
    }
}