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
use crate::{bundle::MessageBundle, codegen::CodeGenerator, error::Error};

use proc_macro2::TokenStream;
use quote::quote;
use std::{
    collections::BTreeMap,
    fs,
    path::{Path, PathBuf},
};

pub fn generate(
    root_dir: impl AsRef<Path>,
    code_generator: impl CodeGenerator,
) -> Result<String, Error> {
    let paths = list_fluent_resources(&root_dir)?;

    let mut resources = vec![];
    for res_path in paths {
        println!("cargo:rerun-if-changed={}", res_path.to_string_lossy());
        let path = res_path.strip_prefix(root_dir.as_ref())?.into();
        let content = fs::read_to_string(res_path)?;
        resources.push((path, content));
    }

    let message_bundle_generated_code = create_message_bundles(resources)?
        .iter()
        .map(|bundle| code_generator.generate(bundle))
        .collect::<Result<Vec<TokenStream>, Error>>()?;

    Ok(quote! {
        #(#message_bundle_generated_code)*
    }
    .to_string())
}

fn create_message_bundles(resources: Vec<(PathBuf, String)>) -> Result<Vec<MessageBundle>, Error> {
    let bundles_by_path = resources.into_iter().try_fold(
        BTreeMap::<PathBuf, Vec<(String, String)>>::new(),
        |mut acc,
         (resource_path, resource_content)|
         -> Result<BTreeMap<PathBuf, Vec<(String, String)>>, Error> {
            let mut path_components = resource_path.components();
            let lang = path_components
                .next()
                .and_then(|c| c.as_os_str().to_str())
                .ok_or_else(|| Error::InvalidPath(resource_path.clone()))?
                .to_string();
            let bundle_path = path_components.as_path().to_path_buf();

            acc.entry(bundle_path)
                .or_default()
                .push((lang, resource_content));

            Ok(acc)
        },
    )?;

    bundles_by_path
        .into_iter()
        .map(|(bundle_path, lang_resources)| {
            let bundle_name = bundle_path
                .file_stem()
                .ok_or_else(|| Error::InvalidPathFormat(bundle_path.clone()))?
                .to_str()
                .ok_or_else(|| Error::InvalidPath(bundle_path.clone()))?;

            MessageBundle::create(&bundle_name, &bundle_path, lang_resources)
        })
        .collect()
}

fn is_fluent_resource(path: &PathBuf) -> bool {
    path.extension()
        .is_some_and(|ext| ext.to_string_lossy() == "ftl")
}

fn list_fluent_resources(root_dir: &impl AsRef<Path>) -> Result<Vec<PathBuf>, Error> {
    let mut pending: Vec<PathBuf> = vec![root_dir.as_ref().into()];
    let mut resource_paths: Vec<PathBuf> = vec![];
    while let Some(dir) = pending.pop() {
        for entry in fs::read_dir(dir)? {
            let entry_path = entry?.path();
            if entry_path.is_dir() {
                pending.push(entry_path);
            } else if is_fluent_resource(&entry_path) {
                resource_paths.push(entry_path);
            }
        }
    }
    resource_paths.sort();
    Ok(resource_paths)
}

#[cfg(test)]
mod tests {
    use std::{path::PathBuf, str::FromStr};

    use crate::{
        bundle::{LanguageBundle, MessageBundle},
        message::{Message, Var},
    };

    fn make_fluent_resources() -> Vec<(PathBuf, String)> {
        vec![
            (
                PathBuf::from_str("en/main.ftl").unwrap(),
                "hello=Hello { $name }".to_string(),
            ),
            (
                PathBuf::from_str("ru-RU/main.ftl").unwrap(),
                "hello=Привет, { $name }".to_string(),
            ),
            (
                PathBuf::from_str("en/extra/test.ftl").unwrap(),
                "greetings=Greetings { $user }".to_string(),
            ),
            (
                PathBuf::from_str("ru-RU/extra/test.ftl").unwrap(),
                "greetings=Привет, { $user }".to_string(),
            ),
        ]
    }

    #[test]
    fn create_message_bundles() {
        let resources = make_fluent_resources();

        let expected = vec![
            MessageBundle {
                name: "test".to_string(),
                path: PathBuf::from_str("extra/test.ftl").unwrap(),
                langs: vec![
                    LanguageBundle {
                        language: "en".to_string(),
                        resource: resources[2].1.clone(),
                        messages: vec![Message {
                            name: "greetings".to_string(),
                            vars: vec![Var {
                                name: "user".to_string(),
                            }]
                            .into_iter()
                            .collect(),
                        }]
                        .into_iter()
                        .collect(),
                    },
                    LanguageBundle {
                        language: "ru-RU".to_string(),
                        resource: resources[3].1.clone(),
                        messages: vec![Message {
                            name: "greetings".to_string(),
                            vars: vec![Var {
                                name: "user".to_string(),
                            }]
                            .into_iter()
                            .collect(),
                        }]
                        .into_iter()
                        .collect(),
                    },
                ],
            },
            MessageBundle {
                name: "main".to_string(),
                path: PathBuf::from_str("main.ftl").unwrap(),
                langs: vec![
                    LanguageBundle {
                        language: "en".to_string(),
                        resource: resources[0].1.clone(),
                        messages: vec![Message {
                            name: "hello".to_string(),
                            vars: vec![Var {
                                name: "name".to_string(),
                            }]
                            .into_iter()
                            .collect(),
                        }]
                        .into_iter()
                        .collect(),
                    },
                    LanguageBundle {
                        language: "ru-RU".to_string(),
                        resource: resources[1].1.clone(),
                        messages: vec![Message {
                            name: "hello".to_string(),
                            vars: vec![Var {
                                name: "name".to_string(),
                            }]
                            .into_iter()
                            .collect(),
                        }]
                        .into_iter()
                        .collect(),
                    },
                ],
            },
        ];

        let actual = super::create_message_bundles(resources.clone()).unwrap();

        assert_eq!(expected, actual);
    }
}