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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
/// This module provides the `Codec` struct and associated functionality for reading,
/// writing, caching, and loading localized resource files in various formats.
/// The `Codec` struct manages a collection of `Resource` instances and supports
/// format inference, language detection from file paths, and serialization.
///
/// The module handles different localization file formats such as Apple `.strings`,
/// Android XML strings, and `.xcstrings`, providing methods to read from files by type
/// or extension, write resources back to files, and cache resources to JSON.
///
use crate::formats::{CSVFormat, TSVFormat};
use crate::{ConflictStrategy, merge_resources};
use crate::{
error::Error,
formats::*,
provenance::{ProvenanceRecord, set_resource_provenance},
read_options::ReadOptions,
traits::Parser,
types::{Entry, Resource},
};
use std::path::Path;
/// Represents a collection of localized resources and provides methods to read,
/// write, cache, and load these resources.
#[derive(Debug, Clone)]
pub struct Codec {
/// The collection of resources managed by this codec.
pub resources: Vec<Resource>,
}
impl Default for Codec {
fn default() -> Self {
Codec::new()
}
}
impl Codec {
/// Creates a new, empty `Codec`.
///
/// # Returns
///
/// A new `Codec` instance with no resources.
pub fn new() -> Self {
Codec {
resources: Vec::new(),
}
}
/// Creates a new `CodecBuilder` for fluent construction.
///
/// This method returns a builder that 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;
///
/// let codec = Codec::builder()
/// .add_file("en.strings")?
/// .add_file("fr.strings")?
/// .build();
/// # Ok::<(), langcodec::Error>(())
/// ```
///
/// # Returns
///
/// Returns a new `CodecBuilder` instance.
pub fn builder() -> crate::builder::CodecBuilder {
crate::builder::CodecBuilder::new()
}
/// Returns an iterator over all resources.
pub fn iter(&self) -> std::slice::Iter<'_, Resource> {
self.resources.iter()
}
/// Returns a mutable iterator over all resources.
pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, Resource> {
self.resources.iter_mut()
}
/// Finds a resource by its language code, if present.
pub fn get_by_language(&self, lang: &str) -> Option<&Resource> {
self.resources
.iter()
.find(|res| res.metadata.language == lang)
}
/// Finds a mutable resource by its language code, if present.
pub fn get_mut_by_language(&mut self, lang: &str) -> Option<&mut Resource> {
self.resources
.iter_mut()
.find(|res| res.metadata.language == lang)
}
/// Adds a new resource to the collection.
pub fn add_resource(&mut self, resource: Resource) {
self.resources.push(resource);
}
/// Appends all resources from another `Codec` into this one.
pub fn extend_from(&mut self, mut other: Codec) {
self.resources.append(&mut other.resources);
}
/// Constructs a `Codec` from multiple `Codec` instances by concatenating their resources.
pub fn from_codecs<I>(codecs: I) -> Self
where
I: IntoIterator<Item = Codec>,
{
let mut combined = Codec::new();
for mut c in codecs {
combined.resources.append(&mut c.resources);
}
combined
}
/// Merges multiple `Codec` instances into one and merges resources by language using the given strategy.
///
/// Returns the merged `Codec` containing resources merged per language group.
pub fn merge_codecs<I>(codecs: I, strategy: &ConflictStrategy) -> Self
where
I: IntoIterator<Item = Codec>,
{
let mut combined = Codec::from_codecs(codecs);
let _ = combined.merge_resources(strategy);
combined
}
// ===== HIGH-LEVEL MODIFICATION METHODS =====
/// Finds an entry by its key across all languages.
///
/// Returns an iterator over all resources and their matching entries.
///
/// # Arguments
///
/// * `key` - The entry key to search for
///
/// # Returns
///
/// An iterator yielding `(&Resource, &Entry)` pairs for all matching entries.
///
/// # Example
///
/// ```rust
/// use langcodec::Codec;
///
/// let mut codec = Codec::new();
/// // ... load resources ...
///
/// for (resource, entry) in codec.find_entries("welcome_message") {
/// println!("{}: {}", resource.metadata.language, entry.value);
/// }
/// ```
pub fn find_entries(&self, key: &str) -> Vec<(&Resource, &Entry)> {
let mut results = Vec::new();
for resource in &self.resources {
if let Some(entry) = resource.find_entry(key) {
results.push((resource, entry));
}
}
results
}
/// Finds an entry by its key in a specific language.
///
/// # Arguments
///
/// * `key` - The entry key to search for
/// * `language` - The language code (e.g., "en", "fr")
///
/// # Returns
///
/// `Some(&Entry)` if found, `None` otherwise.
///
/// # Example
///
/// ```rust
/// use langcodec::Codec;
///
/// let mut codec = Codec::new();
/// // ... load resources ...
///
/// if let Some(entry) = codec.find_entry("welcome_message", "en") {
/// println!("English welcome: {}", entry.value);
/// }
/// ```
pub fn find_entry(&self, key: &str, language: &str) -> Option<&Entry> {
self.get_by_language(language)?.find_entry(key)
}
/// Finds a mutable entry by its key in a specific language.
///
/// # Arguments
///
/// * `key` - The entry key to search for
/// * `language` - The language code (e.g., "en", "fr")
///
/// # Returns
///
/// `Some(&mut Entry)` if found, `None` otherwise.
///
/// # Example
///
/// ```rust
/// use langcodec::Codec;
/// use langcodec::types::Translation;
///
/// let mut codec = Codec::new();
/// // ... load resources ...
///
/// if let Some(entry) = codec.find_entry_mut("welcome_message", "en") {
/// entry.value = Translation::Singular("Hello, World!".to_string());
/// entry.status = langcodec::types::EntryStatus::Translated;
/// }
/// ```
pub fn find_entry_mut(&mut self, key: &str, language: &str) -> Option<&mut Entry> {
self.get_mut_by_language(language)?.find_entry_mut(key)
}
/// Updates a translation for a specific key and language.
///
/// # Arguments
///
/// * `key` - The entry key to update
/// * `language` - The language code (e.g., "en", "fr")
/// * `translation` - The new translation value
/// * `status` - Optional new status (defaults to `Translated`)
///
/// # Returns
///
/// `Ok(())` if the entry was found and updated, `Err` if not found.
///
/// # Example
///
/// ```rust
/// use langcodec::{Codec, types::{Translation, EntryStatus}};
///
/// let mut codec = Codec::new();
/// // Add an entry first
/// codec.add_entry("welcome", "en", Translation::Singular("Hello".to_string()), None, None)?;
///
/// codec.update_translation(
/// "welcome",
/// "en",
/// Translation::Singular("Hello, World!".to_string()),
/// Some(EntryStatus::Translated)
/// )?;
/// # Ok::<(), langcodec::Error>(())
/// ```
pub fn update_translation(
&mut self,
key: &str,
language: &str,
translation: crate::types::Translation,
status: Option<crate::types::EntryStatus>,
) -> Result<(), Error> {
if let Some(entry) = self.find_entry_mut(key, language) {
entry.value = translation;
if let Some(new_status) = status {
entry.status = new_status;
}
Ok(())
} else {
Err(Error::InvalidResource(format!(
"Entry '{}' not found in language '{}'",
key, language
)))
}
}
/// Adds a new entry to a specific language.
///
/// If the language doesn't exist, it will be created automatically.
///
/// # Arguments
///
/// * `key` - The entry key
/// * `language` - The language code (e.g., "en", "fr")
/// * `translation` - The translation value
/// * `comment` - Optional comment for translators
/// * `status` - Optional status (defaults to `New`)
///
/// # Returns
///
/// `Ok(())` if the entry was added successfully.
///
/// # Example
///
/// ```rust
/// use langcodec::{Codec, types::{Translation, EntryStatus}};
///
/// let mut codec = Codec::new();
///
/// codec.add_entry(
/// "new_message",
/// "en",
/// Translation::Singular("This is a new message".to_string()),
/// Some("This is a new message for users".to_string()),
/// Some(EntryStatus::New)
/// )?;
/// # Ok::<(), langcodec::Error>(())
/// ```
pub fn add_entry(
&mut self,
key: &str,
language: &str,
translation: crate::types::Translation,
comment: Option<String>,
status: Option<crate::types::EntryStatus>,
) -> Result<(), Error> {
// Find or create the resource for this language
let resource = if let Some(resource) = self.get_mut_by_language(language) {
resource
} else {
// Create a new resource for this language
let new_resource = crate::types::Resource {
metadata: crate::types::Metadata {
language: language.to_string(),
domain: "".to_string(),
custom: std::collections::HashMap::new(),
},
entries: Vec::new(),
};
self.add_resource(new_resource);
self.get_mut_by_language(language).unwrap()
};
let entry = crate::types::Entry {
id: key.to_string(),
value: translation,
comment,
status: status.unwrap_or(crate::types::EntryStatus::New),
custom: std::collections::HashMap::new(),
};
resource.add_entry(entry);
Ok(())
}
/// Removes an entry from a specific language.
///
/// # Arguments
///
/// * `key` - The entry key to remove
/// * `language` - The language code (e.g., "en", "fr")
///
/// # Returns
///
/// `Ok(())` if the entry was found and removed, `Err` if not found.
///
/// # Example
///
/// ```rust
/// use langcodec::{Codec, types::{Translation, EntryStatus}};
///
/// let mut codec = Codec::new();
/// // Add a resource first
/// codec.add_entry("test_key", "en", Translation::Singular("Test".to_string()), None, None)?;
///
/// // Now remove it
/// codec.remove_entry("test_key", "en")?;
/// # Ok::<(), langcodec::Error>(())
/// ```
pub fn remove_entry(&mut self, key: &str, language: &str) -> Result<(), Error> {
if let Some(resource) = self.get_mut_by_language(language) {
let initial_len = resource.entries.len();
resource.entries.retain(|entry| entry.id != key);
if resource.entries.len() == initial_len {
Err(Error::InvalidResource(format!(
"Entry '{}' not found in language '{}'",
key, language
)))
} else {
Ok(())
}
} else {
Err(Error::InvalidResource(format!(
"Language '{}' not found",
language
)))
}
}
/// Copies an entry from one language to another.
///
/// This is useful for creating new translations based on existing ones.
///
/// # Arguments
///
/// * `key` - The entry key to copy
/// * `from_language` - The source language
/// * `to_language` - The target language
/// * `update_status` - Whether to update the status to `New` in the target language
///
/// # Returns
///
/// `Ok(())` if the entry was copied successfully, `Err` if not found.
///
/// # Example
///
/// ```rust
/// use langcodec::{Codec, types::{Translation, EntryStatus}};
///
/// let mut codec = Codec::new();
/// // Add source entry first
/// codec.add_entry("welcome", "en", Translation::Singular("Hello".to_string()), None, None)?;
///
/// // Copy English entry to French as a starting point
/// codec.copy_entry("welcome", "en", "fr", true)?;
/// # Ok::<(), langcodec::Error>(())
/// ```
pub fn copy_entry(
&mut self,
key: &str,
from_language: &str,
to_language: &str,
update_status: bool,
) -> Result<(), Error> {
let source_entry = self.find_entry(key, from_language).ok_or_else(|| {
Error::InvalidResource(format!(
"Entry '{}' not found in source language '{}'",
key, from_language
))
})?;
let mut new_entry = source_entry.clone();
if update_status {
new_entry.status = crate::types::EntryStatus::New;
}
// Find or create the target resource
let target_resource = if let Some(resource) = self.get_mut_by_language(to_language) {
resource
} else {
// Create a new resource for the target language
let new_resource = crate::types::Resource {
metadata: crate::types::Metadata {
language: to_language.to_string(),
domain: "".to_string(),
custom: std::collections::HashMap::new(),
},
entries: Vec::new(),
};
self.add_resource(new_resource);
self.get_mut_by_language(to_language).unwrap()
};
// Remove existing entry if it exists
target_resource.entries.retain(|entry| entry.id != key);
target_resource.add_entry(new_entry);
Ok(())
}
/// Gets all languages available in the codec.
///
/// # Returns
///
/// An iterator over all language codes.
///
/// # Example
///
/// ```rust
/// use langcodec::Codec;
///
/// let codec = Codec::new();
/// // ... load resources ...
///
/// for language in codec.languages() {
/// println!("Available language: {}", language);
/// }
/// ```
pub fn languages(&self) -> impl Iterator<Item = &str> {
self.resources.iter().map(|r| r.metadata.language.as_str())
}
/// Gets all unique entry keys across all languages.
///
/// # Returns
///
/// An iterator over all unique entry keys.
///
/// # Example
///
/// ```rust
/// use langcodec::Codec;
///
/// let codec = Codec::new();
/// // ... load resources ...
///
/// for key in codec.all_keys() {
/// println!("Available key: {}", key);
/// }
/// ```
pub fn all_keys(&self) -> impl Iterator<Item = &str> {
use std::collections::HashSet;
let mut keys = HashSet::new();
for resource in &self.resources {
for entry in &resource.entries {
keys.insert(entry.id.as_str());
}
}
keys.into_iter()
}
/// Checks if an entry exists in a specific language.
///
/// # Arguments
///
/// * `key` - The entry key to check
/// * `language` - The language code (e.g., "en", "fr")
///
/// # Returns
///
/// `true` if the entry exists, `false` otherwise.
///
/// # Example
///
/// ```rust
/// use langcodec::Codec;
///
/// let codec = Codec::new();
/// // ... load resources ...
///
/// if codec.has_entry("welcome_message", "en") {
/// println!("English welcome message exists");
/// }
/// ```
pub fn has_entry(&self, key: &str, language: &str) -> bool {
self.find_entry(key, language).is_some()
}
/// Gets the count of entries in a specific language.
///
/// # Arguments
///
/// * `language` - The language code (e.g., "en", "fr")
///
/// # Returns
///
/// The number of entries in the specified language, or 0 if the language doesn't exist.
///
/// # Example
///
/// ```rust
/// use langcodec::Codec;
///
/// let codec = Codec::new();
/// // ... load resources ...
///
/// let count = codec.entry_count("en");
/// println!("English has {} entries", count);
/// ```
pub fn entry_count(&self, language: &str) -> usize {
self.get_by_language(language)
.map(|r| r.entries.len())
.unwrap_or(0)
}
/// Validates the codec for common issues.
///
/// # Returns
///
/// `Ok(())` if validation passes, `Err(Error)` with details if validation fails.
///
/// # Example
///
/// ```rust
/// use langcodec::Codec;
///
/// let mut codec = Codec::new();
/// // ... add resources ...
///
/// if let Err(validation_error) = codec.validate() {
/// eprintln!("Validation failed: {}", validation_error);
/// }
/// ```
pub fn validate(&self) -> Result<(), Error> {
// Check for empty resources
if self.resources.is_empty() {
return Err(Error::InvalidResource("No resources found".to_string()));
}
// Check for duplicate languages
let mut languages = std::collections::HashSet::new();
for resource in &self.resources {
if !languages.insert(&resource.metadata.language) {
return Err(Error::InvalidResource(format!(
"Duplicate language found: {}",
resource.metadata.language
)));
}
}
// Check for empty resources
for resource in &self.resources {
if resource.entries.is_empty() {
return Err(Error::InvalidResource(format!(
"Resource for language '{}' has no entries",
resource.metadata.language
)));
}
}
Ok(())
}
/// Validates plural completeness per CLDR category sets for each locale.
///
/// For each plural entry in each resource, checks that all required plural
/// categories for the language are present. Returns a Validation error with
/// aggregated details if any are missing.
pub fn validate_plurals(&self) -> Result<(), Error> {
use crate::plural_rules::collect_resource_plural_issues;
let mut reports = Vec::new();
for res in &self.resources {
reports.extend(collect_resource_plural_issues(res));
}
if reports.is_empty() {
return Ok(());
}
// Fold into an Error message for the validating API
let mut lines = Vec::new();
for r in reports {
let miss: Vec<String> = r.missing.iter().map(|k| format!("{:?}", k)).collect();
let have: Vec<String> = r.have.iter().map(|k| format!("{:?}", k)).collect();
lines.push(format!(
"lang='{}' key='{}': missing plural categories: [{}] (have: [{}])",
r.language,
r.key,
miss.join(", "),
have.join(", ")
));
}
Err(Error::validation_error(lines.join("\n")))
}
/// Collects non-fatal plural validation reports across all resources.
pub fn collect_plural_issues(&self) -> Vec<crate::plural_rules::PluralValidationReport> {
use crate::plural_rules::collect_resource_plural_issues;
let mut reports = Vec::new();
for res in &self.resources {
reports.extend(collect_resource_plural_issues(res));
}
reports
}
/// Autofix: fill missing plural categories using 'other' and mark entries as NeedsReview.
/// Returns total categories added across all resources.
pub fn autofix_fill_missing_from_other(&mut self) -> usize {
use crate::plural_rules::autofix_fill_missing_from_other_resource;
let mut total = 0usize;
for res in &mut self.resources {
total += autofix_fill_missing_from_other_resource(res);
}
total
}
/// Cleans up resources by removing empty resources and entries.
pub fn clean_up_resources(&mut self) {
self.resources
.retain(|resource| !resource.entries.is_empty());
}
/// Validate placeholder consistency across languages for each key.
///
/// Rules (initial version):
/// - For each key, each language must have the same placeholder signature.
/// - For plural entries, all forms within a language must share the same signature.
/// - iOS vs Android differences like `%@`/`%1$@` vs `%s`/`%1$s` are normalized.
///
/// Example
/// ```rust
/// use langcodec::{Codec, types::{Entry, EntryStatus, Metadata, Resource, Translation}};
/// let mut codec = Codec::new();
/// let en = Resource{
/// metadata: Metadata{ language: "en".into(), domain: String::new(), custom: Default::default() },
/// entries: vec![Entry{ id: "greet".into(), value: Translation::Singular("Hello %1$@".into()), comment: None, status: EntryStatus::Translated, custom: Default::default() }]
/// };
/// let fr = Resource{
/// metadata: Metadata{ language: "fr".into(), domain: String::new(), custom: Default::default() },
/// entries: vec![Entry{ id: "greet".into(), value: Translation::Singular("Bonjour %1$s".into()), comment: None, status: EntryStatus::Translated, custom: Default::default() }]
/// };
/// codec.add_resource(en);
/// codec.add_resource(fr);
/// assert!(codec.validate_placeholders(true).is_ok());
/// ```
pub fn validate_placeholders(&self, strict: bool) -> Result<(), Error> {
use crate::placeholder::signature;
use crate::types::Translation;
use std::collections::HashMap;
// key -> lang -> Vec<signatures per form or single>
let mut map: HashMap<String, HashMap<String, Vec<Vec<String>>>> = HashMap::new();
for res in &self.resources {
for entry in &res.entries {
let sigs: Vec<Vec<String>> = match &entry.value {
Translation::Empty => vec![],
Translation::Singular(v) => vec![signature(v)],
Translation::Plural(p) => p.forms.values().map(|v| signature(v)).collect(),
};
map.entry(entry.id.clone())
.or_default()
.entry(res.metadata.language.clone())
.or_default()
.push(sigs.into_iter().flatten().collect());
}
}
let mut problems = Vec::new();
for (key, langs) in map {
// Per-language: ensure all collected signatures for this entry are identical
let mut per_lang_sig: HashMap<String, Vec<String>> = HashMap::new();
for (lang, sig_lists) in langs {
if let Some(first) = sig_lists.first() {
if sig_lists.iter().any(|s| s != first) {
problems.push(format!(
"Key '{}' in '{}': inconsistent placeholders across forms: {:?}",
key, lang, sig_lists
));
}
per_lang_sig.insert(lang, first.clone());
}
}
// Across languages, pick one baseline and compare
if let Some((base_lang, base_sig)) = per_lang_sig.iter().next() {
for (lang, sig) in &per_lang_sig {
if sig != base_sig {
problems.push(format!(
"Key '{}' mismatch: {} {:?} vs {} {:?}",
key, base_lang, base_sig, lang, sig
));
}
}
}
}
if problems.is_empty() {
return Ok(());
}
if strict {
return Err(Error::validation_error(format!(
"Placeholder issues: {}",
problems.join(" | ")
)));
}
// Non-strict mode: treat as success
Ok(())
}
/// Collect placeholder issues without failing.
/// Returns a list of human-readable messages; empty if none.
///
/// Useful to warn in non-strict mode.
pub fn collect_placeholder_issues(&self) -> Vec<String> {
use crate::placeholder::signature;
use crate::types::Translation;
use std::collections::HashMap;
let mut map: HashMap<String, HashMap<String, Vec<Vec<String>>>> = HashMap::new();
for res in &self.resources {
for entry in &res.entries {
let sigs: Vec<Vec<String>> = match &entry.value {
Translation::Empty => vec![],
Translation::Singular(v) => vec![signature(v)],
Translation::Plural(p) => p.forms.values().map(|v| signature(v)).collect(),
};
map.entry(entry.id.clone())
.or_default()
.entry(res.metadata.language.clone())
.or_default()
.push(sigs.into_iter().flatten().collect());
}
}
let mut problems = Vec::new();
for (key, langs) in map {
let mut per_lang_sig: HashMap<String, Vec<String>> = HashMap::new();
for (lang, sig_lists) in langs {
if let Some(first) = sig_lists.first() {
if sig_lists.iter().any(|s| s != first) {
problems.push(format!(
"Key '{}' in '{}': inconsistent placeholders across forms: {:?}",
key, lang, sig_lists
));
}
per_lang_sig.insert(lang, first.clone());
}
}
if let Some((base_lang, base_sig)) = per_lang_sig.iter().next() {
for (lang, sig) in &per_lang_sig {
if sig != base_sig {
problems.push(format!(
"Key '{}' mismatch: {} {:?} vs {} {:?}",
key, base_lang, base_sig, lang, sig
));
}
}
}
}
problems
}
/// Normalize placeholders in all entries (mutates in place).
/// Converts iOS patterns like `%@`, `%1$@`, `%ld` to canonical forms (%s, %1$s, %d/%u).
///
/// Example
/// ```rust
/// use langcodec::{Codec, types::{Entry, EntryStatus, Metadata, Resource, Translation}};
/// let mut codec = Codec::new();
/// codec.add_resource(Resource{
/// metadata: Metadata{ language: "en".into(), domain: String::new(), custom: Default::default() },
/// entries: vec![Entry{ id: "id".into(), value: Translation::Singular("Hello %@ and %1$@".into()), comment: None, status: EntryStatus::Translated, custom: Default::default() }]
/// });
/// codec.normalize_placeholders_in_place();
/// let v = match &codec.resources[0].entries[0].value { Translation::Singular(v) => v.clone(), _ => unreachable!() };
/// assert!(v.contains("%s") && v.contains("%1$s"));
/// ```
pub fn normalize_placeholders_in_place(&mut self) {
use crate::placeholder::normalize_placeholders;
use crate::types::Translation;
for res in &mut self.resources {
for entry in &mut res.entries {
match &mut entry.value {
Translation::Empty => {
continue;
}
Translation::Singular(v) => {
let nv = normalize_placeholders(v);
*v = nv;
}
Translation::Plural(p) => {
for v in p.forms.values_mut() {
let nv = normalize_placeholders(v);
*v = nv;
}
}
}
}
}
}
/// Merge resources with the same language by the given strategy.
///
/// This method groups resources by language and merges multiple resources
/// that share the same language into a single resource. Resources with
/// unique languages are left unchanged.
///
/// # Arguments
///
/// * `strategy` - The conflict resolution strategy to use when merging
/// entries with the same ID across multiple resources
///
/// # Returns
///
/// The number of merge operations performed. A merge operation occurs
/// when there are 2 or more resources for the same language.
///
/// # Example
///
/// ```rust
/// use langcodec::{Codec, types::ConflictStrategy};
///
/// let mut codec = Codec::new();
/// // ... add resources with same language ...
///
/// let merges_performed = codec.merge_resources(&ConflictStrategy::Last);
/// println!("Merged {} language groups", merges_performed);
/// ```
///
/// # Behavior
///
/// - Resources are grouped by language
/// - Only languages with multiple resources are merged
/// - The merged resource replaces all original resources for that language
/// - Resources with unique languages remain unchanged
/// - Entries are merged according to the specified conflict strategy
pub fn merge_resources(&mut self, strategy: &ConflictStrategy) -> usize {
// Group resources by language
let mut grouped_resources: std::collections::HashMap<String, Vec<Resource>> =
std::collections::HashMap::new();
for resource in &self.resources {
grouped_resources
.entry(resource.metadata.language.clone())
.or_default()
.push(resource.clone());
}
let mut merge_count = 0;
// Merge resources by language
for (_language, resources) in grouped_resources {
if resources.len() > 1 {
match merge_resources(&resources, strategy) {
Ok(merged) => {
// Replace the original resources with the merged resource and remove the original resources
self.resources.retain(|r| r.metadata.language != _language);
self.resources.push(merged);
merge_count += 1;
}
Err(e) => {
// Based on the current implementation, the merge_resources should never return an error
// because we are merging resources with the same language
// so we should panic here
panic!("Unexpected error merging resources: {}", e);
}
}
}
}
merge_count
}
/// Writes a resource to a file with automatic format detection.
///
/// # Arguments
///
/// * `resource` - The resource to write
/// * `output_path` - The output file path
///
/// # Returns
///
/// `Ok(())` on success, `Err(Error)` on failure.
///
/// # Example
///
/// ```rust,no_run
/// use langcodec::{Codec, types::{Resource, Metadata, Entry, Translation, EntryStatus}};
///
/// let resource = Resource {
/// metadata: Metadata {
/// language: "en".to_string(),
/// domain: "domain".to_string(),
/// custom: std::collections::HashMap::new(),
/// },
/// entries: vec![],
/// };
/// Codec::write_resource_to_file(&resource, "output.strings")?;
/// # Ok::<(), langcodec::Error>(())
/// ```
pub fn write_resource_to_file(resource: &Resource, output_path: &str) -> Result<(), Error> {
use crate::formats::{
AndroidStringsFormat, CSVFormat, StringsFormat, TSVFormat, XcstringsFormat,
};
use std::path::Path;
// Infer format from output path
let format_type =
crate::converter::infer_format_from_extension(output_path).ok_or_else(|| {
Error::InvalidResource(format!(
"Cannot infer format from output path: {}",
output_path
))
})?;
match format_type {
crate::formats::FormatType::AndroidStrings(_) => {
AndroidStringsFormat::from(resource.clone())
.write_to(Path::new(output_path))
.map_err(|e| {
Error::conversion_error(
format!("Error writing AndroidStrings output: {}", e),
None,
)
})
}
crate::formats::FormatType::Strings(_) => StringsFormat::try_from(resource.clone())
.and_then(|f| f.write_to(Path::new(output_path)))
.map_err(|e| {
Error::conversion_error(format!("Error writing Strings output: {}", e), None)
}),
crate::formats::FormatType::Xcstrings => {
XcstringsFormat::try_from(vec![resource.clone()])
.and_then(|f| f.write_to(Path::new(output_path)))
.map_err(|e| {
Error::conversion_error(
format!("Error writing Xcstrings output: {}", e),
None,
)
})
}
crate::formats::FormatType::Xliff(_) => Err(Error::InvalidResource(
"XLIFF output requires both source and target resources; use convert_resources_to_format instead of write_resource_to_file".to_string(),
)),
crate::formats::FormatType::CSV => CSVFormat::try_from(vec![resource.clone()])
.and_then(|f| f.write_to(Path::new(output_path)))
.map_err(|e| {
Error::conversion_error(format!("Error writing CSV output: {}", e), None)
}),
crate::formats::FormatType::TSV => TSVFormat::try_from(vec![resource.clone()])
.and_then(|f| f.write_to(Path::new(output_path)))
.map_err(|e| {
Error::conversion_error(format!("Error writing TSV output: {}", e), None)
}),
}
}
/// Reads a resource file given its path and explicit format type.
///
/// # Parameters
/// - `path`: Path to the resource file.
/// - `format_type`: The format type of the resource file.
///
/// # Returns
///
/// `Ok(())` if the file was successfully read and resources loaded,
/// or an `Error` otherwise.
pub fn read_file_by_type<P: AsRef<Path>>(
&mut self,
path: P,
format_type: FormatType,
) -> Result<(), Error> {
self.read_file_by_type_with_options(path, format_type, &ReadOptions::default())
}
/// Reads a resource file given its path and explicit format type with read options.
pub fn read_file_by_type_with_options<P: AsRef<Path>>(
&mut self,
path: P,
format_type: FormatType,
options: &ReadOptions,
) -> Result<(), Error> {
let inferred_language = crate::converter::infer_language_from_path(&path, &format_type)?;
let format_language = match &format_type {
FormatType::Strings(lang_opt) | FormatType::AndroidStrings(lang_opt) => {
lang_opt.clone()
}
FormatType::Xliff(lang_opt) => lang_opt.clone(),
_ => None,
};
let language = options
.language_hint
.clone()
.or(inferred_language)
.or(format_language);
let requires_language = matches!(
&format_type,
FormatType::Strings(_) | FormatType::AndroidStrings(_)
);
let format_name = format_type.to_string();
let source_path = path.as_ref().to_string_lossy().to_string();
if options.strict && requires_language && language.is_none() {
return Err(Error::missing_language(
source_path.clone(),
format_name.clone(),
));
}
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)?
}
};
for new_resource in &mut new_resources {
if requires_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_name.clone());
if options.attach_provenance {
set_resource_provenance(
new_resource,
&ProvenanceRecord {
source_path: Some(source_path.clone()),
source_format: Some(format_name.clone()),
source_language: language.clone(),
..ProvenanceRecord::default()
},
);
}
}
self.resources.append(&mut new_resources);
Ok(())
}
/// Reads a resource file by inferring its format from the file extension.
/// Optionally infers language from the path if not provided.
///
/// # Parameters
/// - `path`: Path to the resource file.
/// - `lang`: Optional language code to use.
///
/// # Returns
///
/// `Ok(())` if the file was successfully read,
/// or an `Error` if the format is unsupported or reading fails.
pub fn read_file_by_extension<P: AsRef<Path>>(
&mut self,
path: P,
lang: Option<String>,
) -> Result<(), Error> {
self.read_file_by_extension_with_options(path, &ReadOptions::new().with_language_hint(lang))
}
/// Reads a resource file by inferring format from extension with read options.
pub fn read_file_by_extension_with_options<P: AsRef<Path>>(
&mut self,
path: P,
options: &ReadOptions,
) -> Result<(), Error> {
let format_type = match path.as_ref().extension().and_then(|s| s.to_str()) {
Some("xml") => FormatType::AndroidStrings(options.language_hint.clone()),
Some("strings") => FormatType::Strings(options.language_hint.clone()),
Some("xcstrings") => FormatType::Xcstrings,
Some("xliff") => FormatType::Xliff(None),
Some("csv") => FormatType::CSV,
Some("tsv") => FormatType::TSV,
extension => {
return Err(Error::UnsupportedFormat(format!(
"Unsupported file extension: {:?}.",
extension
)));
}
};
self.read_file_by_type_with_options(path, format_type, options)?;
Ok(())
}
/// Writes all managed resources back to their respective files,
/// grouped by domain.
///
/// # Returns
///
/// `Ok(())` if all writes succeed, or an `Error` otherwise.
pub fn write_to_file(&self) -> Result<(), Error> {
// Group resources by the domain in a HashMap
let mut grouped_resources: std::collections::HashMap<String, Vec<Resource>> =
std::collections::HashMap::new();
for resource in &*self.resources {
let domain = resource.metadata.domain.clone();
grouped_resources
.entry(domain)
.or_default()
.push(resource.clone());
}
// Iterate the map and write each resource to its respective file
for (domain, resources) in grouped_resources {
crate::converter::write_resources_to_file(&resources, &domain)?;
}
Ok(())
}
/// Caches the current resources to a JSON file.
///
/// # Parameters
/// - `path`: Destination file path for the cache.
///
/// # Returns
///
/// `Ok(())` if caching succeeds, or an `Error` if file I/O or serialization fails.
pub fn cache_to_file<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> {
let path = path.as_ref();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(Error::Io)?;
}
let mut writer = std::fs::File::create(path).map_err(Error::Io)?;
serde_json::to_writer(&mut writer, &*self.resources).map_err(Error::Parse)?;
Ok(())
}
/// Loads resources from a JSON cache file.
///
/// # Parameters
/// - `path`: Path to the JSON file containing cached resources.
///
/// # Returns
///
/// `Ok(Codec)` with loaded resources, or an `Error` if loading or deserialization fails.
pub fn load_from_file<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
let mut reader = std::fs::File::open(path).map_err(Error::Io)?;
let resources: Vec<Resource> =
serde_json::from_reader(&mut reader).map_err(Error::Parse)?;
Ok(Codec { resources })
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::{Entry, EntryStatus, Metadata, Translation};
use std::collections::HashMap;
#[test]
fn test_builder_pattern() {
// Test creating an empty codec
let codec = Codec::builder().build();
assert_eq!(codec.resources.len(), 0);
// Test adding resources directly
let resource1 = Resource {
metadata: Metadata {
language: "en".to_string(),
domain: "test".to_string(),
custom: std::collections::HashMap::new(),
},
entries: vec![Entry {
id: "hello".to_string(),
value: Translation::Singular("Hello".to_string()),
comment: None,
status: EntryStatus::Translated,
custom: std::collections::HashMap::new(),
}],
};
let resource2 = Resource {
metadata: Metadata {
language: "fr".to_string(),
domain: "test".to_string(),
custom: std::collections::HashMap::new(),
},
entries: vec![Entry {
id: "hello".to_string(),
value: Translation::Singular("Bonjour".to_string()),
comment: None,
status: EntryStatus::Translated,
custom: std::collections::HashMap::new(),
}],
};
let codec = Codec::builder()
.add_resource(resource1.clone())
.add_resource(resource2.clone())
.build();
assert_eq!(codec.resources.len(), 2);
assert_eq!(codec.resources[0].metadata.language, "en");
assert_eq!(codec.resources[1].metadata.language, "fr");
}
#[test]
fn test_builder_validation() {
// Test validation with empty language
let resource_without_language = Resource {
metadata: Metadata {
language: "".to_string(),
domain: "test".to_string(),
custom: std::collections::HashMap::new(),
},
entries: vec![],
};
let result = Codec::builder()
.add_resource(resource_without_language)
.build_and_validate();
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), Error::Validation(_)));
// Test validation with duplicate languages
let resource1 = Resource {
metadata: Metadata {
language: "en".to_string(),
domain: "test".to_string(),
custom: std::collections::HashMap::new(),
},
entries: vec![],
};
let resource2 = Resource {
metadata: Metadata {
language: "en".to_string(), // Duplicate language
domain: "test".to_string(),
custom: std::collections::HashMap::new(),
},
entries: vec![],
};
let result = Codec::builder()
.add_resource(resource1)
.add_resource(resource2)
.build_and_validate();
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), Error::Validation(_)));
}
#[test]
fn test_builder_add_resources() {
let resources = vec![
Resource {
metadata: Metadata {
language: "en".to_string(),
domain: "test".to_string(),
custom: std::collections::HashMap::new(),
},
entries: vec![],
},
Resource {
metadata: Metadata {
language: "fr".to_string(),
domain: "test".to_string(),
custom: std::collections::HashMap::new(),
},
entries: vec![],
},
];
let codec = Codec::builder().add_resources(resources).build();
assert_eq!(codec.resources.len(), 2);
assert_eq!(codec.resources[0].metadata.language, "en");
assert_eq!(codec.resources[1].metadata.language, "fr");
}
#[test]
fn test_modification_methods() {
use crate::types::{EntryStatus, Translation};
// Create a codec with some test data
let mut codec = Codec::new();
// Add resources
let resource1 = Resource {
metadata: Metadata {
language: "en".to_string(),
domain: "test".to_string(),
custom: std::collections::HashMap::new(),
},
entries: vec![Entry {
id: "welcome".to_string(),
value: Translation::Singular("Hello".to_string()),
comment: None,
status: EntryStatus::Translated,
custom: std::collections::HashMap::new(),
}],
};
let resource2 = Resource {
metadata: Metadata {
language: "fr".to_string(),
domain: "test".to_string(),
custom: std::collections::HashMap::new(),
},
entries: vec![Entry {
id: "welcome".to_string(),
value: Translation::Singular("Bonjour".to_string()),
comment: None,
status: EntryStatus::Translated,
custom: std::collections::HashMap::new(),
}],
};
codec.add_resource(resource1);
codec.add_resource(resource2);
// Test find_entries
let entries = codec.find_entries("welcome");
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].0.metadata.language, "en");
assert_eq!(entries[1].0.metadata.language, "fr");
// Test find_entry
let entry = codec.find_entry("welcome", "en");
assert!(entry.is_some());
assert_eq!(entry.unwrap().id, "welcome");
// Test find_entry_mut and update
if let Some(entry) = codec.find_entry_mut("welcome", "en") {
entry.value = Translation::Singular("Hello, World!".to_string());
entry.status = EntryStatus::NeedsReview;
}
// Verify the update
let updated_entry = codec.find_entry("welcome", "en").unwrap();
assert_eq!(updated_entry.value.to_string(), "Hello, World!");
assert_eq!(updated_entry.status, EntryStatus::NeedsReview);
// Test update_translation
codec
.update_translation(
"welcome",
"fr",
Translation::Singular("Bonjour, le monde!".to_string()),
Some(EntryStatus::NeedsReview),
)
.unwrap();
// Test add_entry
codec
.add_entry(
"new_key",
"en",
Translation::Singular("New message".to_string()),
Some("A new message".to_string()),
Some(EntryStatus::New),
)
.unwrap();
assert!(codec.has_entry("new_key", "en"));
assert_eq!(codec.entry_count("en"), 2);
// Test remove_entry
codec.remove_entry("new_key", "en").unwrap();
assert!(!codec.has_entry("new_key", "en"));
assert_eq!(codec.entry_count("en"), 1);
// Test copy_entry
codec.copy_entry("welcome", "en", "fr", true).unwrap();
let copied_entry = codec.find_entry("welcome", "fr").unwrap();
assert_eq!(copied_entry.status, EntryStatus::New);
// Test languages
let languages: Vec<_> = codec.languages().collect();
assert_eq!(languages.len(), 2);
assert!(languages.contains(&"en"));
assert!(languages.contains(&"fr"));
// Test all_keys
let keys: Vec<_> = codec.all_keys().collect();
assert_eq!(keys.len(), 1);
assert!(keys.contains(&"welcome"));
}
#[test]
fn test_validation() {
let mut codec = Codec::new();
// Test validation with empty language
let resource_without_language = Resource {
metadata: Metadata {
language: "".to_string(),
domain: "test".to_string(),
custom: std::collections::HashMap::new(),
},
entries: vec![],
};
codec.add_resource(resource_without_language);
assert!(codec.validate().is_err());
// Test validation with duplicate languages
let mut codec = Codec::new();
let resource1 = Resource {
metadata: Metadata {
language: "en".to_string(),
domain: "test".to_string(),
custom: std::collections::HashMap::new(),
},
entries: vec![],
};
let resource2 = Resource {
metadata: Metadata {
language: "en".to_string(), // Duplicate language
domain: "test".to_string(),
custom: std::collections::HashMap::new(),
},
entries: vec![],
};
codec.add_resource(resource1);
codec.add_resource(resource2);
assert!(codec.validate().is_err());
// Test validation with missing translations
let mut codec = Codec::new();
let resource1 = Resource {
metadata: Metadata {
language: "en".to_string(),
domain: "test".to_string(),
custom: std::collections::HashMap::new(),
},
entries: vec![Entry {
id: "welcome".to_string(),
value: Translation::Singular("Hello".to_string()),
comment: None,
status: EntryStatus::Translated,
custom: std::collections::HashMap::new(),
}],
};
let resource2 = Resource {
metadata: Metadata {
language: "fr".to_string(),
domain: "test".to_string(),
custom: std::collections::HashMap::new(),
},
entries: vec![], // Missing welcome entry
};
codec.add_resource(resource1);
codec.add_resource(resource2);
assert!(codec.validate().is_err());
}
#[test]
fn test_convert_csv_to_xcstrings() {
// Test CSV to XCStrings conversion
let temp_dir = tempfile::tempdir().unwrap();
let input_file = temp_dir.path().join("test.csv");
let output_file = temp_dir.path().join("output.xcstrings");
let csv_content =
"key,en,fr,de\nhello,Hello,Bonjour,Hallo\nbye,Goodbye,Au revoir,Auf Wiedersehen\n";
std::fs::write(&input_file, csv_content).unwrap();
// First, let's see what the CSV parsing produces
let csv_format = CSVFormat::read_from(&input_file).unwrap();
let resources = Vec::<Resource>::try_from(csv_format).unwrap();
println!("CSV parsed to {} resources:", resources.len());
for (i, resource) in resources.iter().enumerate() {
println!(
" Resource {}: language={}, entries={}",
i,
resource.metadata.language,
resource.entries.len()
);
for entry in &resource.entries {
println!(" Entry: id={}, value={:?}", entry.id, entry.value);
}
}
let result = crate::converter::convert(
&input_file,
FormatType::CSV,
&output_file,
FormatType::Xcstrings,
);
match result {
Ok(()) => println!("✅ CSV to XCStrings conversion succeeded"),
Err(e) => println!("❌ CSV to XCStrings conversion failed: {}", e),
}
// Check the output file content
if output_file.exists() {
let content = std::fs::read_to_string(&output_file).unwrap();
println!("Output file content: {}", content);
}
// Clean up
let _ = std::fs::remove_file(input_file);
let _ = std::fs::remove_file(output_file);
}
#[test]
fn test_merge_resources_method() {
use crate::types::{ConflictStrategy, Entry, EntryStatus, Metadata, Translation};
let mut codec = Codec::new();
// Create multiple resources for the same language (English)
let resource1 = Resource {
metadata: Metadata {
language: "en".to_string(),
domain: "domain1".to_string(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "hello".to_string(),
value: Translation::Singular("Hello".to_string()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
};
let resource2 = Resource {
metadata: Metadata {
language: "en".to_string(),
domain: "domain2".to_string(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "goodbye".to_string(),
value: Translation::Singular("Goodbye".to_string()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
};
let resource3 = Resource {
metadata: Metadata {
language: "en".to_string(),
domain: "domain3".to_string(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "hello".to_string(), // Conflict with resource1
value: Translation::Singular("Hi".to_string()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
};
// Add resources to codec
codec.add_resource(resource1);
codec.add_resource(resource2);
codec.add_resource(resource3);
// Test merging with Last strategy
let merges_performed = codec.merge_resources(&ConflictStrategy::Last);
assert_eq!(merges_performed, 1); // Should merge 1 language group
assert_eq!(codec.resources.len(), 1); // Should have 1 merged resource
let merged_resource = &codec.resources[0];
assert_eq!(merged_resource.metadata.language, "en");
assert_eq!(merged_resource.entries.len(), 2); // hello + goodbye
// Check that the last entry for "hello" was kept (from resource3)
let hello_entry = merged_resource
.entries
.iter()
.find(|e| e.id == "hello")
.unwrap();
assert_eq!(hello_entry.value.plain_translation_string(), "Hi");
}
#[test]
fn test_merge_resources_method_multiple_languages() {
use crate::types::{ConflictStrategy, Entry, EntryStatus, Metadata, Translation};
let mut codec = Codec::new();
// Create resources for English (multiple)
let en_resource1 = Resource {
metadata: Metadata {
language: "en".to_string(),
domain: "domain1".to_string(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "hello".to_string(),
value: Translation::Singular("Hello".to_string()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
};
let en_resource2 = Resource {
metadata: Metadata {
language: "en".to_string(),
domain: "domain2".to_string(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "goodbye".to_string(),
value: Translation::Singular("Goodbye".to_string()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
};
// Create resource for French (single)
let fr_resource = Resource {
metadata: Metadata {
language: "fr".to_string(),
domain: "domain1".to_string(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "bonjour".to_string(),
value: Translation::Singular("Bonjour".to_string()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
};
// Add resources to codec
codec.add_resource(en_resource1);
codec.add_resource(en_resource2);
codec.add_resource(fr_resource);
// Test merging
let merges_performed = codec.merge_resources(&ConflictStrategy::First);
assert_eq!(merges_performed, 1); // Should merge 1 language group (English)
assert_eq!(codec.resources.len(), 2); // Should have 2 resources (merged English + French)
// Check English resource was merged
let en_resource = codec.get_by_language("en").unwrap();
assert_eq!(en_resource.entries.len(), 2);
// Check French resource was unchanged
let fr_resource = codec.get_by_language("fr").unwrap();
assert_eq!(fr_resource.entries.len(), 1);
assert_eq!(fr_resource.entries[0].id, "bonjour");
}
#[test]
fn test_merge_resources_method_no_merges() {
use crate::types::{ConflictStrategy, Entry, EntryStatus, Metadata, Translation};
let mut codec = Codec::new();
// Create resources for different languages (no conflicts)
let en_resource = Resource {
metadata: Metadata {
language: "en".to_string(),
domain: "domain1".to_string(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "hello".to_string(),
value: Translation::Singular("Hello".to_string()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
};
let fr_resource = Resource {
metadata: Metadata {
language: "fr".to_string(),
domain: "domain1".to_string(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "bonjour".to_string(),
value: Translation::Singular("Bonjour".to_string()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
};
// Add resources to codec
codec.add_resource(en_resource);
codec.add_resource(fr_resource);
// Test merging - should perform no merges
let merges_performed = codec.merge_resources(&ConflictStrategy::Last);
assert_eq!(merges_performed, 0); // Should merge 0 language groups
assert_eq!(codec.resources.len(), 2); // Should still have 2 resources
// Check resources are unchanged
assert!(codec.get_by_language("en").is_some());
assert!(codec.get_by_language("fr").is_some());
}
#[test]
fn test_merge_resources_method_empty_codec() {
let mut codec = Codec::new();
// Test merging empty codec
let merges_performed = codec.merge_resources(&ConflictStrategy::Last);
assert_eq!(merges_performed, 0);
assert_eq!(codec.resources.len(), 0);
}
#[test]
fn test_extend_from_and_from_codecs() {
let mut codec1 = Codec::new();
let mut codec2 = Codec::new();
let en_resource = Resource {
metadata: Metadata {
language: "en".to_string(),
domain: "d1".to_string(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "hello".to_string(),
value: Translation::Singular("Hello".to_string()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
};
let fr_resource = Resource {
metadata: Metadata {
language: "fr".to_string(),
domain: "d2".to_string(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "bonjour".to_string(),
value: Translation::Singular("Bonjour".to_string()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
};
codec1.add_resource(en_resource);
codec2.add_resource(fr_resource);
// extend_from
let mut combined = codec1;
combined.extend_from(codec2);
assert_eq!(combined.resources.len(), 2);
// from_codecs
let c = Codec::from_codecs(vec![combined.clone()]);
assert_eq!(c.resources.len(), 2);
}
#[test]
fn test_merge_codecs_across_instances() {
use crate::types::ConflictStrategy;
// Two codecs, both English with different entries -> should merge to one English with two entries
let mut c1 = Codec::new();
let mut c2 = Codec::new();
c1.add_resource(Resource {
metadata: Metadata {
language: "en".to_string(),
domain: "d1".to_string(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "hello".to_string(),
value: Translation::Singular("Hello".to_string()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
});
c2.add_resource(Resource {
metadata: Metadata {
language: "en".to_string(),
domain: "d2".to_string(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "goodbye".to_string(),
value: Translation::Singular("Goodbye".to_string()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
});
let merged = Codec::merge_codecs(vec![c1, c2], &ConflictStrategy::Last);
assert_eq!(merged.resources.len(), 1);
assert_eq!(merged.resources[0].metadata.language, "en");
assert_eq!(merged.resources[0].entries.len(), 2);
}
#[test]
fn test_validate_placeholders_across_languages() {
let mut codec = Codec::new();
// English with %1$@, French with %1$s should match after normalization
codec.add_resource(Resource {
metadata: Metadata {
language: "en".into(),
domain: "d".into(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "greet".into(),
value: Translation::Singular("Hello %1$@".into()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
});
codec.add_resource(Resource {
metadata: Metadata {
language: "fr".into(),
domain: "d".into(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "greet".into(),
value: Translation::Singular("Bonjour %1$s".into()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
});
assert!(codec.validate_placeholders(true).is_ok());
}
#[test]
fn test_validate_placeholders_mismatch() {
let mut codec = Codec::new();
codec.add_resource(Resource {
metadata: Metadata {
language: "en".into(),
domain: "d".into(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "count".into(),
value: Translation::Singular("%d files".into()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
});
codec.add_resource(Resource {
metadata: Metadata {
language: "fr".into(),
domain: "d".into(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "count".into(),
value: Translation::Singular("%s fichiers".into()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
});
assert!(codec.validate_placeholders(true).is_err());
}
#[test]
fn test_collect_placeholder_issues_non_strict_ok() {
let mut codec = Codec::new();
codec.add_resource(Resource {
metadata: Metadata {
language: "en".into(),
domain: "d".into(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "count".into(),
value: Translation::Singular("%d files".into()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
});
codec.add_resource(Resource {
metadata: Metadata {
language: "fr".into(),
domain: "d".into(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "count".into(),
value: Translation::Singular("%s fichiers".into()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
});
// Non-strict should be Ok but issues present
assert!(codec.validate_placeholders(false).is_ok());
let issues = codec.collect_placeholder_issues();
assert!(!issues.is_empty());
}
#[test]
fn test_normalize_placeholders_in_place() {
let mut codec = Codec::new();
codec.add_resource(Resource {
metadata: Metadata {
language: "en".into(),
domain: "d".into(),
custom: HashMap::new(),
},
entries: vec![Entry {
id: "g".into(),
value: Translation::Singular("Hello %@ and %1$@".into()),
comment: None,
status: EntryStatus::Translated,
custom: HashMap::new(),
}],
});
codec.normalize_placeholders_in_place();
let v = match &codec.resources[0].entries[0].value {
Translation::Singular(v) => v.clone(),
_ => String::new(),
};
assert!(v.contains("%s"));
assert!(v.contains("%1$s"));
}
#[test]
fn test_read_file_by_type_with_strict_requires_language() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("Localizable.strings");
std::fs::write(&input, "\"hello\" = \"Hello\";").unwrap();
let mut codec = Codec::new();
let err = codec
.read_file_by_type_with_options(
&input,
FormatType::Strings(None),
&ReadOptions::new().with_strict(true),
)
.unwrap_err();
assert_eq!(err.error_code(), crate::ErrorCode::MissingLanguage);
}
#[test]
fn test_read_file_with_provenance() {
let temp = tempfile::tempdir().unwrap();
let lproj = temp.path().join("en.lproj");
std::fs::create_dir_all(&lproj).unwrap();
let input = lproj.join("Localizable.strings");
std::fs::write(&input, "\"hello\" = \"Hello\";").unwrap();
let mut codec = Codec::new();
codec
.read_file_by_extension_with_options(&input, &ReadOptions::new().with_provenance(true))
.unwrap();
let provenance = crate::resource_provenance(codec.resources.first().unwrap()).unwrap();
assert_eq!(
provenance.source_path,
Some(input.to_string_lossy().to_string())
);
assert_eq!(provenance.source_format, Some("strings".to_string()));
}
}