Skip to main content

factorio_ir/
locale.rs

1#[derive(Debug, Clone, PartialEq, Eq)]
2pub struct LocaleEntry {
3    /// Factorio category name (e.g. `mod-setting-name`), if any.
4    pub category: Option<String>,
5    /// Locale key (e.g. `msr-casual-mode`).
6    pub key: String,
7    /// Translated / English template string.
8    pub value: String,
9}
10
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct LocaleFile {
13    /// Language code (`en`, `de`, ...).
14    pub lang: String,
15    /// File stem written under `locale/<lang>/` (without `.cfg`).
16    pub file: String,
17    pub entries: Vec<LocaleEntry>,
18}
19
20/// Unresolved locale key from `locale!` (literal or `Type::CONST` / FQ path).
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum PendingLocaleKey {
23    Literal(String),
24    /// Path segments as written (`Items`, `WIDGET`) or
25    /// (`crate`, `data`, `items`, `Items`, `WIDGET`).
26    Path(Vec<String>),
27}
28
29/// One unresolved entry before string-const resolution.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct PendingLocaleEntry {
32    pub category: Option<String>,
33    pub key: PendingLocaleKey,
34    pub value: String,
35}
36
37/// Parsed `locale!` language block awaiting `Type::CONST` resolution.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct PendingLocaleFile {
40    pub lang: String,
41    pub file: String,
42    pub entries: Vec<PendingLocaleEntry>,
43}
44
45impl LocaleFile {
46    /// Serialize to Factorio's `.cfg` format.
47    #[must_use]
48    pub fn to_cfg(&self) -> String {
49        let mut output = String::new();
50        let mut current_category: Option<&str> = None;
51        let mut first_section = true;
52
53        for entry in &self.entries {
54            let category = entry.category.as_deref();
55            if category != current_category {
56                if !first_section {
57                    output.push('\n');
58                }
59                if let Some(name) = category {
60                    output.push('[');
61                    output.push_str(name);
62                    output.push_str("]\n");
63                }
64                current_category = category;
65                first_section = false;
66            }
67
68            output.push_str(&entry.key);
69            output.push('=');
70            output.push_str(&entry.value);
71            output.push('\n');
72        }
73
74        output
75    }
76}