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
use std::{
    collections::HashMap,
    env,
    fmt::{self, Display},
    fs::File,
    io::Write,
    path::{Path, PathBuf},
    str::FromStr,
};

use tinyjson::JsonValue;

use crate::{
    error::{BuildError, ConfigError},
    gen, parser,
};

/// Helper function that return an default [`RosettaBuilder`].
pub fn config() -> RosettaBuilder {
    RosettaBuilder::default()
}

/// Builder used to configure Rosetta code generation.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RosettaBuilder {
    files: HashMap<String, PathBuf>,
    fallback: Option<String>,
    name: Option<String>,
    output: Option<PathBuf>,
}

impl RosettaBuilder {
    /// Register a new translation source
    pub fn source(mut self, lang: impl Into<String>, path: impl Into<String>) -> Self {
        self.files.insert(lang.into(), PathBuf::from(path.into()));
        self
    }

    /// Register the fallback locale
    pub fn fallback(mut self, lang: impl Into<String>) -> Self {
        self.fallback = Some(lang.into());
        self
    }

    /// Define a custom name for the output type
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Change the default output of generated files
    pub fn output(mut self, path: impl Into<PathBuf>) -> Self {
        self.output = Some(path.into());
        self
    }

    /// Generate locale files and write them to the output location
    pub fn generate(self) -> Result<(), BuildError> {
        self.build()?.generate()?;
        Ok(())
    }

    /// Validate configuration and build a [`RosettaConfig`]
    fn build(self) -> Result<RosettaConfig, ConfigError> {
        let mut files: HashMap<LanguageId, PathBuf> = self
            .files
            .into_iter()
            .map(|(lang, path)| {
                let lang = lang.parse::<LanguageId>()?;
                Ok((lang, path))
            })
            .collect::<Result<_, _>>()?;

        if files.is_empty() {
            return Err(ConfigError::MissingSource);
        }

        let fallback = match self.fallback {
            Some(lang) => {
                let lang = lang.parse::<LanguageId>()?;

                match files.remove_entry(&lang) {
                    Some(entry) => entry,
                    None => return Err(ConfigError::InvalidFallback),
                }
            }
            None => return Err(ConfigError::MissingFallback),
        };

        Ok(RosettaConfig {
            fallback,
            others: files,
            name: self.name.unwrap_or_else(|| "Lang".to_string()),
            output: self.output,
        })
    }
}

/// ISO 639-1 language identifier.
///
/// Language identifier can be validated using the [`FromStr`] trait.
/// It only checks if the string *looks like* a language identifier (2 character alphanumeric ascii string).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct LanguageId(pub String);

impl LanguageId {
    pub(crate) fn value(&self) -> &str {
        &self.0
    }
}

impl FromStr for LanguageId {
    type Err = ConfigError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let valid_length = s.len() == 2;
        let ascii_alphabetic = s.chars().all(|c| c.is_ascii_alphabetic());

        if valid_length && ascii_alphabetic {
            Ok(Self(s.to_ascii_lowercase()))
        } else {
            Err(ConfigError::InvalidLanguage(s.into()))
        }
    }
}

impl Display for LanguageId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Configuration for Rosetta code generation
///
/// A [`RosettaBuilder`] is provided to construct and validate configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RosettaConfig {
    pub fallback: (LanguageId, PathBuf),
    pub others: HashMap<LanguageId, PathBuf>,
    pub name: String,
    pub output: Option<PathBuf>,
}

impl RosettaConfig {
    /// Returns a list of the languages
    pub fn languages(&self) -> Vec<&LanguageId> {
        let mut languages: Vec<&LanguageId> =
            self.others.iter().map(|(language, _)| language).collect();
        languages.push(&self.fallback.0);
        languages
    }

    /// Generate locale files and write them to the output location
    pub fn generate(&self) -> Result<(), BuildError> {
        let fallback_content = open_file(&self.fallback.1)?;
        let mut parsed = parser::TranslationData::from_fallback(fallback_content)?;
        println!(
            "cargo:rerun-if-changed={}",
            self.fallback.1.to_string_lossy()
        );

        for (language, path) in &self.others {
            let content = open_file(path)?;
            parsed.parse_file(language.clone(), content)?;
            println!("cargo:rerun-if-changed={}", path.to_string_lossy());
        }

        let generated = gen::CodeGenerator::new(&parsed, self).generate();

        let output = match &self.output {
            Some(path) => path.clone(),
            None => Path::new(&env::var("OUT_DIR")?).join("rosetta_output.rs"),
        };

        let mut file = File::create(&output)?;
        file.write_all(generated.to_string().as_bytes())?;

        #[cfg(feature = "rustfmt")]
        rustfmt(&output)?;

        Ok(())
    }
}

/// Open a file and read its content as a JSON [`JsonValue`]
fn open_file(path: &Path) -> Result<JsonValue, BuildError> {
    let content = match std::fs::read_to_string(path) {
        Ok(content) => content,
        Err(error) => {
            return Err(BuildError::FileRead {
                file: path.to_path_buf(),
                source: error,
            })
        }
    };

    match content.parse::<JsonValue>() {
        Ok(parsed) => Ok(parsed),
        Err(error) => Err(BuildError::JsonParse {
            file: path.to_path_buf(),
            source: error,
        }),
    }
}

/// Format a file with rustfmt
#[cfg(feature = "rustfmt")]
fn rustfmt(path: &Path) -> Result<(), BuildError> {
    use std::process::Command;

    Command::new(env::var("RUSTFMT").unwrap_or_else(|_| "rustfmt".to_string()))
        .args(&["--emit", "files"])
        .arg(path)
        .output()
        .map_err(BuildError::Fmt)?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::RosettaConfig;
    use crate::{
        builder::{LanguageId, RosettaBuilder},
        error::ConfigError,
    };

    use std::path::PathBuf;

    use maplit::hashmap;

    #[test]
    fn config_simple() -> Result<(), Box<dyn std::error::Error>> {
        let config = RosettaBuilder::default()
            .source("en", "translations/en.json")
            .source("fr", "translations/fr.json")
            .fallback("en")
            .build()?;

        let expected = RosettaConfig {
            fallback: (
                LanguageId("en".into()),
                PathBuf::from("translations/en.json"),
            ),
            others: hashmap! { LanguageId("fr".into()) => PathBuf::from("translations/fr.json") },
            name: "Lang".to_string(),
            output: None,
        };

        assert_eq!(config, expected);

        Ok(())
    }

    #[test]
    fn config_missing_source() {
        let config = RosettaBuilder::default().build();
        assert_eq!(config, Err(ConfigError::MissingSource));
    }

    #[test]
    fn config_invalid_language() {
        let config = RosettaBuilder::default()
            .source("en", "translations/en.json")
            .source("invalid", "translations/fr.json")
            .fallback("en")
            .build();

        assert_eq!(
            config,
            Err(ConfigError::InvalidLanguage("invalid".to_string()))
        );
    }

    #[test]
    fn config_missing_fallback() {
        let config = RosettaBuilder::default()
            .source("en", "translations/en.json")
            .source("fr", "translations/fr.json")
            .build();

        assert_eq!(config, Err(ConfigError::MissingFallback));
    }

    #[test]
    fn config_invalid_fallback() {
        let config = RosettaBuilder::default()
            .source("en", "translations/en.json")
            .source("fr", "translations/fr.json")
            .fallback("de")
            .build();

        assert_eq!(config, Err(ConfigError::InvalidFallback));
    }
}