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
//! This library contains the configuration stucts (along with their
//! parsing functions) for the
//! [cargo-i18n](https://crates.io/crates/cargo_i18n) tool/system.

mod fluent;
mod gettext;

pub use fluent::FluentConfig;
pub use gettext::GettextConfig;

use std::fs::read_to_string;
use std::io;
use std::{
    fmt::Display,
    path::{Path, PathBuf},
};

use log::{debug, error};
use serde_derive::Deserialize;
use thiserror::Error;
use unic_langid::LanguageIdentifier;

/// An error type for use with the `i18n-config` crate.
#[derive(Debug, Error)]
pub enum I18nConfigError {
    #[error("The specified path is not a crate because there is no Cargo.toml present.")]
    NotACrate(PathBuf),
    #[error("Cannot read file {0:?} in the current working directory {1:?} because {2}.")]
    CannotReadFile(PathBuf, io::Result<PathBuf>, #[source] io::Error),
    #[error("Cannot parse Cargo configuration file {0:?} because {1}.")]
    CannotParseCargoToml(PathBuf, String),
    #[error("Cannot deserialize toml file {0:?} because {1}.")]
    CannotDeserializeToml(PathBuf, toml::de::Error),
    #[error("Cannot parse i18n configuration file {0:?} because {1}.")]
    CannotPaseI18nToml(PathBuf, String),
    #[error("There is no i18n configuration file present for the crate {0}.")]
    NoI18nConfig(String),
    #[error("The \"{0}\" is required to be present in the i18n configuration file \"{1}\"")]
    OptionMissingInI18nConfig(String, PathBuf),
    #[error("There is no parent crate for {0}. Required because {1}.")]
    NoParentCrate(String, String),
    #[error(
        "There is no i18n config file present for the parent crate of {0}. Required because {1}."
    )]
    NoParentI18nConfig(String, String),
}

/// Represents a rust crate.
#[derive(Debug, Clone)]
pub struct Crate<'a> {
    /// The name of the crate.
    pub name: String,
    /// The version of the crate.
    pub version: String,
    /// The path to the crate.
    pub path: PathBuf,
    /// Path to the parent crate which is triggering the localization
    /// for this crate.
    pub parent: Option<&'a Crate<'a>>,
    /// The file path expected to be used for `i18n_config` relative to this crate's root.
    pub config_file_path: PathBuf,
    /// The localization config for this crate (if it exists).
    pub i18n_config: Option<I18nConfig>,
}

impl<'a> Crate<'a> {
    /// Read crate from `Cargo.toml` i18n config using the
    /// `config_file_path` (if there is one).
    pub fn from<P1: Into<PathBuf>, P2: Into<PathBuf>>(
        path: P1,
        parent: Option<&'a Crate>,
        config_file_path: P2,
    ) -> Result<Crate<'a>, I18nConfigError> {
        let path_into = path.into();

        let config_file_path_into = config_file_path.into();

        let cargo_path = path_into.join("Cargo.toml");

        if !cargo_path.exists() {
            return Err(I18nConfigError::NotACrate(path_into));
        }

        let toml_str = read_to_string(cargo_path.clone()).map_err(|err| {
            I18nConfigError::CannotReadFile(cargo_path.clone(), std::env::current_dir(), err)
        })?;
        let cargo_toml: toml::Value = toml::from_str(toml_str.as_ref())
            .map_err(|err| I18nConfigError::CannotDeserializeToml(cargo_path.clone(), err))?;

        let package = cargo_toml
            .as_table()
            .ok_or_else(|| I18nConfigError::CannotParseCargoToml(cargo_path.clone(), "Cargo.toml needs have sections (such as the \"gettext\" section when using gettext.".to_string()))?
            .get("package")
            .ok_or_else(|| I18nConfigError::CannotParseCargoToml(cargo_path.clone(), "Cargo.toml needs to have a \"package\" section.".to_string()))?
            .as_table()
            .ok_or_else(|| I18nConfigError::CannotParseCargoToml(cargo_path.clone(),
                "Cargo.toml's \"package\" section needs to contain values.".to_string()
            ))?;

        let name = package
            .get("name")
            .ok_or_else(|| {
                I18nConfigError::CannotParseCargoToml(
                    cargo_path.clone(),
                    "Cargo.toml needs to specify a package name.".to_string(),
                )
            })?
            .as_str()
            .ok_or_else(|| {
                I18nConfigError::CannotParseCargoToml(
                    cargo_path.clone(),
                    "Cargo.toml's package name needs to be a string.".to_string(),
                )
            })?;

