translocate 0.8.0

translocate is a high performance converter that takes CSV translation files and outputs corresponding JSON translation files.
Documentation
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
use crate::translations::{FormatTranslation, LangData, Translations};
use crate::{get_file_location, Config};
use csv::{Reader, StringRecord};
use serde_json::{to_string_pretty, Map, Value};
use std::collections::HashMap;
use std::fs::{create_dir_all, File};
use std::io::Write;
use yansi::Paint;

const DUPE_KEY_NOTICE: &str = "translation keys overwritten during conversion.\n";

/// Generate JSON files from CSV using structured deserialization
///
/// * `reader` - a configured CSV reader
/// * `headings` - heading row for the CSV file
/// * `rows` - number of rows that are in the CSV file
/// * `config` - parsed command line configuration
pub fn generate_json(
    reader: &mut Reader<File>,
    headings: &StringRecord,
    rows: usize,
    config: &Config,
) -> Result<(), std::io::Error> {
    // HashMap::with_capacity_and_hasher(capacity, hasher) can be used instead, with hasher
    // that is faster https://crates.io/keywords/hasher
    let mut dictionary: HashMap<&str, Map<String, Value>> = HashMap::with_capacity(rows);
    let mut times_overwritten = 0;

    for (idx, item) in reader.deserialize().enumerate() {
        let record: Translations = item?;
        let mut overwrote_data = false;
        let ignored_headings = if let Some(list) = &config.ignored_headings {
            list.clone()
        } else {
            vec![""]
        };

        // Loop in a loop? Incredibly inefficient? Who cares!? Optimize when it matters.
        for heading in headings.iter() {
            let heading = heading.trim();
            // Only process for language headings
            if heading != "id" && !ignored_headings.contains(&heading) && !heading.is_empty() {
                let kv = record.format_lang(heading);
                if let Some(lang_map) = dictionary.get_mut(heading) {
                    // No matter what the parser thinks, we want everything treated as a string
                    let value = match kv.1 {
                        LangData::Float(v) => format!("{v}"),
                        LangData::Integer(v) => format!("{v}"),
                        LangData::String(v) => v.to_owned(),
                    };
                    // if the new value is empty and the old value is not empty, skip replacement.
                    if let Some(old_val) = lang_map.get(kv.0) {
                        if value.is_empty() && old_val != "" {
                            continue;
                        };
                    }

                    let old_val = lang_map.insert(kv.0.into(), value.into());
                    if let Some(_val) = old_val {
                        if !overwrote_data {
                            println!(
                                "{} key \"{}\" overwritten by record {} (line {}).",
                                "Warning:".on_yellow().italic(),
                                kv.0,
                                idx + 1,
                                idx + 1
                            );
                            overwrote_data = true;
                            times_overwritten += 1;
                        }
                    };
                } else {
                    dictionary.insert(heading, Map::with_capacity(rows));
                    // No matter what the parser thinks, we want everything treated as a string
                    let value = match kv.1 {
                        LangData::Float(v) => format!("{v}"),
                        LangData::Integer(v) => format!("{v}"),
                        LangData::String(v) => v.to_owned(),
                    };

                    dictionary
                        .get_mut(heading)
                        .expect("Unexpected error after creating map")
                        .insert(kv.0.into(), value.into());
                }
            }
        }
    }

    if times_overwritten > 0 {
        println!("\n{times_overwritten} {DUPE_KEY_NOTICE}")
    }

    for lang in dictionary.keys() {
        let mut filename = get_file_location(config.output_dir)?;

        if let Some(outfile) = config.output_filename {
            filename.push(lang);
            create_dir_all(&filename)?;
            filename.push(format!("{outfile}.json"));
        } else {
            filename.push(format!("{lang}.json"));
        }

        if let Some(json) = dictionary.get(lang) {
            writeln!(
                File::create(&filename)?,
                "{}",
                to_string_pretty(json).expect("Error writing {lang}.json.")
            )?;
        }
        println!(
            "{} written to {}.",
            filename.file_name().unwrap().to_string_lossy(),
            filename.parent().unwrap().to_string_lossy()
        );
    }

    Ok(())
}

