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
/// Builder for creating a `Codec` instance with a fluent interface.
///
/// This builder allows you to chain method calls to add resources from files
/// and then build the final `Codec` instance.
///
/// # Example
///
/// ```rust,no_run
/// use langcodec::{Codec, formats::FormatType};
///
/// let codec = Codec::builder()
/// .add_file("en.strings")?
/// .add_file("fr.strings")?
/// .add_file_with_format("de.xml", FormatType::AndroidStrings(Some("de".to_string())))?
/// .read_file_by_extension("es.strings", Some("es".to_string()))?
/// .build();
/// # Ok::<(), langcodec::Error>(())
/// ```
use crate::formats::{CSVFormat, TSVFormat, XliffFormat};
use crate::{error::Error, formats::*, traits::Parser, types::Resource};
use std::path::Path;
pub struct CodecBuilder {
resources: Vec<Resource>,
}
impl CodecBuilder {
/// Creates a new `CodecBuilder` with no resources.
pub fn new() -> Self {
Self {
resources: Vec::new(),
}
}
/// Adds a resource file by inferring its format from the file extension.
///
/// The language will be automatically inferred from the file path if possible.
/// For example, `en.lproj/Localizable.strings` will be detected as English.
///
/// # Arguments
///
/// * `path` - Path to the resource file
///
/// # Returns
///
/// Returns `self` for method chaining, or an `Error` if the file cannot be read.
pub fn add_file<P: AsRef<Path>>(mut self, path: P) -> Result<Self, Error> {
let path = path.as_ref();
let format_type = super::converter::infer_format_from_path(path).ok_or_else(|| {
Error::UnknownFormat(format!(
"Cannot infer format from file extension: {:?}",
path.extension()
))
})?;
let language = super::converter::infer_language_from_path(path, &format_type)?;
let domain = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or_default()
.to_string();
let mut new_resources = match &format_type {
FormatType::Strings(_) => {
vec![Resource::from(StringsFormat::read_from(path)?)]
}
FormatType::AndroidStrings(_) => {
vec![Resource::from(AndroidStringsFormat::read_from(path)?)]
}
FormatType::Xcstrings => Vec::<Resource>::try_from(XcstringsFormat::read_from(path)?)?,
FormatType::Xliff(_) => Vec::<Resource>::try_from(XliffFormat::read_from(path)?)?,
FormatType::CSV => {
// Parse CSV format and convert to resources
let csv_format = CSVFormat::read_from(path)?;
Vec::<Resource>::try_from(csv_format)?
}
FormatType::TSV => {
// Parse TSV format and convert to resources
let tsv_format = TSVFormat::read_from(path)?;
Vec::<Resource>::try_from(tsv_format)?
}
};
let should_override_language = matches!(
format_type,
FormatType::Strings(_) | FormatType::AndroidStrings(_)
);
for new_resource in &mut new_resources {
if should_override_language && let Some(ref lang) = language {
new_resource.metadata.language = lang.clone();
}
new_resource.metadata.domain = domain.clone();
new_resource
.metadata
.custom
.insert("format".to_string(), format_type.to_string());
}
self.resources.extend(new_resources);
Ok(self)
}
/// Adds a resource file with a specific format and optional language override.
///
/// This method allows you to specify the format explicitly and optionally
/// override the language that would be inferred from the file path.
///
/// # Arguments
///
/// * `path` - Path to the resource file
/// * `format_type` - The format type to use for parsing
///
/// # Returns
///
/// Returns `self` for method chaining, or an `Error` if the file cannot be read.
pub fn add_file_with_format<P: AsRef<Path>>(
mut self,
path: P,
format_type: FormatType,
) -> Result<Self, Error> {
let language = format_type.language().cloned().or_else(|| {
super::converter::infer_language_from_path(&path, &format_type)
.ok()
.flatten()
});
let domain = path
.as_ref()
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or_default()
.to_string();
let path = path.as_ref();
let mut new_resources = match &format_type {
FormatType::Strings(_) => {
vec![Resource::from(StringsFormat::read_from(path)?)]
}
FormatType::AndroidStrings(_) => {
vec![Resource::from(AndroidStringsFormat::read_from(path)?)]
}
FormatType::Xcstrings => Vec::<Resource>::try_from(XcstringsFormat::read_from(path)?)?,
FormatType::Xliff(_) => Vec::<Resource>::try_from(XliffFormat::read_from(path)?)?,
FormatType::CSV => {
// Parse CSV format and convert to resources
let csv_format = CSVFormat::read_from(path)?;
Vec::<Resource>::try_from(csv_format)?
}
FormatType::TSV => {
// Parse TSV format and convert to resources
let tsv_format = TSVFormat::read_from(path)?;
Vec::<Resource>::try_from(tsv_format)?
}
};
let should_override_language = matches!(
format_type,
FormatType::Strings(_) | FormatType::AndroidStrings(_)
);
for new_resource in &mut new_resources {
if should_override_language && let Some(ref lang) = language {
new_resource.metadata.language = lang.clone();
}
new_resource.metadata.domain = domain.clone();
new_resource
.metadata
.custom
.insert("format".to_string(), format_type.to_string());
}
self.resources.extend(new_resources);
Ok(self)
}
/// Adds a resource file by inferring its format from the file extension with optional language override.
///
/// This method is similar to `add_file` but allows you to specify a language
/// that will override any language inferred from the file path.
///
/// # Arguments
///
/// * `path` - Path to the resource file
/// * `lang` - Optional language code to use (overrides path inference)
///
/// # Returns
///
/// Returns `self` for method chaining, or an `Error` if the file cannot be read.
pub fn read_file_by_extension<P: AsRef<Path>>(
self,
path: P,
lang: Option<String>,
) -> Result<Self, Error> {
let format_type = match path.as_ref().extension().and_then(|s| s.to_str()) {
Some("xml") => FormatType::AndroidStrings(lang),
Some("strings") => FormatType::Strings(lang),
Some("xcstrings") => FormatType::Xcstrings,
Some("xliff") => FormatType::Xliff(lang),
Some("csv") => FormatType::CSV,
Some("tsv") => FormatType::TSV,
extension => {
return Err(Error::UnsupportedFormat(format!(
"Unsupported file extension: {:?}.",
extension
)));
}
};
self.add_file_with_format(path, format_type)
}
/// Adds a resource directly to the builder.
///
/// This method allows you to add a `Resource` instance directly, which is useful
/// when you have resources that were created programmatically or loaded from
/// other sources.
///
/// # Arguments
///
/// * `resource` - The resource to add
///
/// # Returns
///
/// Returns `self` for method chaining.
pub fn add_resource(mut self, resource: Resource) -> Self {
self.resources.push(resource);
self
}
/// Adds multiple resources directly to the builder.
///
/// This method allows you to add multiple `Resource` instances at once.
///
/// # Arguments
///
/// * `resources` - Iterator of resources to add
///
/// # Returns
///
/// Returns `self` for method chaining.
pub fn add_resources<I>(mut self, resources: I) -> Self
where
I: IntoIterator<Item = Resource>,
{
self.resources.extend(resources);
self
}
/// Loads resources from a JSON cache file.
///
/// This method loads resources that were previously cached using `Codec::cache_to_file`.
///
/// # Arguments
///
/// * `path` - Path to the JSON cache file
///
/// # Returns
///
/// Returns `self` for method chaining, or an `Error` if the file cannot be read.
pub fn load_from_cache<P: AsRef<Path>>(mut self, path: P) -> Result<Self, Error> {
let mut reader = std::fs::File::open(path).map_err(Error::Io)?;
let cached_resources: Vec<Resource> =
serde_json::from_reader(&mut reader).map_err(Error::Parse)?;
self.resources.extend(cached_resources);
Ok(self)
}
/// Builds the final `Codec` instance.
///
/// This method consumes the builder and returns the constructed `Codec`.
///
/// # Returns
///
/// Returns the constructed `Codec` instance.
pub fn build(self) -> super::codec::Codec {
super::codec::Codec {
resources: self.resources,
}
}
/// Builds the final `Codec` instance and validates it.
///
/// This method is similar to `build()` but performs additional validation
/// on the resources before returning the `Codec`.
///
/// # Returns
///
/// Returns the constructed `Codec` instance, or an `Error` if validation fails.
pub fn build_and_validate(self) -> Result<super::codec::Codec, Error> {
let codec = self.build();
// Validate that all resources have a language
for (i, resource) in codec.resources.iter().enumerate() {
if resource.metadata.language.is_empty() {
return Err(Error::Validation(format!(
"Resource at index {} has no language specified",
i
)));
}
}
// Check for duplicate languages
let mut languages = std::collections::HashSet::new();
for resource in &codec.resources {
if !languages.insert(&resource.metadata.language) {
return Err(Error::Validation(format!(
"Duplicate language found: {}",
resource.metadata.language
)));
}
}
Ok(codec)
}
}
impl Default for CodecBuilder {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::NamedTempFile;
#[test]
fn test_builder_read_file_by_extension() {
// Create a temporary strings file using tempfile
let temp_file = NamedTempFile::new().unwrap();
let test_file = temp_file.path().with_extension("strings");
let content = r#"/* English localization */
"hello" = "Hello";
"goodbye" = "Goodbye";
"thanks" = "Thank you!";
"#;
// Write the test file
std::fs::write(&test_file, content).unwrap();
// Test the builder with read_file_by_extension
let result = CodecBuilder::new()
.read_file_by_extension(&test_file, Some("en".to_string()))
.unwrap()
.build();
// Verify the result
assert_eq!(result.resources.len(), 1);
let resource = &result.resources[0];
assert_eq!(resource.metadata.language, "en");
assert_eq!(resource.entries.len(), 3);
// Clean up - tempfile will automatically clean up when temp_file goes out of scope
let _ = std::fs::remove_file(&test_file);
}
}