globetrotter 0.0.15

Polyglot, type-safe internationalization
Documentation
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
//! Configuration discovery, version selection, and schema parsing.

/// Resolved settings and precedence layers.
pub mod settings;
pub mod usages;
/// Version 1 of the configuration schema and its parsing routines.
pub mod v1;

pub use settings::{Settings, SettingsLayer};

use codespan_reporting::diagnostic::{Diagnostic, Label};

use globetrotter_model::diagnostics::{DiagnosticExt, Span, ToDiagnostics};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use yaml_spanned::Value;

/// The configuration schema version.
#[derive(
    Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, Default,
)]
pub enum Version {
    /// Version 1 of the configuration schema.
    #[serde(rename = "1", alias = "v1", alias = "V1")]
    V1,
    /// An input alias that resolves to the latest supported schema.
    #[serde(rename = "latest")]
    #[default]
    Latest,
}

/// Returns supported configuration file names in discovery order.
pub fn config_file_names() -> impl Iterator<Item = &'static str> {
    [".globetrotter.yaml", "globetrotter.yaml"].into_iter()
}

/// Searches a directory for the first supported configuration file.
///
/// The returned path is canonicalized. Hidden `.globetrotter.yaml` takes
/// precedence over `globetrotter.yaml`.
///
/// # Errors
///
/// Returns an error if accessing the filesystem fails while probing for the
/// supported configuration file names.
pub async fn find_config_file(dir: &Path) -> std::io::Result<Option<PathBuf>> {
    for path in config_file_names().map(|name| dir.join(name)) {
        match tokio::fs::canonicalize(&path).await {
            Ok(path) => return Ok(Some(path)),
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                // Try the next supported config file name.
            }
            Err(err) => return Err(err),
        }
    }
    Ok(None)
}

/// Parses a raw YAML string into [`v1::Configs`].
///
/// Version and schema diagnostics are appended to `diagnostics`; existing
/// diagnostics are retained.
/// `strict` decides whether those parse-time findings are errors; the file's
/// own `strict` key governs generation only and is not consulted here.
///
/// # Errors
///
/// Returns an error if the YAML cannot be parsed or if the configuration
/// schema is invalid for the detected version.
pub fn from_str<F: Copy + PartialEq>(
    raw_config: &str,
    config_dir: &Path,
    file_id: F,
    strict: Option<bool>,
    diagnostics: &mut Vec<Diagnostic<F>>,
) -> Result<v1::Configs<F>, ConfigError> {
    let value = yaml_spanned::from_str(raw_config).map_err(ConfigError::YAML)?;
    let version = parse_version(&value, file_id, strict, diagnostics)?;

    match version {
        Version::Latest | Version::V1 => {
            v1::parse_configs(&value, config_dir, file_id, strict, diagnostics)
        }
    }
}

