formatjs_cli 0.1.11

Command-line interface for FormatJS - A Rust-based CLI for internationalization
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
use anyhow::{Context, Result};
use glob::glob;
use std::path::PathBuf;

use crate::compile;
use crate::formatters::Formatter;

/// Batch compile all extracted translation JSON files in a folder.
///
/// This command scans a source folder for translation JSON files, compiles each one
/// using the same logic as the compile command, and writes the compiled output to
/// a corresponding location in the output folder while preserving directory structure.
///
/// # Arguments
///
/// * `folder` - Source directory containing translation JSON files
/// * `out_folder` - Output directory for compiled files
/// * `format` - Optional formatter (same signature as compile command)
/// * `ast` - Whether to compile to AST representation
/// * `skip_errors` - Continue compiling after errors, excluding keys with errors from output
/// * `pseudo_locale` - Optional pseudo-locale generation
/// * `ignore_tag` - Treat HTML/XML tags as string literals
///
/// # Example
///
/// ```no_run
/// # use std::path::PathBuf;
/// # use formatjs_cli::compile_folder::compile_folder;
/// compile_folder(
///     &PathBuf::from("lang/"),
///     &PathBuf::from("dist/lang/"),
///     None,
///     true,
///     false,
///     None,
///     false,
/// ).unwrap();
/// ```
pub fn compile_folder(
    folder: &PathBuf,
    out_folder: &PathBuf,
    format: Option<Formatter>,
    ast: bool,
    skip_errors: bool,
    pseudo_locale: Option<compile::PseudoLocale>,
    ignore_tag: bool,
) -> Result<()> {
    use crate::compile::compile;

    // Verify source folder exists
    if !folder.exists() {
        anyhow::bail!("Source folder does not exist: {}", folder.display());
    }
    if !folder.is_dir() {
        anyhow::bail!("Source path is not a directory: {}", folder.display());
    }

    // Create output folder if it doesn't exist
    std::fs::create_dir_all(out_folder).with_context(|| {
        format!(
            "Failed to create output directory: {}",
            out_folder.display()
        )
    })?;

    // Find all .json files in the source folder (recursively)
    let pattern = folder.join("**/*.json");
    let pattern_str = pattern
        .to_str()
        .context("Folder path contains invalid UTF-8")?;

    let json_files: Vec<PathBuf> = match glob(pattern_str) {
        Ok(paths) => paths.filter_map(Result::ok).collect(),
        Err(e) => {
            anyhow::bail!("Failed to read folder pattern '{}': {}", pattern_str, e);
        }
    };

    if json_files.is_empty() {
        eprintln!(
            "Warning: No .json files found in folder {}",
            folder.display()
        );
        return Ok(());
    }

    eprintln!("Found {} JSON files to compile", json_files.len());

    // Process each file individually
    let mut success_count = 0;
    let mut error_count = 0;

    for json_file in &json_files {
        // Get the relative path from source folder
        let relative_path = json_file
            .strip_prefix(folder)
            .with_context(|| format!("Failed to get relative path for {}", json_file.display()))?;

        // Construct output path
        let out_file = out_folder.join(relative_path);

        // Ensure output directory exists
        if let Some(parent) = out_file.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
        }

        // Compile this single file
        eprintln!("Compiling {} ...", relative_path.display());
        match compile(
            &[json_file.clone()],
            format,
            Some(&out_file),
            ast,
            skip_errors,
            pseudo_locale,
            ignore_tag,
        ) {
            Ok(_) => {
                success_count += 1;
            }
            Err(e) => {
                error_count += 1;
                eprintln!("  Error: {}", e);
                // Continue processing other files
            }
        }
    }

    eprintln!(
        "\n✓ Folder compilation complete: {} succeeded, {} failed",
        success_count, error_count
    );

    if error_count > 0 {
        anyhow::bail!("{} file(s) failed to compile", error_count);
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn test_compile_folder_simple() {
        let src_dir = tempdir().unwrap();
        let out_dir = tempdir().unwrap();

        // Create input files with message descriptor format
        fs::write(
            src_dir.path().join("en.json"),
            json!({"greeting": {"defaultMessage": "Hello!"}}).to_string(),
        )
        .unwrap();
        fs::write(
            src_dir.path().join("fr.json"),
            json!({"greeting": {"defaultMessage": "Bonjour!"}}).to_string(),
        )
        .unwrap();

        // Compile folder
        compile_folder(
            &src_dir.path().to_path_buf(),
            &out_dir.path().to_path_buf(),
            None,
            false,
            false,
            None,
            false,
        )
        .unwrap();

        // Verify output files exist
        assert!(out_dir.path().join("en.json").exists());
        assert!(out_dir.path().join("fr.json").exists());

        // Verify content
        let en_content = fs::read_to_string(out_dir.path().join("en.json")).unwrap();
        let en_json: serde_json::Value = serde_json::from_str(&en_content).unwrap();
        assert_eq!(en_json["greeting"], "Hello!");

        let fr_content = fs::read_to_string(out_dir.path().join("fr.json")).unwrap();
        let fr_json: serde_json::Value = serde_json::from_str(&fr_content).unwrap();
        assert_eq!(fr_json["greeting"], "Bonjour!");
    }

    #[test]
    fn test_compile_folder_preserves_structure() {
        let src_dir = tempdir().unwrap();
        let out_dir = tempdir().unwrap();

        // Create nested directory structure
        fs::create_dir(src_dir.path().join("locales")).unwrap();
        fs::create_dir(src_dir.path().join("locales/en")).unwrap();
        fs::create_dir(src_dir.path().join("locales/fr")).unwrap();

        // Create input files in nested structure with message descriptor format
        fs::write(
            src_dir.path().join("locales/en/messages.json"),
            json!({"greeting": {"defaultMessage": "Hello!"}}).to_string(),
        )
        .unwrap();
        fs::write(
            src_dir.path().join("locales/fr/messages.json"),
            json!({"greeting": {"defaultMessage": "Bonjour!"}}).to_string(),
        )
        .unwrap();

        // Compile folder
        compile_folder(
            &src_dir.path().to_path_buf(),
            &out_dir.path().to_path_buf(),
            None,
            false,
            false,
            None,
            false,
        )
        .unwrap();

        // Verify directory structure is preserved
        assert!(out_dir.path().join("locales/en/messages.json").exists());
        assert!(out_dir.path().join("locales/fr/messages.json").exists());

        // Verify content
        let en_content =
            fs::read_to_string(out_dir.path().join("locales/en/messages.json")).unwrap();
        let en_json: serde_json::Value = serde_json::from_str(&en_content).unwrap();
        assert_eq!(en_json["greeting"], "Hello!");
    }

    #[test]
    fn test_compile_folder_with_formatter() {
        let src_dir = tempdir().unwrap();
        let out_dir = tempdir().unwrap();

        // Create input file with MessageDescriptor format
        fs::write(
            src_dir.path().join("messages.json"),
            json!({
                "greeting": {
                    "defaultMessage": "Hello {name}!",
                    "description": "Greeting"
                }
            })
            .to_string(),
        )
        .unwrap();

        // Compile folder with default formatter
        compile_folder(
            &src_dir.path().to_path_buf(),
            &out_dir.path().to_path_buf(),
            Some(Formatter::Default),
            false,
            false,
            None,
            false,
        )
        .unwrap();

        // Verify output
        let content = fs::read_to_string(out_dir.path().join("messages.json")).unwrap();
        let json: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(json["greeting"], "Hello {name}!");
    }

    #[test]
    fn test_compile_folder_to_ast() {
        let src_dir = tempdir().unwrap();
        let out_dir = tempdir().unwrap();

        // Create input file with message descriptor format
        fs::write(
            src_dir.path().join("messages.json"),
            json!({"greeting": {"defaultMessage": "Hello {name}!"}}).to_string(),
        )
        .unwrap();

        // Compile folder to AST
        compile_folder(
            &src_dir.path().to_path_buf(),
            &out_dir.path().to_path_buf(),
            None,
            true, // AST output
            false,
            None,
            false,
        )
        .unwrap();

        // Verify output is AST
        let content = fs::read_to_string(out_dir.path().join("messages.json")).unwrap();
        let json: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert!(json["greeting"].is_array());
    }

    #[test]
    fn test_compile_folder_source_not_exists() {
        let out_dir = tempdir().unwrap();
        let nonexistent = PathBuf::from("/nonexistent/path");

        // Should fail when source folder doesn't exist
        let result = compile_folder(
            &nonexistent,
            &out_dir.path().to_path_buf(),
            None,
            false,
            false,
            None,
            false,
        );

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("does not exist"));
    }

    #[test]
    fn test_compile_folder_source_not_directory() {
        let dir = tempdir().unwrap();
        let file = dir.path().join("file.txt");
        let out_dir = tempdir().unwrap();

        // Create a file instead of directory
        fs::write(&file, "content").unwrap();

        // Should fail when source is not a directory
        let result = compile_folder(
            &file,
            &out_dir.path().to_path_buf(),
            None,
            false,
            false,
            None,
            false,
        );

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not a directory"));
    }

    #[test]
    fn test_compile_folder_no_json_files() {
        let src_dir = tempdir().unwrap();
        let out_dir = tempdir().unwrap();

        // Create a non-JSON file
        fs::write(src_dir.path().join("readme.txt"), "text").unwrap();

        // Should succeed but warn about no files
        let result = compile_folder(
            &src_dir.path().to_path_buf(),
            &out_dir.path().to_path_buf(),
            None,
            false,
            false,
            None,
            false,
        );

        assert!(result.is_ok());
    }

    #[test]
    fn test_compile_folder_partial_failure() {
        let src_dir = tempdir().unwrap();
        let out_dir = tempdir().unwrap();

        // Create one valid and one invalid file with message descriptor format
        fs::write(
            src_dir.path().join("valid.json"),
            json!({"greeting": {"defaultMessage": "Hello!"}}).to_string(),
        )
        .unwrap();
        fs::write(
            src_dir.path().join("invalid.json"),
            json!({"greeting": {"defaultMessage": "Hello {name"}}).to_string(), // Invalid ICU
        )
        .unwrap();

        // Should fail (compile_folder doesn't skip errors by default)
        let result = compile_folder(
            &src_dir.path().to_path_buf(),
            &out_dir.path().to_path_buf(),
            None,
            false,
            false,
            None,
            false,
        );

        assert!(result.is_err());
    }

    #[test]
    fn test_compile_folder_multiple_files() {
        let src_dir = tempdir().unwrap();
        let out_dir = tempdir().unwrap();

        // Create multiple files
        for i in 0..5 {
            fs::write(
                src_dir.path().join(format!("msg{}.json", i)),
                json!({format!("msg{}", i): format!("Message {}", i)}).to_string(),
            )
            .unwrap();
        }

        // Compile folder
        compile_folder(
            &src_dir.path().to_path_buf(),
            &out_dir.path().to_path_buf(),
            None,
            false,
            false,
            None,
            false,
        )
        .unwrap();

        // Verify all files were compiled
        for i in 0..5 {
            assert!(out_dir.path().join(format!("msg{}.json", i)).exists());
        }
    }

    #[test]
    fn test_compile_folder_creates_output_dir() {
        let src_dir = tempdir().unwrap();
        let parent_dir = tempdir().unwrap();
        let out_dir = parent_dir.path().join("nested/output/dir");

        // Create input file
        fs::write(
            src_dir.path().join("messages.json"),
            json!({"greeting": "Hello!"}).to_string(),
        )
        .unwrap();

        // Compile folder (should create nested output directory)
        compile_folder(
            &src_dir.path().to_path_buf(),
            &out_dir,
            None,
            false,
            false,
            None,
            false,
        )
        .unwrap();

        // Verify output directory was created
        assert!(out_dir.exists());
        assert!(out_dir.join("messages.json").exists());
    }
}