-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathconvert.rs
More file actions
1120 lines (1038 loc) · 41.6 KB
/
convert.rs
File metadata and controls
1120 lines (1038 loc) · 41.6 KB
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::formats::{self, parse_custom_format};
use crate::transformers::custom_format_to_resource;
use crate::ui;
use crate::validation::{self, validate_custom_format_file};
use langcodec::{Codec, ReadOptions, convert_auto, formats::FormatType};
use std::fs::File;
use std::io::BufWriter;
#[derive(Debug, Clone)]
pub struct ConvertOptions {
pub input_format: Option<String>,
pub output_format: Option<String>,
pub source_language: Option<String>,
pub version: Option<String>,
pub output_lang: Option<String>,
pub exclude_lang: Vec<String>,
pub include_lang: Vec<String>,
}
fn parse_standard_output_format(format: &str) -> Result<FormatType, String> {
match format.to_lowercase().as_str() {
"strings" => Ok(FormatType::Strings(None)),
"android" | "androidstrings" => Ok(FormatType::AndroidStrings(None)),
"xcstrings" => Ok(FormatType::Xcstrings),
"xliff" => Ok(FormatType::Xliff(None)),
"csv" => Ok(FormatType::CSV),
"tsv" => Ok(FormatType::TSV),
_ => Err(format!(
"Unsupported output format: '{}'. Supported formats: strings, android, xcstrings, xliff, csv, tsv",
format
)),
}
}
fn wants_named_output(
output: &str,
output_format_hint: Option<&String>,
extension: &str,
format_name: &str,
) -> bool {
output.ends_with(extension)
|| output_format_hint.is_some_and(|hint| hint.eq_ignore_ascii_case(format_name))
}
fn wants_xcstrings_output(output: &str, output_format_hint: Option<&String>) -> bool {
wants_named_output(output, output_format_hint, ".xcstrings", "xcstrings")
}
fn wants_xliff_output(output: &str, output_format_hint: Option<&String>) -> bool {
wants_named_output(output, output_format_hint, ".xliff", "xliff")
}
fn resolve_xliff_source_language(
resources: &[langcodec::Resource],
explicit_source_language: Option<&String>,
target_language: &str,
) -> Result<String, String> {
if let Some(explicit_source_language) = explicit_source_language {
let trimmed = explicit_source_language.trim();
if trimmed.is_empty() {
return Err("--source-language cannot be empty for .xliff output".to_string());
}
return Ok(trimmed.to_string());
}
let metadata_source_languages = resources
.iter()
.filter_map(|resource| resource.metadata.custom.get("source_language"))
.map(|value| value.trim())
.filter(|value| !value.is_empty())
.collect::<std::collections::BTreeSet<_>>();
let available_languages = resources
.iter()
.map(|resource| resource.metadata.language.trim())
.filter(|language| !language.is_empty())
.collect::<std::collections::BTreeSet<_>>();
if metadata_source_languages.len() > 1 {
return Err(format!(
"Conflicting source_language metadata found for .xliff output: {}. Pass --source-language.",
metadata_source_languages
.into_iter()
.collect::<Vec<_>>()
.join(", ")
));
}
if let Some(source_language) = metadata_source_languages.iter().next() {
let extras = available_languages
.iter()
.filter(|language| **language != *source_language && **language != target_language)
.cloned()
.collect::<Vec<_>>();
if *source_language != target_language && extras.is_empty() {
return Ok((*source_language).to_string());
}
return Err(format!(
"source_language metadata '{}' is ambiguous for .xliff output with available languages ({}). Pass --source-language.",
source_language,
available_languages
.iter()
.cloned()
.collect::<Vec<_>>()
.join(", ")
));
}
if available_languages.is_empty() {
return Err("XLIFF output requires language metadata on the input resources".to_string());
}
if available_languages.len() == 1 {
return Ok(available_languages.iter().next().unwrap().to_string());
}
let non_target_languages = available_languages
.iter()
.filter(|language| **language != target_language)
.cloned()
.collect::<Vec<_>>();
match non_target_languages.as_slice() {
[source_language] => Ok((*source_language).to_string()),
_ => Err(format!(
"Could not infer the XLIFF source language from available languages ({}). Pass --source-language.",
available_languages
.into_iter()
.collect::<Vec<_>>()
.join(", ")
)),
}
}
fn infer_output_path_language(path: &str) -> Option<String> {
match langcodec::infer_format_from_path(path) {
Some(FormatType::Strings(Some(lang))) | Some(FormatType::AndroidStrings(Some(lang))) => {
Some(lang)
}
_ => None,
}
}
fn resolve_convert_output_format(
output: &str,
output_format_hint: Option<&String>,
output_lang: Option<&String>,
) -> Result<FormatType, String> {
let mut output_format = if let Some(format_hint) = output_format_hint {
parse_standard_output_format(format_hint)?
} else {
langcodec::infer_format_from_path(output)
.or_else(|| langcodec::infer_format_from_extension(output))
.ok_or_else(|| format!("Cannot infer output format from extension: {}", output))?
};
let path_language = infer_output_path_language(output);
match &output_format {
FormatType::Strings(_) | FormatType::AndroidStrings(_) => {
if let Some(language) = output_lang {
if let Some(path_language) = path_language
&& path_language != *language
{
return Err(format!(
"--output-lang '{}' conflicts with language '{}' implied by output path '{}'",
language, path_language, output
));
}
output_format = output_format.with_language(Some(language.clone()));
} else if let Some(path_language) = path_language {
output_format = output_format.with_language(Some(path_language));
}
Ok(output_format)
}
FormatType::Xliff(_) => {
if let Some(language) = output_lang {
output_format = output_format.with_language(Some(language.clone()));
Ok(output_format)
} else {
Err(
".xliff output requires --output-lang to select the target language"
.to_string(),
)
}
}
FormatType::Xcstrings | FormatType::CSV | FormatType::TSV => {
if let Some(language) = output_lang {
Err(format!(
"--output-lang '{}' is only supported for .strings, strings.xml, or .xliff output",
language
))
} else {
Ok(output_format)
}
}
}
}
pub fn run_unified_convert_command(
input: String,
output: String,
options: ConvertOptions,
strict: bool,
) {
let wants_xliff = wants_xliff_output(&output, options.output_format.as_ref());
if wants_xliff {
println!(
"{}",
ui::status_line_stdout(
ui::Tone::Info,
"Converting to XLIFF 1.2 with explicit source/target language selection...",
)
);
match read_resources_from_any_input(&input, options.input_format.as_ref(), strict).and_then(
|mut resources| {
let output_format = resolve_convert_output_format(
&output,
options.output_format.as_ref(),
options.output_lang.as_ref(),
)?;
let target_language =
match &output_format {
FormatType::Xliff(Some(target_language)) => target_language.clone(),
_ => return Err(
".xliff output requires --output-lang to select the target language"
.to_string(),
),
};
let source_language = resolve_xliff_source_language(
&resources,
options.source_language.as_ref(),
&target_language,
)?;
for resource in &mut resources {
resource
.metadata
.custom
.insert("source_language".to_string(), source_language.clone());
}
convert_resources_to_format(resources, &output, output_format)
.map_err(|e| format!("Error converting to xliff: {}", e))
},
) {
Ok(()) => {
println!(
"{}",
ui::status_line_stdout(ui::Tone::Success, "Successfully converted to xliff",)
);
return;
}
Err(e) => {
println!(
"{}",
ui::status_line_stdout(ui::Tone::Error, "Conversion to xliff failed")
);
eprintln!("Error: {}", e);
std::process::exit(1);
}
}
}
if let Some(output_lang) = options.output_lang.as_ref() {
if output.ends_with(".langcodec") {
eprintln!(
"Error: --output-lang '{}' is not supported for .langcodec output. Use --include-lang instead.",
output_lang
);
std::process::exit(1);
}
println!(
"{}",
ui::status_line_stdout(
ui::Tone::Info,
&format!("Converting with explicit output language '{}'", output_lang),
)
);
match read_resources_from_any_input(&input, options.input_format.as_ref(), strict).and_then(
|resources| {
let output_format = resolve_convert_output_format(
&output,
options.output_format.as_ref(),
options.output_lang.as_ref(),
)?;
convert_resources_to_format(resources, &output, output_format)
.map_err(|e| format!("Error converting to output format: {}", e))
},
) {
Ok(()) => {
println!(
"{}",
ui::status_line_stdout(
ui::Tone::Success,
"Successfully converted with explicit output language",
)
);
return;
}
Err(e) => {
println!(
"{}",
ui::status_line_stdout(ui::Tone::Error, "Conversion failed")
);
eprintln!("Error: {}", e);
std::process::exit(1);
}
}
}
// Special handling: when targeting xcstrings, ensure required metadata exists.
// If source_language/version are missing, default to en/1.0 respectively.
let wants_xcstrings = wants_xcstrings_output(&output, options.output_format.as_ref());
if wants_xcstrings {
println!(
"{}",
ui::status_line_stdout(
ui::Tone::Info,
"Converting to xcstrings with default sourceLanguage if missing...",
)
);
match read_resources_from_any_input(&input, options.input_format.as_ref(), strict).and_then(
|mut resources| {
// Determine source_language priority: explicit flag > metadata > default
let source_language = options
.source_language
.as_ref()
.and_then(|s| {
let trimmed = s.trim();
if !trimmed.is_empty() {
Some(s.clone())
} else {
None
}
})
.or_else(|| {
resources.first().and_then(|r| {
r.metadata
.custom
.get("source_language")
.cloned()
.filter(|s| !s.trim().is_empty())
})
})
.unwrap_or_else(|| "en".to_string());
// Determine version: keep existing if present; otherwise default to "1.0"
let version = options
.version
.clone()
.or_else(|| {
resources
.first()
.and_then(|r| r.metadata.custom.get("version").cloned())
})
.unwrap_or_else(|| "1.0".to_string());
// Apply to all resources so the writer has consistent metadata
for r in &mut resources {
r.metadata
.custom
.insert("source_language".to_string(), source_language.clone());
r.metadata
.custom
.insert("version".to_string(), version.clone());
}
convert_resources_to_format(resources, &output, FormatType::Xcstrings)
.map_err(|e| format!("Error converting to xcstrings: {}", e))
},
) {
Ok(()) => {
println!(
"{}",
ui::status_line_stdout(
ui::Tone::Success,
"Successfully converted to xcstrings",
)
);
return;
}
Err(e) => {
println!(
"{}",
ui::status_line_stdout(ui::Tone::Error, "Conversion to xcstrings failed")
);
// Preserve legacy expectation for invalid JSON: surface an inference hint
if input.ends_with(".json") {
eprintln!("Cannot infer input format");
}
eprintln!("Error: {}", e);
std::process::exit(1);
}
}
}
// If the desired output is .langcodec, handle via resource serialization
if output.ends_with(".langcodec") {
let filter_msg = if !options.include_lang.is_empty() || !options.exclude_lang.is_empty() {
let mut parts = Vec::new();
if !options.include_lang.is_empty() {
parts.push(format!("including: {}", options.include_lang.join(", ")));
}
if !options.exclude_lang.is_empty() {
parts.push(format!("excluding: {}", options.exclude_lang.join(", ")));
}
format!(" with language filtering ({})", parts.join(", "))
} else {
String::new()
};
println!(
"{}",
ui::status_line_stdout(
ui::Tone::Info,
&format!(
"Converting input to .langcodec (Resource JSON array){}...",
filter_msg
),
)
);
match read_resources_from_any_input(&input, options.input_format.as_ref(), strict).and_then(
|resources| {
// Apply language filtering
let filtered_resources = resources
.into_iter()
.filter(|resource| {
let lang = &resource.metadata.language;
// If include_lang is specified, only include those languages
if !options.include_lang.is_empty() && !options.include_lang.contains(lang)
{
return false;
}
// If exclude_lang is specified, exclude those languages
if !options.exclude_lang.is_empty() && options.exclude_lang.contains(lang) {
return false;
}
true
})
.collect();
write_resources_as_langcodec(&filtered_resources, &output)
},
) {
Ok(()) => {
let filter_msg =
if !options.include_lang.is_empty() || !options.exclude_lang.is_empty() {
let mut parts = Vec::new();
if !options.include_lang.is_empty() {
parts.push(format!("including: {}", options.include_lang.join(", ")));
}
if !options.exclude_lang.is_empty() {
parts.push(format!("excluding: {}", options.exclude_lang.join(", ")));
}
format!(" with language filtering ({})", parts.join(", "))
} else {
String::new()
};
println!(
"{}",
ui::status_line_stdout(
ui::Tone::Success,
&format!(
"Successfully converted to .langcodec (Resource JSON array){}",
filter_msg
),
)
);
return;
}
Err(e) => {
let filter_msg =
if !options.include_lang.is_empty() || !options.exclude_lang.is_empty() {
let mut parts = Vec::new();
if !options.include_lang.is_empty() {
parts.push(format!("including: {}", options.include_lang.join(", ")));
}
if !options.exclude_lang.is_empty() {
parts.push(format!("excluding: {}", options.exclude_lang.join(", ")));
}
format!(" with language filtering ({})", parts.join(", "))
} else {
String::new()
};
println!(
"{}",
ui::status_line_stdout(
ui::Tone::Error,
&format!("Conversion to .langcodec failed{}", filter_msg),
)
);
eprintln!("Error: {}", e);
std::process::exit(1);
}
}
}
if strict {
if let (Some(input_fmt), Some(output_fmt)) = (
options.input_format.as_deref(),
options.output_format.as_deref(),
) {
println!(
"{}",
ui::status_line_stdout(
ui::Tone::Info,
"Strict mode: converting with explicit format hints only...",
)
);
if let Err(e) = try_explicit_format_conversion(
&input,
&output,
input_fmt,
output_fmt,
options.output_lang.as_ref(),
) {
println!(
"{}",
ui::status_line_stdout(ui::Tone::Error, "Strict conversion failed")
);
eprintln!("Error: {}", e);
std::process::exit(1);
}
println!(
"{}",
ui::status_line_stdout(ui::Tone::Success, "Successfully converted in strict mode",)
);
return;
}
if input.ends_with(".json")
|| input.ends_with(".yaml")
|| input.ends_with(".yml")
|| input.ends_with(".langcodec")
{
println!(
"{}",
ui::status_line_stdout(
ui::Tone::Info,
"Strict mode: converting custom format without fallback...",
)
);
if let Err(e) = try_custom_format_conversion(
&input,
&output,
&options.input_format,
options.output_format.as_ref(),
options.output_lang.as_ref(),
) {
println!(
"{}",
ui::status_line_stdout(ui::Tone::Error, "Strict conversion failed")
);
eprintln!("Error: {}", e);
std::process::exit(1);
}
println!(
"{}",
ui::status_line_stdout(ui::Tone::Success, "Successfully converted in strict mode",)
);
return;
}
println!(
"{}",
ui::status_line_stdout(
ui::Tone::Info,
"Strict mode: converting using extension-based standard formats only...",
)
);
if let Err(e) = convert_auto(&input, &output) {
println!(
"{}",
ui::status_line_stdout(ui::Tone::Error, "Strict conversion failed")
);
eprintln!("Error: {}", e);
std::process::exit(1);
}
println!(
"{}",
ui::status_line_stdout(ui::Tone::Success, "Successfully converted in strict mode",)
);
return;
}
// Strategy 1: Try standard lib crate conversion first
println!(
"{}",
ui::status_line_stdout(
ui::Tone::Info,
"Trying standard format detection from file extensions...",
)
);
if let Ok(()) = convert_auto(&input, &output) {
println!(
"{}",
ui::status_line_stdout(
ui::Tone::Success,
"Successfully converted using standard format detection",
)
);
return;
}
// Strategy 2: Try custom formats for JSON/YAML/langcodec files
if input.ends_with(".json")
|| input.ends_with(".yaml")
|| input.ends_with(".yml")
|| input.ends_with(".langcodec")
{
// For JSON files without explicit format, try standard format detection first
if input.ends_with(".json") && options.input_format.is_none() {
println!(
"{}",
ui::status_line_stdout(ui::Tone::Info, "Trying standard JSON format detection...",)
);
// Try to use the standard format detection which will show proper JSON parsing errors
if convert_auto(&input, &output).is_err() {
println!(
"{}",
ui::status_line_stdout(
ui::Tone::Info,
"Trying custom JSON format conversion...",
)
);
// If standard detection fails, try custom formats
match try_custom_format_conversion(
&input,
&output,
&options.input_format,
options.output_format.as_ref(),
options.output_lang.as_ref(),
) {
Ok(()) => {
println!(
"{}",
ui::status_line_stdout(
ui::Tone::Success,
"Successfully converted using custom JSON format",
)
);
return;
}
Err(custom_error) => {
// If both fail, show the custom conversion error because it is usually
// more actionable than the initial extension-based failure.
println!(
"{}",
ui::status_line_stdout(ui::Tone::Error, "Conversion failed")
);
eprintln!("Error: {}", custom_error);
std::process::exit(1);
}
}
}
} else {
// For YAML and langcodec files, try custom formats directly
println!(
"{}",
ui::status_line_stdout(ui::Tone::Info, "Converting using custom format...")
);
if let Err(e) = try_custom_format_conversion(
&input,
&output,
&options.input_format,
options.output_format.as_ref(),
options.output_lang.as_ref(),
) {
println!(
"{}",
ui::status_line_stdout(ui::Tone::Error, "Custom format conversion failed",)
);
eprintln!("Error: {}", e);
std::process::exit(1);
}
println!(
"{}",
ui::status_line_stdout(
ui::Tone::Success,
"Successfully converted using custom format",
)
);
return;
}
}
// Strategy 3: If we have format hints, try with explicit formats
if let (Some(input_fmt), Some(output_fmt)) =
(options.input_format.clone(), options.output_format.clone())
{
println!(
"{}",
ui::status_line_stdout(ui::Tone::Info, "Converting with explicit format hints...")
);
if let Err(e) = try_explicit_format_conversion(
&input,
&output,
&input_fmt,
&output_fmt,
options.output_lang.as_ref(),
) {
println!(
"{}",
ui::status_line_stdout(ui::Tone::Error, "Explicit format conversion failed",)
);
eprintln!("Error: {}", e);
std::process::exit(1);
}
println!(
"{}",
ui::status_line_stdout(
ui::Tone::Success,
"Successfully converted with explicit formats",
)
);
return;
}
// If all strategies failed, provide helpful error message
println!(
"{}",
ui::status_line_stdout(ui::Tone::Error, "All conversion strategies failed")
);
print_conversion_error(&input, &output);
std::process::exit(1);
}
fn try_custom_format_conversion(
input: &str,
output: &str,
input_format: &Option<String>,
output_format: Option<&String>,
output_lang: Option<&String>,
) -> Result<(), String> {
// Validate custom format file
validate_custom_format_file(input)?;
let custom_format = if let Some(format_str) = input_format {
parse_custom_format(format_str)?
} else {
// Auto-detect format based on file content
let file_content = std::fs::read_to_string(input)
.map_err(|e| format!("Error reading file {}: {}", input, e))?;
// Validate file content
formats::validate_custom_format_content(input, &file_content)?
};
// Convert custom format to Resource
let resources = custom_format_to_resource(input.to_string(), custom_format)?;
// If output is .langcodec, serialize resources as JSON array
if output.ends_with(".langcodec") {
write_resources_as_langcodec(&resources, output)?;
return Ok(());
}
// Get output format type
let output_format_type = resolve_convert_output_format(output, output_format, output_lang)?;
// Convert to target format
convert_resources_to_format(resources, output, output_format_type)
.map_err(|e| format!("Error converting to output format: {}", e))?;
Ok(())
}
fn print_conversion_error(input: &str, output: &str) {
eprintln!("Error: Could not convert '{}' to '{}'", input, output);
eprintln!();
eprintln!("Tried the following strategies:");
eprintln!("1. Standard format detection from file extensions");
if input.ends_with(".json") {
eprintln!("2. Custom JSON format conversion");
}
if input.ends_with(".yaml") || input.ends_with(".yml") {
eprintln!("2. Custom YAML format conversion");
}
if input.ends_with(".langcodec") {
eprintln!("2. Custom langcodec Resource array format conversion");
}
eprintln!();
eprintln!("Supported input formats:");
eprintln!("- .strings (Apple strings files)");
eprintln!("- .xml (Android strings files)");
eprintln!("- .xcstrings (Apple xcstrings files)");
eprintln!("- .xliff (Apple/Xcode XLIFF 1.2 files)");
eprintln!("- .csv (CSV files)");
eprintln!("- .tsv (TSV files)");
eprintln!("- .langcodec (Resource JSON array)");
eprintln!("- .json (JSON key-value pairs or Resource format)");
eprintln!("- .yaml/.yml (YAML language map format)");
eprintln!();
eprintln!("Supported output formats:");
eprintln!("- .strings (Apple strings files)");
eprintln!("- .xml (Android strings files)");
eprintln!("- .xcstrings (Apple xcstrings files)");
eprintln!("- .xliff (Apple/Xcode XLIFF 1.2 files)");
eprintln!("- .csv (CSV files)");
eprintln!("- .tsv (TSV files)");
eprintln!("- .langcodec (Resource JSON array)");
eprintln!();
eprintln!(
"For JSON files, the command will try both standard Resource format and key-value pairs."
);
eprintln!("For YAML files, the command will try YAML language map format.");
eprintln!(
"Custom formats: {}",
formats::get_supported_custom_formats()
);
}
/// Convert a Vec<Resource> to a specific output format using the lib crate
fn convert_resources_to_format(
resources: Vec<langcodec::Resource>,
output: &str,
output_format: FormatType,
) -> Result<(), langcodec::Error> {
langcodec::converter::convert_resources_to_format(resources, output, output_format)
}
/// Try explicit format conversion with specified input and output formats
fn try_explicit_format_conversion(
input: &str,
output: &str,
input_format: &str,
output_format: &str,
output_lang: Option<&String>,
) -> Result<(), String> {
// Validate input file exists
validation::validate_file_path(input)?;
// Validate output path
validation::validate_output_path(output)?;
// Parse input format
let input_format_type = match input_format.to_lowercase().as_str() {
"strings" => langcodec::formats::FormatType::Strings(None),
"android" | "androidstrings" => langcodec::formats::FormatType::AndroidStrings(None),
"xcstrings" => langcodec::formats::FormatType::Xcstrings,
"xliff" => langcodec::formats::FormatType::Xliff(None),
"csv" => langcodec::formats::FormatType::CSV,
"tsv" => langcodec::formats::FormatType::TSV,
_ => {
return Err(format!(
"Unsupported input format: '{}'. Supported formats: strings, android, xcstrings, xliff, csv, tsv",
input_format
));
}
};
// Handle .langcodec output specially by reading resources then serializing
if output_format.to_lowercase().as_str() == "langcodec" || output.ends_with(".langcodec") {
// Read resources using explicit input format
let mut codec = Codec::new();
codec
.read_file_by_type(input, input_format_type)
.map_err(|e| format!("Failed to read input with explicit format: {}", e))?;
write_resources_as_langcodec(&codec.resources, output)
} else {
// Parse output format
let output_format_type =
resolve_convert_output_format(output, Some(&output_format.to_string()), output_lang)?;
// Use the lib crate's convert function
langcodec::convert(input, input_format_type, output, output_format_type)
.map_err(|e| format!("Conversion error: {}", e))
}
}
/// Try to read a custom format file and add it to the codec for view
pub fn try_custom_format_view(
input: &str,
_lang: Option<String>,
codec: &mut Codec,
) -> Result<(), String> {
// Validate custom format file
validation::validate_custom_format_file(input)?;
// Auto-detect format based on file content
let file_content = std::fs::read_to_string(input)
.map_err(|e| format!("Error reading file {}: {}", input, e))?;
// Validate file content
let custom_format = formats::validate_custom_format_content(input, &file_content)?;
// Convert custom format to Resource
let resources = custom_format_to_resource(input.to_string(), custom_format)?;
// Add resources to codec
for resource in resources {
codec.add_resource(resource);
}
Ok(())
}
/// Serialize resources as a .langcodec (Resource JSON array) file
fn write_resources_as_langcodec(
resources: &Vec<langcodec::Resource>,
output: &str,
) -> Result<(), String> {
let file = File::create(output).map_err(|e| format!("Failed to create {}: {}", output, e))?;
let writer = BufWriter::new(file);
serde_json::to_writer_pretty(writer, resources)
.map_err(|e| format!("Failed to write .langcodec JSON: {}", e))
}
/// Read resources from any supported input (standard or custom formats)
pub fn read_resources_from_any_input(
input: &str,
input_format_hint: Option<&String>,
strict: bool,
) -> Result<Vec<langcodec::Resource>, String> {
if strict {
if let Some(fmt) = input_format_hint {
let fmt_lower = fmt.to_lowercase();
let maybe_std = match fmt_lower.as_str() {
"strings" => Some(langcodec::formats::FormatType::Strings(None)),
"android" | "androidstrings" => {
Some(langcodec::formats::FormatType::AndroidStrings(None))
}
"xcstrings" => Some(langcodec::formats::FormatType::Xcstrings),
"xliff" => Some(langcodec::formats::FormatType::Xliff(None)),
"csv" => Some(langcodec::formats::FormatType::CSV),
"tsv" => Some(langcodec::formats::FormatType::TSV),
_ => None,
};
if let Some(std_fmt) = maybe_std {
let mut codec = Codec::new();
codec
.read_file_by_type_with_options(
input,
std_fmt,
&ReadOptions::new().with_strict(true),
)
.map_err(|e| format!("Failed to read input with explicit format: {}", e))?;
return Ok(codec.resources);
}
let custom_format = parse_custom_format(fmt)?;
let resources = custom_format_to_resource(input.to_string(), custom_format)?;
return Ok(resources);
}
if input.ends_with(".strings")
|| input.ends_with(".xml")
|| input.ends_with(".xcstrings")
|| input.ends_with(".xliff")
|| input.ends_with(".csv")
|| input.ends_with(".tsv")
{
let mut codec = Codec::new();
codec
.read_file_by_extension_with_options(input, &ReadOptions::new().with_strict(true))
.map_err(|e| format!("Failed to read input: {}", e))?;
return Ok(codec.resources);
}
if input.ends_with(".json")
|| input.ends_with(".yaml")
|| input.ends_with(".yml")
|| input.ends_with(".langcodec")
{
validate_custom_format_file(input)?;
let file_content = std::fs::read_to_string(input)
.map_err(|e| format!("Error reading file {}: {}", input, e))?;
let custom_format = formats::validate_custom_format_content(input, &file_content)?;
let resources = custom_format_to_resource(input.to_string(), custom_format)?;
return Ok(resources);
}
return Err(format!(
"Unsupported input format or file extension: '{}'. Supported formats: .strings, .xml, .xcstrings, .xliff, .csv, .tsv, .json, .yaml, .yml, .langcodec",
input
));
}
// First: if explicit input format is provided and is a standard format, use it
if let Some(fmt) = input_format_hint {
let fmt_lower = fmt.to_lowercase();
let maybe_std = match fmt_lower.as_str() {
"strings" => Some(langcodec::formats::FormatType::Strings(None)),
"android" | "androidstrings" => {
Some(langcodec::formats::FormatType::AndroidStrings(None))
}
"xcstrings" => Some(langcodec::formats::FormatType::Xcstrings),
"xliff" => Some(langcodec::formats::FormatType::Xliff(None)),
"csv" => Some(langcodec::formats::FormatType::CSV),
"tsv" => Some(langcodec::formats::FormatType::TSV),
_ => None,