/// An error that can occur while parsing a configuration file.
#[derive(thiserror::Error, Debug)]
pub enum ConfigError {
    /// A required key was missing from the configuration.
    #[error("{message}")]
    MissingKey {
        /// The name of the missing key.
        key: String,
        /// A human-readable description of the problem.
        message: String,
        /// The span of the surrounding value.
        span: Span,
    },
    /// A value had a type other than the one expected.
    #[error("{message}")]
    UnexpectedType {
        /// A human-readable description of the problem.
        message: String,
        /// The kinds that would have been accepted.
        expected: Vec<yaml_spanned::value::Kind>,
        /// The kind that was actually found.
        found: yaml_spanned::value::Kind,
        /// The span of the offending value.
        span: Span,
    },
    /// An `allow` entry could not be parsed into a lint suppression.
    #[error("invalid `allow` entry `{entry}`: {source}")]
    InvalidAllowEntry {
        /// The entry as written.
        entry: String,
        /// Why the entry could not be parsed.
        #[source]
        source: globetrotter_model::lint::ParseAllowEntryError,
        /// The span of the offending entry.
        span: Span,
    },
    /// Deserialization of a value into a typed representation failed.
    #[error("{source}")]
    Serde {
        /// The underlying deserialization error.
        #[source]
        source: yaml_spanned::error::SerdeError,
        /// The span of the offending value.
        span: Span,
    },
    /// The underlying YAML could not be parsed.
    #[error(transparent)]
    YAML(#[from] yaml_spanned::Error),
}

impl ToDiagnostics for ConfigError {
    fn to_diagnostics<F: Copy + PartialEq>(&self, file_id: F) -> Vec<Diagnostic<F>> {
        match self {
            Self::MissingKey {
                message, key, span, ..
            } => vec![
                Diagnostic::error()
                    .with_message(format!("missing required key `{key}`"))
                    .with_labels(vec![
                        Label::secondary(file_id, span.clone()).with_message(message),
                    ]),
            ],
            Self::UnexpectedType {
                expected,
                found,
                span,
                ..
            } => {
                let expected = expected
                    .iter()
                    .map(|ty| format!("`{ty:?}`"))
                    .collect::<Vec<_>>()
                    .join(", or ");
                let diagnostic = Diagnostic::error()
                    .with_message(self.to_string())
                    .with_labels(vec![
                        Label::primary(file_id, span.clone())
                            .with_message(format!("expected {expected}")),
                    ])
                    .with_notes(vec![indoc::formatdoc!(
                        "
                        expected type {expected}
                           found type `{found:?}`
                        "
                    )]);
                vec![diagnostic]
            }
            Self::InvalidAllowEntry {
                entry,
                source,
                span,
            } => vec![
                Diagnostic::error()
                    .with_message(self.to_string())
                    .with_labels(vec![
                        Label::primary(file_id, span.clone()).with_message(source.to_string()),
                    ])
                    .with_notes(vec![source.note(entry)]),
            ],
            Self::Serde { source, span } => vec![
                Diagnostic::error()
                    .with_message(self.to_string())
                    .with_labels(vec![
                        Label::primary(file_id, span.clone()).with_message(source.to_string()),
                    ]),
            ],
            Self::YAML(source) => {
                use yaml_spanned::error::ToDiagnostics;
                source.to_diagnostics(file_id)
            }
        }
    }
}

/// Parses the configuration `version` field from a YAML value.
///
/// A missing field resolves to [`Version::Latest`] and appends a warning, or an
/// error when `strict` is explicitly `true`.
///
/// # Errors
///
/// Returns an error if the `version` field is present but cannot be parsed
/// into a supported `Version` value.
pub fn parse_version<F>(
    value: &yaml_spanned::Spanned<Value>,
    file_id: F,
    strict: Option<bool>,
    diagnostics: &mut Vec<Diagnostic<F>>,
) -> Result<Version, ConfigError> {
    match value.get("version") {
        None => {
            let diagnostic = Diagnostic::warning_or_error(strict.unwrap_or(false))
                .with_message("missing version")
                .with_labels(vec![
                    Label::primary(file_id, value.span)
                        .with_message("no version is specified - assuming version 1"),
                ]);
            diagnostics.push(diagnostic);
            Ok(Version::Latest)
        }
        Some(yaml_spanned::Spanned {
            inner: Value::Number(n),
            ..
        }) if n.as_f64() == Some(1.0) => Ok(Version::V1),
        Some(value) => {
            let version = v1::parse::<Version>(value)?;
            Ok(version.into_inner())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::ConfigError;
    use color_eyre::eyre;
    use similar_asserts::assert_eq as sim_assert_eq;
    use yaml_spanned::{Spanned, Value};

    /// Every settings key parses into the config's [`SettingsLayer`],
    /// including the `engine` and `absolute` spelling aliases.
    #[test_util::test]
    fn parses_settings_keys_and_aliases() -> eyre::Result<()> {
        use globetrotter_model::{TemplateEngine, diagnostics::Spanned};

        let raw = indoc::indoc! {r#"
            version: 1
            config:
              languages: ["en"]
              engine: handlebars
              strict: true
              check_templates: false
              dry_run: true
              absolute: true
              inputs:
                - ./translations/a.toml
              outputs:
                json:
                  - ./out/{{language}}.json
        "#};
        let mut diagnostics = vec![];
        let configs = super::from_str(raw, std::path::Path::new("."), (), None, &mut diagnostics)?;

        // Spanned comparisons ignore spans, so dummy spans match parsed ones.
        sim_assert_eq!(
            have: configs[0].config.settings,
            want: super::SettingsLayer {
                strict: Some(true),
                check_templates: Some(false),
                dry_run: Some(true),
                print_absolute_paths: Some(true),
                template_engine: Some(Spanned::dummy(TemplateEngine::Handlebars)),
            }
        );
        Ok(())
    }

    /// A config-wide `allow` list parses into typed suppression entries.
    #[test_util::test]
    fn parses_config_allow_list() -> eyre::Result<()> {
        use globetrotter_model::lint::{AllowEntry, LintCode};

        let raw = indoc::indoc! {r#"
            version: 1
            config:
              languages: ["en"]
              allow: ["lint:duplicate", "lint:llm-drift"]
              inputs:
                - ./translations/a.toml
              outputs:
                json:
                  - ./out/{{language}}.json
        "#};
        let mut diagnostics = vec![];
        let configs = super::from_str(raw, std::path::Path::new("."), (), None, &mut diagnostics)?;

        sim_assert_eq!(
            have: configs[0].config.allow,
            want: [
                AllowEntry::Code(LintCode::Duplicate),
                AllowEntry::Code(LintCode::LlmDrift),
            ]
            .into_iter()
            .collect()
        );
        Ok(())
    }

    /// A file with neither `config` nor `configs` parses to nothing but says
    /// so, since silently generating nothing hides a misspelled key.
    #[test_util::test]
    fn warns_about_missing_configurations() -> eyre::Result<()> {
        use codespan_reporting::diagnostic::Severity;

        let raw = indoc::indoc! {"
            version: 1
            configuration: {}
        "};
        let mut diagnostics = vec![];
        let configs = super::from_str(raw, std::path::Path::new("."), (), None, &mut diagnostics)?;

        assert!(configs.is_empty());
        assert_eq!(diagnostics.len(), 1, "{diagnostics:?}");
        assert_eq!(diagnostics[0].severity, Severity::Warning);
        assert_eq!(diagnostics[0].message, "empty configurations");
        Ok(())
    }

    /// Every typed output section accepts one path or a list of paths, so a
    /// configured backend is never silently dropped.
    #[test_util::test]
    fn parses_typed_output_paths() -> eyre::Result<()> {
        let raw = indoc::indoc! {"
            version: 1
            config:
              languages: [en]
              inputs: [./translations.toml]
              outputs:
                json: ./out/{{language}}.json
                rust: ./out/translations.rs
                golang: [./out/a.go, ./out/b.go]
                python: ./out/translations.py
        "};
        let mut diagnostics = vec![];
        let configs = super::from_str(raw, std::path::Path::new("."), (), None, &mut diagnostics)?;
        let outputs = &configs[0].config.outputs;

        #[cfg(feature = "rust")]
        sim_assert_eq!(
            have: outputs.rust.as_ref().map(|rust| rust.output_paths.clone()),
            want: Some(vec![std::path::PathBuf::from("./out/translations.rs")])
        );
        #[cfg(feature = "golang")]
        sim_assert_eq!(
            have: outputs.golang.as_ref().map(|go| go.output_paths.clone()),
            want: Some(vec![
                std::path::PathBuf::from("./out/a.go"),
                std::path::PathBuf::from("./out/b.go"),
            ])
        );
        #[cfg(feature = "python")]
        sim_assert_eq!(
            have: outputs.python.as_ref().map(|python| python.output_paths.clone()),
            want: Some(vec![std::path::PathBuf::from("./out/translations.py")])
        );
        assert!(!outputs.is_empty());
        Ok(())
    }

    /// An input's `exclude` accepts one pattern or a list of patterns.
    #[test_util::test]
    fn parses_exclude_as_string_or_sequence() -> eyre::Result<()> {
        let raw = indoc::indoc! {"
            version: 1
            configs:
              app:
                languages: [en]
                inputs:
                  - path: ./translations/**/*.toml
                    exclude: ./translations/drafts/*.toml
                  - path: ./translations/**/*.toml
                    exclude:
                      - ./translations/drafts/*.toml
                      - ./translations/legacy.toml
                outputs:
                  json: ./out/{{language}}.json
        "};
        let mut diagnostics = vec![];
        let configs = super::from_str(raw, std::path::Path::new("."), (), None, &mut diagnostics)?;

        let excludes: Vec<Vec<&str>> = configs[0]
            .config
            .inputs
            .iter()
            .map(|input| {
                input
                    .exclude
                    .iter()
                    .map(|pattern| pattern.as_ref().as_str())
                    .collect()
            })
            .collect();
        sim_assert_eq!(
            have: excludes,
            want: vec![
                vec!["./translations/drafts/*.toml"],
                vec!["./translations/drafts/*.toml", "./translations/legacy.toml"],
            ]
        );
        Ok(())
    }

    /// A bare lint code is rejected in the config file just as it is in a
    /// translation file, so the `lint:` prefix stays the only spelling.
    #[test_util::test]
    fn rejects_unprefixed_config_allow_entry() {
        use globetrotter_model::lint::ParseAllowEntryError;

        let raw = indoc::indoc! {r#"
            version: 1
            config:
              languages: ["en"]
              allow: ["duplicate"]
        "#};
        let mut diagnostics = vec![];
        let result = super::from_str(raw, std::path::Path::new("."), (), None, &mut diagnostics);
        assert!(
            matches!(
                &result,
                Err(ConfigError::InvalidAllowEntry {
                    entry,
                    source: ParseAllowEntryError::MissingPrefix,
                    ..
                }) if entry == "duplicate"
            ),
            "{result:?}"
        );
    }

    /// Numeric, string, and prefixed version-one spellings parse identically.
    #[test_util::test]
    fn test_parse_version() -> eyre::Result<()> {
        fn parse_version_wrapper(
            value: impl Into<Spanned<Value>>,
            strict: bool,
        ) -> Result<super::Version, ConfigError> {
            let mut diagnostics = vec![];

            super::parse_version(&value.into(), (), Some(strict), &mut diagnostics)
        }

        let have = parse_version_wrapper(
            Value::Mapping([("version".into(), 1.into())].into_iter().collect()),
            true,
        )?;
        sim_assert_eq!(
            have: have,
            want: super::Version::V1
        );

        let have = parse_version_wrapper(
            Value::Mapping([("version".into(), "1".into())].into_iter().collect()),
            true,
        )?;
        sim_assert_eq!(
            have: have,
            want: super::Version::V1
        );

        let have = parse_version_wrapper(
            Value::Mapping([("version".into(), "v1".into())].into_iter().collect()),
            true,
        )?;
        sim_assert_eq!(
            have: have,
            want: super::Version::V1
        );
        Ok(())
    }
}