yek 0.25.5

A tool to serialize a repository into chunks of text 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
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
use anyhow::Result;
use normalize_path::NormalizePath;
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::Write;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use tempfile::tempdir;
use yek::config::YekConfig;
use yek::parallel::process_files_parallel;

#[cfg(unix)]
fn make_unreadable(path: &Path) -> std::io::Result<()> {
    let mut permissions = fs::metadata(path)?.permissions();
    permissions.set_mode(0o000);
    fs::set_permissions(path, permissions)
}

#[cfg(not(unix))]
fn make_unreadable(_path: &Path) -> std::io::Result<()> {
    // On Windows, we can't easily make files unreadable in the same way
    // Skip this test functionality on Windows
    Ok(())
}

#[cfg(unix)]
fn make_readable(path: &Path) -> std::io::Result<()> {
    let mut permissions = fs::metadata(path)?.permissions();
    permissions.set_mode(0o644);
    fs::set_permissions(path, permissions)
}

#[cfg(not(unix))]
fn make_readable(_path: &Path) -> std::io::Result<()> {
    // On Windows, files are readable by default
    Ok(())
}

#[test]
fn test_normalize_path_unix_style() {
    let input = Path::new("/usr/local/bin");
    let base = Path::new("/"); // Dummy base path
    let expected = "usr/local/bin".to_string();
    assert_eq!(
        input
            .strip_prefix(base)
            .unwrap()
            .normalize()
            .to_string_lossy()
            .to_string(),
        expected
    );
}

#[test]
fn test_normalize_path_windows_style() {
    let input = Path::new("C:\\Program Files\\Yek");
    let base = Path::new("C:\\"); // Dummy base for normalization
    let expected = if cfg!(windows) {
        "Program Files\\Yek".to_string()
    } else {
        "C:/Program Files/Yek".to_string()
    };
    let stripped_path = input.strip_prefix(base).unwrap_or(input);
    // Normalize the stripped path, then replace backslashes with forward slashes
    let normalized = stripped_path
        .normalize()
        .to_string_lossy()
        .to_string()
        .replace("\\", "/");
    let expected_normalized = expected.replace("\\", "/");
    assert_eq!(normalized, expected_normalized);
}

#[test]
fn test_process_files_parallel_empty() {
    let temp_dir = tempdir().expect("failed to create temp dir");
    let config = YekConfig::extend_config_with_defaults(
        vec![temp_dir.path().to_string_lossy().to_string()],
        ".".to_string(),
    );
    let boosts: HashMap<String, i32> = HashMap::new();
    let result = process_files_parallel(temp_dir.path(), &config, &boosts)
        .expect("process_files_parallel failed");
    assert_eq!(result.len(), 0);
}

#[test]
fn test_process_files_parallel_with_files() {
    let temp_dir = tempdir().expect("failed to create temp dir");
    let file_names = vec!["a.txt", "b.txt", "c.txt"];
    for &file in &file_names {
        let file_path = temp_dir.path().join(file);
        fs::write(file_path, "dummy content").expect("failed to write dummy file");
    }
    let config = YekConfig::extend_config_with_defaults(
        vec![temp_dir.path().to_string_lossy().to_string()],
        ".".to_string(),
    );
    let boosts: HashMap<String, i32> = HashMap::new();
    let base = temp_dir.path();
    let result =
        process_files_parallel(base, &config, &boosts).expect("process_files_parallel failed");
    assert_eq!(result.len(), file_names.len());
    let names: Vec<&str> = result.iter().map(|pf| pf.rel_path.as_str()).collect();
    for file in file_names {
        assert!(names.contains(&file), "Missing file: {}", file);
    }
}