/// Generate JSON files from CSV using StringRecord
///
/// * `reader` - a configured CSV reader
/// * `headings` - heading row for the CSV file
/// * `rows` - number of rows that are in the CSV file
/// * `config` - parsed command line configuration
pub fn generate_json_fast(
    reader: &mut Reader<File>,
    headings: &StringRecord,
    rows: usize,
    config: &Config,
) -> Result<(), std::io::Error> {
    // HashMap::with_capacity_and_hasher(capacity, hasher) can be used instead, with hasher
    // that is faster https://crates.io/keywords/hasher
    let mut dictionary: HashMap<&str, Map<String, Value>> = HashMap::with_capacity(rows);
    let mut times_overwritten = 0;

    let mut record = StringRecord::new();
    let mut idx = 0;
    let ignored_headings = if let Some(list) = &config.ignored_headings {
        list.clone()
    } else {
        vec![""]
    };

    while reader.read_record(&mut record)? {
        let mut overwrote_data = false;
        idx += 1;

        // Loop in a loop? Incredibly inefficient? Who cares!? Optimize when it matters.
        for (column_idx, heading) in headings.iter().enumerate() {
            let heading = heading.trim();
            // Only process for language headings
            if column_idx != 0 && !ignored_headings.contains(&heading) && !heading.is_empty() {
                let value = match &record.get(column_idx) {
                    Some(head) => head,
                    None => "",
                };

                // Check if there's an existing translation key record in the language map
                // and replace it.
                if let Some(lang_map) = dictionary.get_mut(heading) {
                    // But if the new value is empty and the old value is not empty, skip replacement.
                    if let Some(old_val) = lang_map.get(&record[0]) {
                        if value.is_empty() && old_val != "" {
                            continue;
                        };
                    }

                    let old_val = lang_map.insert(record[0].into(), value.into());
                    if let Some(_val) = old_val {
                        if !overwrote_data {
                            println!(
                                "{} key \"{}\" overwritten by record {} (line {}).",
                                "Warning:".on_yellow().italic(),
                                &record[0],
                                idx,
                                idx
                            );
                            overwrote_data = true;
                            times_overwritten += 1;
                        }
                    };
                } else {
                    dictionary.insert(heading, Map::with_capacity(rows));
                    // No matter what the parser thinks, we want everything treated as a string
                    let value = match &record.get(column_idx) {
                        Some(head) => head,
                        None => "",
                    };

                    dictionary
                        .get_mut(heading)
                        .expect("Unexpected error after creating map")
                        .insert(record[0].into(), value.into());
                }
            }
        }
    }

    if times_overwritten > 0 {
        println!("\n{times_overwritten} {DUPE_KEY_NOTICE}")
    }

    for lang in dictionary.keys() {
        let mut filename = get_file_location(config.output_dir)?;

        if let Some(outfile) = config.output_filename {
            filename.push(lang);
            create_dir_all(&filename)?;
            filename.push(format!("{outfile}.json"));
        } else {
            filename.push(format!("{lang}.json"));
        }

        if let Some(json) = dictionary.get(lang) {
            writeln!(
                File::create(&filename)?,
                "{}",
                to_string_pretty(json).expect("Error writing {lang}.json.")
            )?;
        }
        println!(
            "{} written to {}.",
            filename.file_name().unwrap().to_string_lossy(),
            filename.parent().unwrap().to_string_lossy()
        );
    }

    Ok(())
}

#[cfg(test)]
mod generator_tests {
    use super::generate_json_fast;
    use crate::{get_file_location, get_file_reader, Config};
    use csv::{Reader, StringRecord, Terminator, Trim};
    use pretty_assertions::assert_eq;
    use std::fs::{self, File};
    use std::io::Write;
    use std::path::Path;

    const CONFIG: Config = Config {
        delimiter: b',',
        escape_char: b'"',
        ignored_headings: None,
        flexible: true,
        output_dir: "",
        output_filename: None,
        terminator_char: Terminator::CRLF,
        trim_whitespace: Trim::Fields,
    };

    const CSV_ALL_LANG: &str = "\
id,da_DK,de_DE,en_US,es_ES,fr_FR,it_IT,LangDomain,nl_NL,pt_BR,pt_PT,sv_SE,
new.translation,ny oversættelse,neue Übersetzung,new translation,nueva traducción,nouvelle traduction,nuova traduzione,,nieuwe vertaling,nova tradução,nova tradução,ny översättning,
";

    const CSV_ROW_A: &str = "\
id,da_DK_a,
new.translation,,
";

    const CSV_ROW_0: &str = "\
id,da_DK_0,
old.translation,,
new.translation,,
";

    const CSV_ROW_1: &str = "\
id,da_DK_1,
new.translation,ny oversættelse,
";

    const CSV_ROW_2: &str = "\
id,da_DK_2,
new.translation,ny oversættelse,
new.translation,,
";

    const CSV_ROW_3: &str = "\
id,da_DK_3,
new.translation,ny oversættelse,
new.translation,,
new.translation,nyoversættelse,
";

    const CSV_ROW_4: &str = "\
id,da_DK_4,
new.translation,,
new.translation,ny oversættelse,
";