        let version = package
            .get("version")
            .ok_or_else(|| {
                I18nConfigError::CannotParseCargoToml(
                    cargo_path.clone(),
                    "Cargo.toml needs to specify a package version.".to_string(),
                )
            })?
            .as_str()
            .ok_or_else(|| {
                I18nConfigError::CannotParseCargoToml(
                    cargo_path,
                    "Cargo.toml's package version needs to be a string.".to_string(),
                )
            })?;

        let full_config_file_path = path_into.join(&config_file_path_into);
        let i18n_config = if full_config_file_path.exists() {
            Some(I18nConfig::from_file(&full_config_file_path)?)
        } else {
            None
        };

        Ok(Crate {
            name: String::from(name),
            version: String::from(version),
            path: path_into,
            parent,
            config_file_path: config_file_path_into,
            i18n_config,
        })
    }

    /// The name of the module/library used for this crate. Replaces
    /// `-` characters with `_` in the crate name.
    pub fn module_name(&self) -> String {
        self.name.replace("-", "_")
    }

    /// If there is a parent, get it's
    /// [I18nConfig#active_config()](I18nConfig#active_config()),
    /// otherwise return None.
    pub fn parent_active_config(
        &'a self,
    ) -> Result<Option<(&'a Crate, &'a I18nConfig)>, I18nConfigError> {
        match self.parent {
            Some(parent) => parent.active_config(),
            None => Ok(None),
        }
    }

    /// Identify the config which should be used for this crate, and
    /// the crate (either this crate or one of it's parents)
    /// associated with that config.
    pub fn active_config(&'a self) -> Result<Option<(&'a Crate, &'a I18nConfig)>, I18nConfigError> {
        debug!("Resolving active config for {0}", self);
        match &self.i18n_config {
            Some(config) => {
                if let Some(gettext_config) = &config.gettext {
                    if gettext_config.extract_to_parent {
                        debug!("Resolving active config for {0}, extract_to_parent is true, so attempting to obtain parent config.", self);

                        if self.parent.is_none() {
                            return Err(I18nConfigError::NoParentCrate(
                                self.to_string(),
                                "the gettext extract_to_parent option is active".to_string(),
                            ));
                        }

                        return Ok(Some(self.parent_active_config()?.ok_or_else(|| {
                            I18nConfigError::NoParentI18nConfig(
                                self.to_string(),
                                "the gettext extract_to_parent option is active".to_string(),
                            )
                        })?));
                    }
                }

                Ok(Some((self, &config)))
            }
            None => {
                debug!(
                    "{0} has no i18n config, attempting to obtain parent config instead.",
                    self
                );
                self.parent_active_config()
            }
        }
    }

    /// Get the [I18nConfig](I18nConfig) in this crate, or return an
    /// error if there is none present.
    pub fn config_or_err(&self) -> Result<&I18nConfig, I18nConfigError> {
        match &self.i18n_config {
            Some(config) => Ok(config),
            None => Err(I18nConfigError::NoI18nConfig(self.to_string())),
        }
    }

    /// Get the [GettextConfig](GettextConfig) in this crate, or
    /// return an error if there is none present.
    pub fn gettext_config_or_err(&self) -> Result<&GettextConfig, I18nConfigError> {
        match &self.config_or_err()?.gettext {
            Some(gettext_config) => Ok(gettext_config),
            None => Err(I18nConfigError::OptionMissingInI18nConfig(
                "gettext section".to_string(),
                self.config_file_path.clone(),
            )),
        }
    }

    /// If this crate has a parent, check whether the parent wants to
    /// collate subcrates string extraction, as per the parent's
    /// [GettextConfig#collate_extracted_subcrates](GettextConfig#collate_extracted_subcrates).
    /// This also requires that the current crate's [GettextConfig#extract_to_parent](GettextConfig#extract_to_parent)
    /// is **true**.
    ///
    /// Returns **false** if there is no parent or the parent has no gettext config.
    pub fn collated_subcrate(&self) -> bool {
        let parent_extract_to_subcrate = self
            .parent
            .map(|parent_crate| {
                parent_crate
                    .gettext_config_or_err()
                    .map(|parent_gettext_config| parent_gettext_config.collate_extracted_subcrates)
                    .unwrap_or(false)
            })
            .unwrap_or(false);

        let extract_to_parent = self
            .gettext_config_or_err()
            .map(|gettext_config| gettext_config.extract_to_parent)
            .unwrap_or(false);

        parent_extract_to_subcrate && extract_to_parent
    }

    /// Attempt to resolve the parents of this crate which have this
    /// crate listed as a subcrate in their i18n config.
    pub fn find_parent(&self) -> Option<Crate<'a>> {
        let parent_crt = match self
            .path
            .canonicalize()
            .map(|op| op.parent().map(|p| p.to_path_buf()))
            .ok()
            .unwrap_or(None)
        {
            Some(parent_path) => match Crate::from(parent_path, None, "i18n.toml") {
                Ok(parent_crate) => {
                    debug!("Found parent ({0}) of {1}.", parent_crate, self);
                    Some(parent_crate)
                }
                Err(err) => {
                    match err {
                        I18nConfigError::NotACrate(path) => {
                            debug!("The parent of {0} at path {1:?} is not a valid crate with a Cargo.toml", self, path);
                        }
                        _ => {
                            error!(
                                "Error occurred while attempting to resolve parent of {0}: {1}",
                                self, err
                            );
                        }
                    }

                    None
                }
            },
            None => None,
        };

        match parent_crt {
            Some(crt) => match &crt.i18n_config {
                Some(config) => {
                    let this_is_subcrate = config
                        .subcrates
                        .iter()
                        .any(|subcrate_path| {
                            let subcrate_path_canon = match crt.path.join(subcrate_path).canonicalize() {
                                Ok(canon) => canon,
                                Err(err) => {
                                    error!("Error: unable to canonicalize the subcrate path: {0:?} because {1}", subcrate_path, err);
                                    return false;
                                }
                            };

                            let self_path_canon = match self.path.canonicalize() {
                                Ok(canon) => canon,
                                Err(err) => {
                                    error!("Error: unable to canonicalize the crate path: {0:?} because {1}", self.path, err);
                                    return false;
                                }
                            };

                            subcrate_path_canon == self_path_canon
                        });

                    if this_is_subcrate {
                        Some(crt)
                    } else {
                        debug!("Parent {0} does not have {1} correctly listed as one of its subcrates (curently: {2:?}) in its i18n config.", crt, self, config.subcrates);
                        None
                    }
                }
                None => {
                    debug!("Parent {0} of {1} does not have an i18n config", crt, self);
                    None
                }
            },
            None => {
                debug!("Could not find a valid parent of {0}.", self);
                None
            }
        }
    }
}