#[test]
fn test_process_files_parallel_file_read_error() {
    let temp_dir = tempdir().expect("failed to create temp dir");
    let file_path = temp_dir.path().join("unreadable.txt");
    fs::write(&file_path, "content").expect("failed to write file");

    // Make the file unreadable (Unix only)
    if cfg!(unix) {
        make_unreadable(&file_path).unwrap();

        let config = YekConfig::extend_config_with_defaults(
            vec![temp_dir.path().to_string_lossy().to_string()],
            ".".to_string(),
        );
        let boosts: HashMap<String, i32> = HashMap::new();
        let result = process_files_parallel(temp_dir.path(), &config, &boosts)
            .expect("process_files_parallel failed");

        // The unreadable file should be skipped, so the result should be empty
        assert_eq!(result.len(), 0);

        // Restore permissions so the directory can be cleaned up
        make_readable(&file_path).unwrap();
    } else {
        // On Windows, just test that the file is processed normally
        let config = YekConfig::extend_config_with_defaults(
            vec![temp_dir.path().to_string_lossy().to_string()],
            ".".to_string(),
        );
        let boosts: HashMap<String, i32> = HashMap::new();
        let result = process_files_parallel(temp_dir.path(), &config, &boosts)
            .expect("process_files_parallel failed");

        // The file should be processed normally on Windows
        assert_eq!(result.len(), 1);
    }
}