    const SSV_ROW_1: &str = "\
id;da_DK_s;
new.translation;ny oversættelse;
";

    const TSV_ROW_1: &str = "\
id\tda_DK_t\t
new.translation\tny oversættelse\t
";

    const DA_JSON_0: &str = "{\n  \"new.translation\": \"\",\n  \"old.translation\": \"\"\n}\n";
    const DA_JSON_1: &str = "{\n  \"new.translation\": \"ny oversættelse\"\n}\n";
    const DA_JSON_2: &str = "{\n  \"new.translation\": \"nyoversættelse\"\n}\n";

    fn generate_csv_reader(
        input_filename: &str,
        input_data: &str,
        config: &Config,
    ) -> (Reader<File>, StringRecord, usize) {
        File::options()
            .write(true)
            .create(true)
            .open(input_filename)
            .unwrap()
            .write_all(input_data.as_bytes())
            .unwrap();
        let mut reader = get_file_reader(input_filename, config).unwrap();
        let file = get_file_location(input_filename).unwrap();
        let mut reader_count = Reader::from_path(file).unwrap();

        let headings = reader.headers().unwrap().clone();
        let rows = reader_count.byte_records().count();

        (reader, headings, rows)
    }

    #[test]
    fn it_writes_all_columns_except_langdomain_to_a_file() {
        let test_file_path = "test_file0.csv";
        let illegal_file = "LangDomain.json";
        let lang_file_list = [
            "da_DK.json",
            "de_DE.json",
            "en_US.json",
            "es_ES.json",
            "fr_FR.json",
            "it_IT.json",
            "nl_NL.json",
            "pt_BR.json",
            "pt_PT.json",
            "sv_SE.json",
        ];
        let translations = [
            "ny oversættelse",
            "neue Übersetzung",
            "new translation",
            "nueva traducción",
            "nouvelle traduction",
            "nuova traduzione",
            "nieuwe vertaling",
            "nova tradução",
            "nova tradução",
            "ny översättning",
        ];
        let config = &Config {
            ignored_headings: Some(vec!["LangDomain"]),
            ..CONFIG
        };
        let mut test_conf = generate_csv_reader(test_file_path, CSV_ALL_LANG, config);

        generate_json_fast(&mut test_conf.0, &test_conf.1, test_conf.2, config).unwrap();

        for (idx, file) in lang_file_list.iter().enumerate() {
            let trans = fs::read_to_string(file).unwrap();
            let trans = trans.trim();
            fs::remove_file(file).unwrap();

            assert!(File::open(illegal_file).is_err());
            assert_eq!(
                trans,
                format!("{{\n  \"new.translation\": \"{}\"\n}}", translations[idx])
            );
        }
        fs::remove_file(test_file_path).unwrap();
    }

    #[test]
    fn it_creates_a_new_json_file_for_the_given_language_from_tsv() {
        let test_file_path = "test_file_1.tsv";
        let lang_file_path = "da_DK_t.json";
        let config = &Config {
            delimiter: b'\t',
            ..CONFIG
        };
        let mut test_conf = generate_csv_reader(test_file_path, TSV_ROW_1, config);

        generate_json_fast(&mut test_conf.0, &test_conf.1, test_conf.2, config).unwrap();

        let trans = fs::read_to_string(lang_file_path).unwrap();
        fs::remove_file(test_file_path).unwrap();
        fs::remove_file(lang_file_path).unwrap();

        assert_eq!(trans, DA_JSON_1);
    }

    #[test]
    fn it_creates_a_json_file_with_specific_name() {
        let test_file_path = "test_file_a.csv";
        let lang_file_path = "da_DK_a/locales.json";
        let config = &Config {
            output_filename: Some("locales"),
            ..CONFIG
        };

        let mut test_conf = generate_csv_reader(test_file_path, CSV_ROW_A, config);
        generate_json_fast(&mut test_conf.0, &test_conf.1, test_conf.2, config).unwrap();

        assert!(Path::new(lang_file_path).exists());
        fs::remove_file(lang_file_path).unwrap();

        let config = &Config {
            output_dir: "custom",
            output_filename: Some("locales"),
            ..CONFIG
        };
        let lang_file_path = "custom/da_DK_a/locales.json";
        let mut test_conf = generate_csv_reader(test_file_path, CSV_ROW_A, config);
        generate_json_fast(&mut test_conf.0, &test_conf.1, test_conf.2, config).unwrap();

        assert!(Path::new(lang_file_path).exists());

        fs::remove_file(test_file_path).unwrap();
        fs::remove_dir_all("custom").unwrap();
        fs::remove_dir_all("da_DK_a").unwrap();
    }

