ruchy 4.1.1

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
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
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
//! Refactored test command handler
//! Complexity reduced from ~200 lines to ≤10 per function
use super::test_helpers::{
    discover_test_files, execute_tests, generate_coverage_report, generate_json_output,
    print_test_summary, TestResult,
};
use anyhow::Result;
use std::path::{Path, PathBuf};
use std::time::Instant;
/// Handle test command - refactored with ≤10 complexity
pub fn handle_test_command(
    path: Option<PathBuf>,
    watch: bool,
    verbose: bool,
    filter: Option<&str>,
    coverage: bool,
    coverage_format: &str,
    parallel: usize,
    threshold: f64,
    format: &str,
) -> Result<()> {
    let test_path = path.unwrap_or_else(|| PathBuf::from("."));
    if watch {
        handle_watch_mode(&test_path, verbose, filter)
    } else {
        run_tests(
            &test_path,
            verbose,
            filter,
            coverage,
            coverage_format,
            parallel,
            threshold,
            format,
        )
    }
}
/// Run tests once
fn run_tests(
    path: &Path,
    verbose: bool,
    filter: Option<&str>,
    coverage: bool,
    coverage_format: &str,
    _parallel: usize, // Unused for now
    threshold: f64,
    format: &str,
) -> Result<()> {
    // Discover test files
    let test_files = discover_test_files(path, filter, verbose)?;
    if test_files.is_empty() {
        println!("⚠️  No .ruchy test files found in {}", path.display());
        return Ok(());
    }
    println!("🧪 Running {} .ruchy test files...\n", test_files.len());
    // Execute tests
    let total_start = Instant::now();
    let test_results = execute_tests(&test_files, verbose);
    let total_duration = total_start.elapsed();
    // Print summary
    print_test_summary(&test_results, total_duration, verbose);
    // Handle output format
    if format == "json" {
        let json = generate_json_output(&test_results, total_duration)?;
        println!("\n{}", json);
    }
    // Handle coverage if requested
    if coverage {
        generate_coverage_report(&test_files, &test_results, coverage_format, threshold)?;
    }
    // Check for failures
    check_test_failures(&test_results)?;
    println!("\n✅ All tests passed!");
    Ok(())
}
/// Handle watch mode
fn handle_watch_mode(path: &Path, verbose: bool, filter: Option<&str>) -> Result<()> {
    use colored::Colorize;
    use std::thread;
    use std::time::Duration;
    println!(
        "{} Watching {} for test changes...",
        "👁".bright_cyan(),
        path.display()
    );
    println!("Press Ctrl+C to stop watching\n");
    // Initial test run
    let _ = run_tests(path, verbose, filter, false, "text", 1, 0.0, "text");
    // Watch for changes
    let mut last_modified = get_latest_modification(path);
    loop {
        thread::sleep(Duration::from_millis(1000));
        let current_modified = get_latest_modification(path);
        if current_modified > last_modified {
            last_modified = current_modified;
            println!("\n{} Files changed, running tests...", "".bright_cyan());
            let _ = run_tests(path, verbose, filter, false, "text", 1, 0.0, "text");
        }
    }
}
/// Get latest modification time in directory
fn get_latest_modification(path: &Path) -> std::time::SystemTime {
    use std::fs;
    let mut latest = std::time::SystemTime::now();
    if let Ok(entries) = fs::read_dir(path) {
        for entry in entries.flatten() {
            if let Ok(path) = entry.path().canonicalize() {
                if path.extension().and_then(|ext| ext.to_str()) == Some("ruchy") {
                    if let Ok(metadata) = fs::metadata(&path) {
                        if let Ok(modified) = metadata.modified() {
                            if modified > latest {
                                latest = modified;
                            }
                        }
                    }
                }
            }
        }
    }
    latest
}
/// Check if any tests failed and return error if necessary
fn check_test_failures(test_results: &[TestResult]) -> Result<()> {
    let failed = test_results.iter().filter(|r| !r.success).count();
    if failed > 0 {
        Err(anyhow::anyhow!(
            "Test failures detected: {} tests failed",
            failed
        ))
    } else {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::time::Duration;
    use tempfile::TempDir;

    // Helper function to create a test directory with .ruchy files
    fn create_test_directory_with_files() -> Result<TempDir> {
        let temp_dir = TempDir::new()?;

        // Create a passing test file
        let test_file1 = temp_dir.path().join("passing_test.ruchy");
        fs::write(&test_file1, "println(\"Hello Test\")")?;

        // Create another passing test file
        let test_file2 = temp_dir.path().join("another_test.ruchy");
        fs::write(&test_file2, "let x = 42; println(x)")?;

        // Create a non-ruchy file (should be ignored)
        let readme_file = temp_dir.path().join("README.txt");
        fs::write(&readme_file, "This is documentation")?;

        Ok(temp_dir)
    }

    // Helper function to create TestResult instances
    fn create_test_result(
        file: &str,
        success: bool,
        duration_ms: u64,
        error: Option<&str>,
    ) -> TestResult {
        TestResult {
            file: PathBuf::from(file),
            success,
            duration: Duration::from_millis(duration_ms),
            error: error.map(std::string::ToString::to_string),
        }
    }

    // ========== Test Command Handler Tests ==========
    #[test]
    fn test_handle_test_command_default_path() {
        let temp_dir =
            create_test_directory_with_files().expect("Failed to create test directory with files");

        // Change to the temp directory for the test
        let original_dir = std::env::current_dir().expect("Failed to get current directory");
        std::env::set_current_dir(temp_dir.path())
            .expect("Failed to set current directory to temp path");

        let result = handle_test_command(
            None,   // Use default path (current directory)
            false,  // No watch mode
            false,  // Not verbose
            None,   // No filter
            false,  // No coverage
            "text", // Coverage format
            1,      // Parallel threads
            0.0,    // No threshold
            "text", // Output format
        );

        // Restore original directory
        std::env::set_current_dir(original_dir).expect("Failed to restore original directory");

        // Test should complete without panicking
        assert!(result.is_ok() || result.is_err());
    }

    #[test]
    fn test_handle_test_command_with_path() {
        let temp_dir =
            create_test_directory_with_files().expect("Failed to create test directory with files");

        let result = handle_test_command(
            Some(temp_dir.path().to_path_buf()),
            false,  // No watch mode
            true,   // Verbose
            None,   // No filter
            false,  // No coverage
            "text", // Coverage format
            1,      // Parallel threads
            0.0,    // No threshold
            "text", // Output format
        );

        // Test should complete without panicking
        assert!(result.is_ok() || result.is_err());
    }

    #[test]
    fn test_handle_test_command_with_filter() {
        let temp_dir =
            create_test_directory_with_files().expect("Failed to create test directory with files");

        let result = handle_test_command(
            Some(temp_dir.path().to_path_buf()),
            false,           // No watch mode
            false,           // Not verbose
            Some("passing"), // Filter for "passing" in filename
            false,           // No coverage
            "text",          // Coverage format
            1,               // Parallel threads
            0.0,             // No threshold
            "text",          // Output format
        );

        // Test should complete without panicking
        assert!(result.is_ok() || result.is_err());
    }

    #[test]
    fn test_handle_test_command_with_coverage() {
        let temp_dir =
            create_test_directory_with_files().expect("Failed to create test directory with files");

        let result = handle_test_command(
            Some(temp_dir.path().to_path_buf()),
            false,  // No watch mode
            false,  // Not verbose
            None,   // No filter
            true,   // Enable coverage
            "html", // HTML coverage format
            1,      // Parallel threads
            80.0,   // Coverage threshold
            "text", // Output format
        );

        // Test should complete without panicking
        assert!(result.is_ok() || result.is_err());
    }

    #[test]
    fn test_handle_test_command_json_output() {
        let temp_dir =
            create_test_directory_with_files().expect("Failed to create test directory with files");

        let result = handle_test_command(
            Some(temp_dir.path().to_path_buf()),
            false,  // No watch mode
            false,  // Not verbose
            None,   // No filter
            false,  // No coverage
            "text", // Coverage format
            1,      // Parallel threads
            0.0,    // No threshold
            "json", // JSON output format
        );

        // Test should complete without panicking
        assert!(result.is_ok() || result.is_err());
    }

    // ========== Run Tests Function Tests ==========
    #[test]
    fn test_run_tests_empty_directory() {
        let temp_dir = TempDir::new().expect("Failed to create temporary test directory");
        // Create empty directory with no .ruchy files

        let result = run_tests(
            temp_dir.path(),
            false,  // Not verbose
            None,   // No filter
            false,  // No coverage
            "text", // Coverage format
            1,      // Parallel threads
            0.0,    // No threshold
            "text", // Output format
        );

        // Should handle empty directory gracefully
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_tests_with_files() {
        let temp_dir =
            create_test_directory_with_files().expect("Failed to create test directory with files");

        let result = run_tests(
            temp_dir.path(),
            true,   // Verbose
            None,   // No filter
            false,  // No coverage
            "text", // Coverage format
            1,      // Parallel threads
            0.0,    // No threshold
            "text", // Output format
        );

        // Test should complete without panicking
        assert!(result.is_ok() || result.is_err());
    }

    #[test]
    fn test_run_tests_with_filter() {
        let temp_dir =
            create_test_directory_with_files().expect("Failed to create test directory with files");

        let result = run_tests(
            temp_dir.path(),
            false,           // Not verbose
            Some("another"), // Filter for "another" in filename
            false,           // No coverage
            "text",          // Coverage format
            1,               // Parallel threads
            0.0,             // No threshold
            "text",          // Output format
        );

        // Test should complete without panicking
        assert!(result.is_ok() || result.is_err());
    }

    #[test]
    fn test_run_tests_json_format() {
        let temp_dir =
            create_test_directory_with_files().expect("Failed to create test directory with files");

        let result = run_tests(
            temp_dir.path(),
            false,  // Not verbose
            None,   // No filter
            false,  // No coverage
            "text", // Coverage format
            1,      // Parallel threads
            0.0,    // No threshold
            "json", // JSON output format
        );

        // Test should complete without panicking
        assert!(result.is_ok() || result.is_err());
    }

    #[test]
    fn test_run_tests_with_coverage() {
        let temp_dir =
            create_test_directory_with_files().expect("Failed to create test directory with files");

        let result = run_tests(
            temp_dir.path(),
            false,  // Not verbose
            None,   // No filter
            true,   // Enable coverage
            "html", // HTML coverage format
            1,      // Parallel threads
            75.0,   // Coverage threshold
            "text", // Output format
        );

        // Test should complete without panicking
        assert!(result.is_ok() || result.is_err());
    }

    // ========== Watch Mode Tests ==========
    #[test]

    fn test_handle_watch_mode_setup() {
        let _temp_dir =
            create_test_directory_with_files().expect("Failed to create test directory with files");

        // We can't easily test the full watch mode (infinite loop),
        // but we can test that it doesn't panic on initial setup
        // This test would need to be run manually or with a timeout mechanism

        // For now, just test that the function exists and can be called
        // In a real test environment, you'd use a timeout or separate thread

        // Note: This test is marked as  to prevent infinite loop in CI
        let _result = std::panic::catch_unwind(|| {
            std::thread::spawn(move || {
                std::thread::sleep(Duration::from_millis(10)); // Short sleep
                std::process::exit(0); // Exit quickly to avoid infinite loop
            });
        });
    }

    // ========== File Modification Tests ==========
    #[test]
    fn test_get_latest_modification_empty_directory() {
        let temp_dir = TempDir::new().expect("Failed to create temporary test directory");
        // Empty directory with no .ruchy files

        let modification_time = get_latest_modification(temp_dir.path());
        // Should return some time (likely current time)
        assert!(modification_time <= std::time::SystemTime::now());
    }

    #[test]
    fn test_get_latest_modification_with_ruchy_files() {
        let temp_dir =
            create_test_directory_with_files().expect("Failed to create test directory with files");

        let modification_time = get_latest_modification(temp_dir.path());
        // Should return a valid time
        assert!(modification_time <= std::time::SystemTime::now());
    }

    #[test]
    fn test_get_latest_modification_with_mixed_files() {
        let temp_dir = TempDir::new().expect("Failed to create temporary test directory");

        // Create a .ruchy file
        let ruchy_file = temp_dir.path().join("test.ruchy");
        fs::write(&ruchy_file, "println(\"test\")")
            .unwrap_or_else(|_| panic!("Failed to write test file: {}", ruchy_file.display()));

        // Create a non-ruchy file (should be ignored)
        let other_file = temp_dir.path().join("other.txt");
        fs::write(&other_file, "not ruchy")
            .unwrap_or_else(|_| panic!("Failed to write test file: {}", other_file.display()));

        let modification_time = get_latest_modification(temp_dir.path());
        // Should return a valid time
        assert!(modification_time <= std::time::SystemTime::now());
    }

    #[test]
    fn test_get_latest_modification_nonexistent_directory() {
        let nonexistent_path = Path::new("/nonexistent/directory");

        let modification_time = get_latest_modification(nonexistent_path);
        // Should handle gracefully and return some time
        assert!(modification_time <= std::time::SystemTime::now());
    }

    // ========== Test Failure Checking Tests ==========
    #[test]
    fn test_check_test_failures_all_passing() {
        let test_results = vec![
            create_test_result("test1.ruchy", true, 100, None),
            create_test_result("test2.ruchy", true, 150, None),
            create_test_result("test3.ruchy", true, 200, None),
        ];

        // Should return Ok for all passing tests
        assert!(check_test_failures(&test_results).is_ok());
    }

    #[test]
    fn test_check_test_failures_with_failures() {
        let test_results = vec![
            create_test_result("test1.ruchy", true, 100, None),
            create_test_result("test2.ruchy", false, 50, Some("Parse error")),
            create_test_result("test3.ruchy", true, 200, None),
        ];

        // Should return Err when there are failures
        let result = check_test_failures(&test_results);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("1 tests failed"));
    }

    #[test]
    fn test_check_test_failures_all_failing() {
        let test_results = vec![
            create_test_result("test1.ruchy", false, 50, Some("Error 1")),
            create_test_result("test2.ruchy", false, 60, Some("Error 2")),
            create_test_result("test3.ruchy", false, 70, Some("Error 3")),
        ];

        // Should return Err when all tests fail
        let result = check_test_failures(&test_results);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("3 tests failed"));
    }

    #[test]
    fn test_check_test_failures_empty_results() {
        let test_results: Vec<TestResult> = vec![];

        // Should return Ok for empty results (no failures)
        assert!(check_test_failures(&test_results).is_ok());
    }

    // ========== Integration Tests ==========
    #[test]
    fn test_integration_complete_workflow() {
        let temp_dir =
            create_test_directory_with_files().expect("Failed to create test directory with files");

        // Test the complete workflow without watch mode
        let result = handle_test_command(
            Some(temp_dir.path().to_path_buf()),
            false,  // No watch mode
            true,   // Verbose
            None,   // No filter
            false,  // No coverage (to keep test simple)
            "text", // Coverage format
            1,      // Single thread
            0.0,    // No threshold
            "text", // Text output
        );

        // Should complete the full workflow
        assert!(result.is_ok() || result.is_err());
    }

    #[test]
    fn test_integration_with_all_options() {
        let temp_dir =
            create_test_directory_with_files().expect("Failed to create test directory with files");

        // Test with maximum options enabled
        let result = handle_test_command(
            Some(temp_dir.path().to_path_buf()),
            false,        // No watch mode (to keep test finite)
            true,         // Verbose
            Some("test"), // Filter
            true,         // Enable coverage
            "json",       // JSON coverage format
            2,            // Multiple threads
            50.0,         // Coverage threshold
            "json",       // JSON output
        );

        // Should handle all options gracefully
        assert!(result.is_ok() || result.is_err());
    }

    // ========== Error Handling Tests ==========
    #[test]
    fn test_error_handling_invalid_path() {
        let invalid_path = PathBuf::from("/absolutely/nonexistent/path/that/should/not/exist");

        let result = handle_test_command(
            Some(invalid_path),
            false,  // No watch mode
            false,  // Not verbose
            None,   // No filter
            false,  // No coverage
            "text", // Coverage format
            1,      // Single thread
            0.0,    // No threshold
            "text", // Text output
        );

        // Should handle invalid path gracefully (likely return an error)
        assert!(result.is_err() || result.is_ok());
    }

    #[test]
    fn test_parameter_validation() {
        let temp_dir =
            create_test_directory_with_files().expect("Failed to create test directory with files");

        // Test with various parameter combinations
        let test_cases = vec![
            (0, 0.0, "text"),    // Minimum values
            (1, 50.0, "json"),   // Medium values
            (10, 100.0, "html"), // Maximum values
        ];

        for (parallel, threshold, format) in test_cases {
            let result = handle_test_command(
                Some(temp_dir.path().to_path_buf()),
                false,  // No watch mode
                false,  // Not verbose
                None,   // No filter
                false,  // No coverage
                "text", // Coverage format
                parallel,
                threshold,
                format,
            );

            // All parameter combinations should be handled
            assert!(result.is_ok() || result.is_err());
        }
    }
}