impl<'a> Display for Crate<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Crate \"{0}\" at \"{1}\"",
            self.name,
            self.path.to_string_lossy()
        )
    }
}

/// The data structure representing what is stored (and possible to
/// store) within a `i18n.toml` file.
#[derive(Deserialize, Debug, Clone)]
pub struct I18nConfig {
    /// The locale identifier of the language used in the source code
    /// for `gettext` system, and the primary fallback language (for
    /// which all strings must be present) when using the `fluent`
    /// system.
    pub fallback_language: LanguageIdentifier,
    /// Specify which subcrates to perform localization within. The
    /// subcrate needs to have its own `i18n.toml`.
    #[serde(default)]
    pub subcrates: Vec<PathBuf>,
    /// The subcomponent of this config relating to gettext, only
    /// present if the gettext localization system will be used.
    pub gettext: Option<GettextConfig>,
    /// The subcomponent of this config relating to gettext, only
    /// present if the fluent localization system will be used.
    pub fluent: Option<FluentConfig>,
}

impl I18nConfig {
    /// Load the config from the specified toml file path.
    pub fn from_file<P: AsRef<Path>>(toml_path: P) -> Result<I18nConfig, I18nConfigError> {
        let toml_path_final: &Path = toml_path.as_ref();
        let toml_str = read_to_string(toml_path_final).map_err(|err| {
            I18nConfigError::CannotReadFile(
                toml_path_final.to_path_buf(),
                std::env::current_dir(),
                err,
            )
        })?;
        let config: I18nConfig = toml::from_str(toml_str.as_ref()).map_err(|err| {
            I18nConfigError::CannotDeserializeToml(toml_path_final.to_path_buf(), err)
        })?;

        Ok(config)
    }
}