    #[test]
    fn it_creates_a_new_json_file_for_the_given_language_from_ssv() {
        let test_file_path = "test_file_1.ssv";
        let lang_file_path = "da_DK_s.json";
        let config = &Config {
            delimiter: b';',
            ..CONFIG
        };
        let mut test_conf = generate_csv_reader(test_file_path, SSV_ROW_1, config);

        generate_json_fast(&mut test_conf.0, &test_conf.1, test_conf.2, config).unwrap();

        let trans = fs::read_to_string(lang_file_path).unwrap();
        fs::remove_file(test_file_path).unwrap();
        fs::remove_file(lang_file_path).unwrap();

        assert_eq!(trans, DA_JSON_1);
    }

    #[test]
    fn it_ignores_column_header_when_configured_to_do_so() {
        // Empty translation
        let test_file_0 = "test_file_ignore.csv";
        let lang_file_0 = "da_DK_0.json";
        let config = &Config {
            ignored_headings: Some(vec!["da_DK_0"]),
            ..CONFIG
        };

        let mut test_conf_0 = generate_csv_reader(test_file_0, CSV_ROW_0, config);
        generate_json_fast(&mut test_conf_0.0, &test_conf_0.1, test_conf_0.2, config).unwrap();

        fs::remove_file(test_file_0).unwrap();
        assert!(File::open(lang_file_0).is_err());
    }

    #[test]
    fn it_creates_a_new_json_file_for_the_given_language_from_csv() {
        // Empty translation
        let test_file_0 = "test_file0.csv";
        let lang_file_0 = "da_DK_0.json";
        let mut test_conf_0 = generate_csv_reader(test_file_0, CSV_ROW_0, &CONFIG);
        generate_json_fast(&mut test_conf_0.0, &test_conf_0.1, test_conf_0.2, &CONFIG).unwrap();

        // Actual translation
        let test_file_1 = "test_file1.csv";
        let lang_file_1 = "da_DK_1.json";
        let mut test_conf_1 = generate_csv_reader(test_file_1, CSV_ROW_1, &CONFIG);
        generate_json_fast(&mut test_conf_1.0, &test_conf_1.1, test_conf_1.2, &CONFIG).unwrap();

        let trans_0 = fs::read_to_string(lang_file_0).unwrap();
        fs::remove_file(test_file_0).unwrap();
        fs::remove_file(lang_file_0).unwrap();

        let trans_1 = fs::read_to_string(lang_file_1).unwrap();
        fs::remove_file(test_file_1).unwrap();
        fs::remove_file(lang_file_1).unwrap();

        assert_eq!(trans_0, DA_JSON_0);
        assert_eq!(trans_1, DA_JSON_1);
    }

    #[test]
    fn it_does_not_overwrite_existing_key_with_empty_value() {
        let test_file_path = "test_file2.csv";
        let lang_file_path = "da_DK_2.json";
        let mut test_conf = generate_csv_reader(test_file_path, CSV_ROW_2, &CONFIG);

        generate_json_fast(&mut test_conf.0, &test_conf.1, test_conf.2, &CONFIG).unwrap();

        let trans = fs::read_to_string(lang_file_path).unwrap();
        fs::remove_file(test_file_path).unwrap();
        fs::remove_file(lang_file_path).unwrap();

        assert_eq!(trans, DA_JSON_1);
    }

    #[test]
    fn it_overwrites_existing_key_with_new_value() {
        let test_file_path = "test_file3.csv";
        let lang_file_path = "da_DK_3.json";
        let mut test_conf = generate_csv_reader(test_file_path, CSV_ROW_3, &CONFIG);

        generate_json_fast(&mut test_conf.0, &test_conf.1, test_conf.2, &CONFIG).unwrap();

        let trans = fs::read_to_string(lang_file_path).unwrap();
        fs::remove_file(test_file_path).unwrap();
        fs::remove_file(lang_file_path).unwrap();

        assert_eq!(trans, DA_JSON_2);
    }

    #[test]
    fn it_overwrites_empty_value_with_new_value() {
        let test_file_path = "test_file4.csv";
        let lang_file_path = "da_DK_4.json";
        let mut test_conf = generate_csv_reader(test_file_path, CSV_ROW_4, &CONFIG);

        generate_json_fast(&mut test_conf.0, &test_conf.1, test_conf.2, &CONFIG).unwrap();

        let trans = fs::read_to_string(lang_file_path).unwrap();
        fs::remove_file(test_file_path).unwrap();
        fs::remove_file(lang_file_path).unwrap();

        assert_eq!(trans, DA_JSON_1);
    }
}