#[test]
fn test_process_files_parallel_walk_error() {
    let temp_dir = tempdir().expect("failed to create temp dir");
    let subdir = temp_dir.path().join("subdir");
    fs::create_dir(&subdir).expect("failed to create subdir");

    // Make the subdir unreadable, causing walk error (Unix only)
    if cfg!(unix) {
        make_unreadable(&subdir).unwrap();

        let config = YekConfig::extend_config_with_defaults(
            vec![temp_dir.path().to_string_lossy().to_string()],
            ".".to_string(),
        );
        let boosts: HashMap<String, i32> = HashMap::new();
        let result = process_files_parallel(temp_dir.path(), &config, &boosts);

        // Walk errors are logged and skipped, not propagated as Err
        assert!(result.is_ok()); // Walk errors are logged and skipped, not propagated as Err
        let processed_files = result.unwrap();
        assert_eq!(processed_files.len(), 0); // No files processed due to walk error

        // Restore permissions for cleanup
        make_readable(&subdir).unwrap();
    } else {
        // On Windows, just test normal directory walking
        let config = YekConfig::extend_config_with_defaults(
            vec![temp_dir.path().to_string_lossy().to_string()],
            ".".to_string(),
        );
        let boosts: HashMap<String, i32> = HashMap::new();
        let result = process_files_parallel(temp_dir.path(), &config, &boosts);

        // Should succeed on Windows
        assert!(result.is_ok());
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_glob_pattern_single_file() -> Result<()> {
        let temp_dir = tempdir()?;
        let file_path = temp_dir.path().join("test.txt");
        let mut file = File::create(&file_path)?;
        writeln!(file, "Test content")?;

        let glob_pattern = temp_dir.path().join("*.txt").to_string_lossy().to_string();
        let config = YekConfig::default();
        let boost_map = HashMap::new();

        let result = process_files_parallel(&PathBuf::from(&glob_pattern), &config, &boost_map)?;
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].rel_path, file_path.to_string_lossy().to_string());

        Ok(())
    }

    #[test]
    fn test_glob_pattern_multiple_files() -> Result<()> {
        let temp_dir = tempdir()?;

        // Create multiple test files
        let files = vec!["test1.txt", "test2.txt", "other.md"];
        for fname in &files {
            let file_path = temp_dir.path().join(fname);
            let mut file = File::create(&file_path)?;
            writeln!(file, "Test content for {}", fname)?;
        }

        let glob_pattern = temp_dir.path().join("*.txt").to_string_lossy().to_string();
        let config = YekConfig::default();
        let boost_map = HashMap::new();

        let result = process_files_parallel(&PathBuf::from(&glob_pattern), &config, &boost_map)?;
        assert_eq!(result.len(), 2); // Should only match .txt files

        let paths: Vec<String> = result.iter().map(|f| f.rel_path.clone()).collect();
        let test1_path = temp_dir
            .path()
            .join("test1.txt")
            .to_string_lossy()
            .to_string();
        let test2_path = temp_dir
            .path()
            .join("test2.txt")
            .to_string_lossy()
            .to_string();
        assert!(paths.contains(&test1_path));
        assert!(paths.contains(&test2_path));

        Ok(())
    }

    #[test]
    fn test_glob_pattern_nested_directories() -> Result<()> {
        let temp_dir = tempdir()?;

        // Create nested directory structure
        let nested_dir = temp_dir.path().join("nested");
        fs::create_dir(&nested_dir)?;

        // Create files in both root and nested directory
        let root_file = temp_dir.path().join("root.rs"); // Use .rs to avoid default ignore patterns
        let nested_file = nested_dir.join("nested.rs");
        let other_file = temp_dir.path().join("other.md");

        for (path, content) in [
            (&root_file, "Root content"),
            (&nested_file, "Nested content"),
            (&other_file, "Other content"),
        ] {
            let mut file = File::create(path)?;
            writeln!(file, "{}", content)?;
        }

        let glob_pattern = temp_dir
            .path()
            .join("**/*.rs") // Changed to .rs files
            .to_string_lossy()
            .to_string();
        let config = YekConfig::default();
        let boost_map = HashMap::new();

        let result = process_files_parallel(&PathBuf::from(&glob_pattern), &config, &boost_map)?;
        assert_eq!(result.len(), 2); // Should match both .rs files

        let paths: Vec<String> = result.iter().map(|f| f.rel_path.clone()).collect();
        let root_path = root_file.to_string_lossy().to_string();
        let nested_path = nested_file.to_string_lossy().to_string();
        assert!(paths.contains(&root_path));
        assert!(paths.contains(&nested_path));

        Ok(())
    }

    #[test]
    fn test_glob_pattern_no_matches() -> Result<()> {
        let temp_dir = tempdir()?;
        let glob_pattern = temp_dir.path().join("*.txt").to_string_lossy().to_string();
        let config = YekConfig::default();
        let boost_map = HashMap::new();

        let result = process_files_parallel(&PathBuf::from(&glob_pattern), &config, &boost_map)?;
        assert!(result.is_empty());

        Ok(())
    }
    #[test]
    fn test_process_files_parallel_single_file() {
        let temp_dir = tempdir().expect("failed to create temp dir");
        let file_path = temp_dir.path().join("single.txt");
        fs::write(&file_path, "single file content").expect("failed to write file");

        let config = YekConfig::extend_config_with_defaults(
            vec![file_path.to_string_lossy().to_string()],
            ".".to_string(),
        );
        let boosts: HashMap<String, i32> = HashMap::new();

        let result = process_files_parallel(&file_path, &config, &boosts)
            .expect("process_files_parallel failed");

        assert_eq!(result.len(), 1);
        assert_eq!(result[0].rel_path, "single.txt");
        assert_eq!(result[0].content, "single file content");
    }

    #[test]
    fn test_process_files_parallel_glob_pattern() {
        let temp_dir = tempdir().expect("failed to create temp dir");

        // Create files matching a pattern
        fs::write(temp_dir.path().join("file1.rs"), "content1").expect("failed to write file1");
        fs::write(temp_dir.path().join("file2.rs"), "content2").expect("failed to write file2");
        fs::write(temp_dir.path().join("file.md"), "markdown").expect("failed to write md file");

        let glob_pattern = temp_dir.path().join("*.rs").to_string_lossy().to_string();
        let config = YekConfig::default();
        let boosts: HashMap<String, i32> = HashMap::new();

        let result = process_files_parallel(Path::new(&glob_pattern), &config, &boosts)
            .expect("process_files_parallel failed");

        assert_eq!(result.len(), 2);
        let rel_paths: Vec<&str> = result.iter().map(|f| f.rel_path.as_str()).collect();
        assert!(rel_paths.iter().any(|&p| p.ends_with("file1.rs")));
        assert!(rel_paths.iter().any(|&p| p.ends_with("file2.rs")));
    }

    #[test]
    fn test_process_files_parallel_with_gitignore() {
        let temp_dir = tempdir().expect("failed to create temp dir");

        // Create files
        fs::write(temp_dir.path().join("included.txt"), "included")
            .expect("failed to write included");
        fs::write(temp_dir.path().join("ignored.txt"), "ignored").expect("failed to write ignored");

        // Create .gitignore
        fs::write(temp_dir.path().join(".gitignore"), "*.txt\n")
            .expect("failed to write gitignore");

        let config = YekConfig::extend_config_with_defaults(
            vec![temp_dir.path().to_string_lossy().to_string()],
            ".".to_string(),
        );
        let boosts: HashMap<String, i32> = HashMap::new();

        let result = process_files_parallel(temp_dir.path(), &config, &boosts)
            .expect("process_files_parallel failed");

        // Files should be ignored by .gitignore
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_process_files_parallel_binary_file() {
        let temp_dir = tempdir().expect("failed to create temp dir");
        let binary_path = temp_dir.path().join("binary.bin");
        fs::write(&binary_path, [0u8, 1, 2, 3]).expect("failed to write binary file");

        let config = YekConfig::extend_config_with_defaults(
            vec![temp_dir.path().to_string_lossy().to_string()],
            ".".to_string(),
        );
        let boosts: HashMap<String, i32> = HashMap::new();

        let result = process_files_parallel(temp_dir.path(), &config, &boosts)
            .expect("process_files_parallel failed");

        // Binary file should be skipped
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_normalize_path_edge_cases() {
        use yek::parallel::normalize_path;

        let base = Path::new("/base");
        let path = Path::new("/base/sub/file.txt");
        assert_eq!(normalize_path(path, base), "sub/file.txt");

        // Path not under base
        let path = Path::new("/other/file.txt");
        assert_eq!(normalize_path(path, base), "/other/file.txt");

        // Empty path
        let path = Path::new("");
        assert_eq!(normalize_path(path, base), "");
    }
}

// Priority 2: File processing edge case tests
#[test]
fn test_process_files_parallel_with_gitignore_parse_error() {
    let temp_dir = tempdir().expect("failed to create temp dir");

    // Create an invalid .gitignore file
    fs::write(temp_dir.path().join(".gitignore"), "[[invalid pattern")
        .expect("failed to write gitignore");
    fs::write(temp_dir.path().join("test.txt"), "content").expect("failed to write test file");

    let config = YekConfig::extend_config_with_defaults(
        vec![temp_dir.path().to_string_lossy().to_string()],
        ".".to_string(),
    );
    let boosts: HashMap<String, i32> = HashMap::new();

    // Should handle gitignore parse errors gracefully
    let result = process_files_parallel(temp_dir.path(), &config, &boosts);
    assert!(result.is_ok());
    // File should still be processed despite gitignore error
    let files = result.unwrap();
    assert!(!files.is_empty());
}

#[test]
fn test_process_files_parallel_with_large_binary_file() {
    let temp_dir = tempdir().expect("failed to create temp dir");

    // Create a large binary file (over 1MB)
    let large_binary = vec![0u8; 1024 * 1024 + 1];
    fs::write(temp_dir.path().join("large.bin"), large_binary)
        .expect("failed to write large binary");

    let config = YekConfig::extend_config_with_defaults(
        vec![temp_dir.path().to_string_lossy().to_string()],
        ".".to_string(),
    );
    let boosts: HashMap<String, i32> = HashMap::new();

    let result = process_files_parallel(temp_dir.path(), &config, &boosts)
        .expect("process_files_parallel failed");

    // Large binary file should be skipped
    assert_eq!(result.len(), 0);
}

#[test]
fn test_process_files_parallel_with_utf8_bom() {
    let temp_dir = tempdir().expect("failed to create temp dir");

    // Create a file with UTF-8 BOM
    let mut content = vec![0xEF, 0xBB, 0xBF]; // UTF-8 BOM
    content.extend_from_slice(b"Hello World");
    fs::write(temp_dir.path().join("bom.txt"), content).expect("failed to write BOM file");

    let config = YekConfig::extend_config_with_defaults(
        vec![temp_dir.path().to_string_lossy().to_string()],
        ".".to_string(),
    );
    let boosts: HashMap<String, i32> = HashMap::new();

    let result = process_files_parallel(temp_dir.path(), &config, &boosts)
        .expect("process_files_parallel failed");

    // UTF-8 BOM file should be processed
    assert_eq!(result.len(), 1);
    // BOM should be preserved in content
    assert!(result[0].content.starts_with('\u{FEFF}'));
}

#[test]
fn test_process_files_parallel_with_mixed_encoding() {
    let temp_dir = tempdir().expect("failed to create temp dir");

    // Create a file with mixed/invalid UTF-8 encoding
    let invalid_utf8 = vec![
        0x48, 0x65, 0x6C, 0x6C, 0x6F, 0xFF, 0xFE, 0x57, 0x6F, 0x72, 0x6C, 0x64,
    ];
    fs::write(temp_dir.path().join("mixed.txt"), invalid_utf8)
        .expect("failed to write mixed encoding file");

    let config = YekConfig::extend_config_with_defaults(
        vec![temp_dir.path().to_string_lossy().to_string()],
        ".".to_string(),
    );
    let boosts: HashMap<String, i32> = HashMap::new();

    let result = process_files_parallel(temp_dir.path(), &config, &boosts)
        .expect("process_files_parallel failed");

    // File with mixed encoding should be processed with lossy conversion
    assert_eq!(result.len(), 1);
    assert!(result[0].content.contains("Hello"));
    assert!(result[0].content.contains("World"));
}

#[test]
fn test_process_files_parallel_with_symlink_loop() {
    #[cfg(unix)]
    {
        use std::os::unix::fs::symlink;

        let temp_dir = tempdir().expect("failed to create temp dir");
        let dir1 = temp_dir.path().join("dir1");
        let dir2 = temp_dir.path().join("dir2");

        fs::create_dir(&dir1).expect("failed to create dir1");
        fs::create_dir(&dir2).expect("failed to create dir2");

        // Create symlink loop
        symlink(&dir2, dir1.join("link_to_dir2")).expect("failed to create symlink");
        symlink(&dir1, dir2.join("link_to_dir1")).expect("failed to create symlink");

        // Add a file to process
        fs::write(dir1.join("file.txt"), "content").expect("failed to write file");

        let config = YekConfig::extend_config_with_defaults(
            vec![temp_dir.path().to_string_lossy().to_string()],
            ".".to_string(),
        );
        let boosts: HashMap<String, i32> = HashMap::new();

        let result = process_files_parallel(temp_dir.path(), &config, &boosts);

        // Should handle symlink loops gracefully (by not following symlinks)
        assert!(result.is_ok());
        let files = result.unwrap();
        // Should find the file exactly once
        assert_eq!(
            files
                .iter()
                .filter(|f| f.rel_path.ends_with("file.txt"))
                .count(),
            1
        );
    }
}

#[test]
fn test_process_files_parallel_with_channel_error_simulation() {
    // This test verifies the code handles channel errors gracefully
    // by processing a directory with many files
    let temp_dir = tempdir().expect("failed to create temp dir");

    // Create many files to stress the channel
    for i in 0..100 {
        fs::write(
            temp_dir.path().join(format!("file{}.txt", i)),
            format!("content{}", i),
        )
        .expect("failed to write file");
    }

    let config = YekConfig::extend_config_with_defaults(
        vec![temp_dir.path().to_string_lossy().to_string()],
        ".".to_string(),
    );
    let boosts: HashMap<String, i32> = HashMap::new();

    let result = process_files_parallel(temp_dir.path(), &config, &boosts);
    assert!(result.is_ok());
    let files = result.unwrap();
    assert_eq!(files.len(), 100);
}