Skip to main content

langcodec_cli/
merge.rs

1use crate::formats::parse_custom_format;
2use crate::transformers::custom_format_to_resource;
3use crate::ui;
4
5use langcodec::{Codec, ReadOptions, converter};
6use rayon::prelude::*;
7
8/// Strategy for handling conflicts when merging localization files.
9#[derive(Debug, Clone, PartialEq, clap::ValueEnum)]
10pub enum ConflictStrategy {
11    /// Keep the first occurrence of a key
12    First,
13    /// Keep the last occurrence of a key (default)
14    Last,
15    /// Skip conflicting entries
16    Skip,
17}
18
19fn resolve_merge_output_format(
20    output: &str,
21    lang: Option<&String>,
22) -> Result<langcodec::FormatType, String> {
23    let mut output_format = converter::infer_format_from_path(output)
24        .ok_or_else(|| format!("Cannot infer format from output path: {}", output))?;
25
26    let path_language = match &output_format {
27        langcodec::FormatType::Strings(Some(language))
28        | langcodec::FormatType::Stringsdict(Some(language))
29        | langcodec::FormatType::AndroidStrings(Some(language)) => Some(language.clone()),
30        _ => None,
31    };
32
33    match &output_format {
34        langcodec::FormatType::Strings(_)
35        | langcodec::FormatType::Stringsdict(_)
36        | langcodec::FormatType::AndroidStrings(_) => {
37            if let Some(language) = lang {
38                if let Some(path_language) = path_language
39                    && path_language != *language
40                {
41                    return Err(format!(
42                        "--lang '{}' conflicts with language '{}' implied by output path '{}'",
43                        language, path_language, output
44                    ));
45                }
46                output_format = output_format.with_language(Some(language.clone()));
47            }
48            Ok(output_format)
49        }
50        langcodec::FormatType::Xliff(_) => Err(
51            ".xliff is not supported by `merge` in v1. Use `convert` for XLIFF generation."
52                .to_string(),
53        ),
54        langcodec::FormatType::Xcstrings
55        | langcodec::FormatType::CSV
56        | langcodec::FormatType::TSV => Ok(output_format),
57    }
58}
59
60/// Run the merge command: merge multiple localization files into one output file.
61pub fn run_merge_command(
62    inputs: Vec<String>,
63    output: String,
64    strategy: ConflictStrategy,
65    lang: Option<String>,
66    source_language_override: Option<String>,
67    version_override: Option<String>,
68    strict: bool,
69) {
70    if inputs.is_empty() {
71        eprintln!(
72            "{}",
73            ui::status_line_stderr(
74                ui::Tone::Error,
75                "Error: At least one input file is required."
76            )
77        );
78        std::process::exit(1);
79    }
80
81    // Read all input files concurrently into Codecs, then combine and merge
82    println!(
83        "{}",
84        ui::status_line_stdout(
85            ui::Tone::Info,
86            &format!("Reading {} input files...", inputs.len()),
87        )
88    );
89    let read_results: Vec<Result<Codec, String>> = inputs
90        .par_iter()
91        .map(|input| read_input_to_codec(input, lang.clone(), strict))
92        .collect();
93
94    let mut input_codecs: Vec<Codec> = Vec::with_capacity(read_results.len());
95    for (idx, res) in read_results.into_iter().enumerate() {
96        match res {
97            Ok(c) => input_codecs.push(c),
98            Err(e) => {
99                println!(
100                    "{}",
101                    ui::status_line_stdout(
102                        ui::Tone::Error,
103                        &format!("Error reading input file {}/{}", idx + 1, inputs.len()),
104                    )
105                );
106                eprintln!("{}", e);
107                std::process::exit(1);
108            }
109        }
110    }
111
112    // Combine all input codecs first, then merge by language
113    let mut codec = Codec::from_codecs(input_codecs);
114
115    // Skip validation for merge operations since we expect multiple resources with potentially duplicate languages
116
117    // Merge resources using the new lib crate method
118    println!(
119        "{}",
120        ui::status_line_stdout(ui::Tone::Info, "Merging resources...")
121    );
122    let conflict_strategy = match strategy {
123        ConflictStrategy::First => langcodec::types::ConflictStrategy::First,
124        ConflictStrategy::Last => langcodec::types::ConflictStrategy::Last,
125        ConflictStrategy::Skip => langcodec::types::ConflictStrategy::Skip,
126    };
127
128    let merge_count = codec.merge_resources(&conflict_strategy);
129    println!(
130        "{}",
131        ui::status_line_stdout(
132            ui::Tone::Success,
133            &format!("Merged {} language groups", merge_count),
134        )
135    );
136
137    println!(
138        "{}",
139        ui::status_line_stdout(ui::Tone::Info, "Writing merged output...")
140    );
141    match resolve_merge_output_format(&output, lang.as_ref()) {
142        Ok(format) => {
143            println!(
144                "{}",
145                ui::status_line_stdout(
146                    ui::Tone::Info,
147                    &format!("Converting resources to format: {:?}", format),
148                )
149            );
150            // Set source_language field in the resources to make sure xcstrings format would not throw an error
151            // First, try to get the source language from the first resource if it exists; otherwise, the first resource's language
152            // would be used as the source language. If the two checks fail, the default value "en" would be used.
153            let source_language = source_language_override
154                .filter(|s| !s.trim().is_empty())
155                .unwrap_or_else(|| {
156                    codec
157                        .resources
158                        .first()
159                        .and_then(|r| {
160                            r.metadata
161                                .custom
162                                .get("source_language")
163                                .cloned()
164                                .filter(|s| !s.trim().is_empty())
165                        })
166                        .unwrap_or_else(|| {
167                            codec
168                                .resources
169                                .first()
170                                .map(|r| r.metadata.language.clone())
171                                .unwrap_or("en".to_string())
172                        })
173                });
174
175            println!(
176                "{}",
177                ui::status_line_stdout(
178                    ui::Tone::Accent,
179                    &format!("Setting metadata.source_language to: {}", source_language),
180                )
181            );
182
183            // Set version field in the resources to make sure xcstrings format would not throw an error
184            let version = version_override.unwrap_or_else(|| {
185                codec
186                    .resources
187                    .first()
188                    .and_then(|r| r.metadata.custom.get("version").cloned())
189                    .unwrap_or_else(|| "1.0".to_string())
190            });
191
192            println!(
193                "{}",
194                ui::status_line_stdout(
195                    ui::Tone::Accent,
196                    &format!("Setting metadata.version to: {}", version),
197                )
198            );
199
200            codec.iter_mut().for_each(|r| {
201                r.metadata
202                    .custom
203                    .insert("source_language".to_string(), source_language.clone());
204                r.metadata
205                    .custom
206                    .insert("version".to_string(), version.clone());
207            });
208
209            if let Err(e) = converter::convert_resources_to_format(codec.resources, &output, format)
210            {
211                println!(
212                    "{}",
213                    ui::status_line_stdout(ui::Tone::Error, "Error converting resources to format")
214                );
215                eprintln!("Error converting to {}: {}", output, e);
216                std::process::exit(1);
217            }
218        }
219        Err(e) => {
220            println!(
221                "{}",
222                ui::status_line_stdout(ui::Tone::Error, "Error writing output file")
223            );
224            eprintln!("Error writing to {}: {}", output, e);
225            std::process::exit(1);
226        }
227    }
228
229    println!(
230        "{}",
231        ui::status_line_stdout(
232            ui::Tone::Success,
233            &format!("Successfully merged {} files into {}", inputs.len(), output),
234        )
235    );
236}
237
238/// Read a single input file into a vector of Resources, supporting both standard and custom formats
239fn read_input_to_resources(
240    input: &str,
241    lang: Option<String>,
242    strict: bool,
243) -> Result<Vec<langcodec::Resource>, String> {
244    if strict {
245        if input.ends_with(".json") || input.ends_with(".yaml") || input.ends_with(".yml") {
246            crate::validation::validate_custom_format_file(input)
247                .map_err(|e| format!("Failed to validate {}: {}", input, e))?;
248
249            let file_content = std::fs::read_to_string(input)
250                .map_err(|e| format!("Error reading file {}: {}", input, e))?;
251
252            crate::formats::validate_custom_format_content(input, &file_content)
253                .map_err(|e| format!("Invalid custom format {}: {}", input, e))?;
254
255            let resources = custom_format_to_resource(
256                input.to_string(),
257                parse_custom_format("json-language-map")
258                    .map_err(|e| format!("Failed to parse custom format: {}", e))?,
259            )
260            .map_err(|e| format!("Failed to convert custom format {}: {}", input, e))?;
261
262            return Ok(resources);
263        }
264
265        let mut local_codec = Codec::new();
266        local_codec
267            .read_file_by_extension_with_options(
268                input,
269                &ReadOptions::new()
270                    .with_language_hint(lang)
271                    .with_strict(true),
272            )
273            .map_err(|e| format!("Error reading {}: {}", input, e))?;
274        return Ok(local_codec.resources);
275    }
276
277    // Try standard format via lib crate (uses extension + language inference)
278    {
279        let mut local_codec = Codec::new();
280        if let Ok(()) = local_codec.read_file_by_extension(input, lang.clone()) {
281            return Ok(local_codec.resources);
282        }
283    }
284
285    // Try custom JSON/YAML formats (for merge, we follow the existing JSON-language-map behavior)
286    if input.ends_with(".json") || input.ends_with(".yaml") || input.ends_with(".yml") {
287        // Validate custom format file
288        crate::validation::validate_custom_format_file(input)
289            .map_err(|e| format!("Failed to validate {}: {}", input, e))?;
290
291        // Auto-detect format based on file content
292        let file_content = std::fs::read_to_string(input)
293            .map_err(|e| format!("Error reading file {}: {}", input, e))?;
294
295        // Validate file content (ignore returned format; keep parity with existing merge behavior)
296        crate::formats::validate_custom_format_content(input, &file_content)
297            .map_err(|e| format!("Invalid custom format {}: {}", input, e))?;
298
299        // Convert custom format to Resource using JSON language map to match current merge behavior
300        let resources = custom_format_to_resource(
301            input.to_string(),
302            parse_custom_format("json-language-map")
303                .map_err(|e| format!("Failed to parse custom format: {}", e))?,
304        )
305        .map_err(|e| format!("Failed to convert custom format {}: {}", input, e))?;
306
307        return Ok(resources);
308    }
309
310    Err(format!("Error reading {}: unsupported format", input))
311}
312
313/// Read a single input into a Codec (wrapper over read_input_to_resources)
314fn read_input_to_codec(input: &str, lang: Option<String>, strict: bool) -> Result<Codec, String> {
315    let resources = read_input_to_resources(input, lang, strict)?;
316    Ok(Codec { resources })
317}