dumpfiles 0.3.0

A CLI and library for generating structured YAML representations of directory contents, optimized for efficiently sharing codebases with LLMs.
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
extern crate dumpfiles;
extern crate tempfile;

use dumpfiles::{write_directory_contents_yaml, GitignoreMode};
use std::fs::{self, File};
use std::io::Write;
use std::path::Path;
use tempfile::tempdir;

/// Helper function to create a file with content
fn create_file(path: &Path, content: &str) -> std::io::Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    let mut file = File::create(path)?;
    file.write_all(content.as_bytes())?;
    Ok(())
}

/// Helper function to read and parse basic YAML structure
fn read_yaml_output(path: &Path) -> std::io::Result<String> {
    fs::read_to_string(path)
}

/// Helper to verify a file entry exists in the YAML output
fn assert_file_in_yaml(yaml_content: &str, file_path: &str, expected_content: Option<&str>) {
    assert!(
        yaml_content.contains(&format!("  - path: {:?}", file_path)),
        "Expected file '{}' not found in YAML output",
        file_path
    );

    if let Some(content) = expected_content {
        assert!(
            yaml_content.contains(content),
            "Expected content '{}' not found for file '{}'",
            content,
            file_path
        );
    }
}

/// Helper to verify a file is NOT in the YAML output
fn assert_file_not_in_yaml(yaml_content: &str, file_path: &str) {
    assert!(
        !yaml_content.contains(&format!("  - path: {:?}", file_path)),
        "File '{}' should not be in YAML output",
        file_path
    );
}

#[test]
fn test_basic_single_file() {
    let dir = tempdir().unwrap();
    let test_file = dir.path().join("test.txt");
    create_file(&test_file, "Hello, world!").unwrap();

    let output_path = dir.path().join("output.yaml");

    write_directory_contents_yaml(dir.path(), &output_path, &[], GitignoreMode::Auto, None)
        .unwrap();

    let output = read_yaml_output(&output_path).unwrap();

    // Check basic structure
    assert!(output.starts_with("project:"));
    assert!(output.contains("files:"));

    // Check file entry
    assert_file_in_yaml(&output, "test.txt", Some("Hello, world!"));
    assert!(output.contains("lines: 1"));
    assert!(output.contains("size: \"13 B\""));
}

#[test]
fn test_multiple_files() {
    let dir = tempdir().unwrap();
    create_file(&dir.path().join("file1.txt"), "Content 1").unwrap();
    create_file(&dir.path().join("file2.txt"), "Content 2").unwrap();
    create_file(&dir.path().join("file3.md"), "# Markdown").unwrap();

    let output_path = dir.path().join("output.yaml");

    write_directory_contents_yaml(dir.path(), &output_path, &[], GitignoreMode::Auto, None)
        .unwrap();

    let output = read_yaml_output(&output_path).unwrap();

    assert_file_in_yaml(&output, "file1.txt", Some("Content 1"));
    assert_file_in_yaml(&output, "file2.txt", Some("Content 2"));
    assert_file_in_yaml(&output, "file3.md", Some("# Markdown"));
}

#[test]
fn test_nested_directories() {
    let dir = tempdir().unwrap();
    create_file(&dir.path().join("root.txt"), "Root file").unwrap();
    create_file(&dir.path().join("subdir/nested.txt"), "Nested file").unwrap();
    create_file(&dir.path().join("subdir/deep/deeper.txt"), "Deep file").unwrap();

    let output_path = dir.path().join("output.yaml");

    write_directory_contents_yaml(dir.path(), &output_path, &[], GitignoreMode::Auto, None)
        .unwrap();

    let output = read_yaml_output(&output_path).unwrap();

    assert_file_in_yaml(&output, "root.txt", Some("Root file"));

    // Check paths use forward slashes even on Windows
    #[cfg(windows)]
    {
        assert_file_in_yaml(&output, "subdir/nested.txt", Some("Nested file"));
        assert_file_in_yaml(&output, "subdir/deep/deeper.txt", Some("Deep file"));
    }

    #[cfg(not(windows))]
    {
        assert_file_in_yaml(&output, "subdir/nested.txt", Some("Nested file"));
        assert_file_in_yaml(&output, "subdir/deep/deeper.txt", Some("Deep file"));
    }
}

#[test]
fn test_ignore_patterns_basic() {
    let dir = tempdir().unwrap();
    create_file(&dir.path().join("include.txt"), "Include me").unwrap();
    create_file(&dir.path().join("exclude.log"), "Exclude me").unwrap();
    create_file(&dir.path().join("test.tmp"), "Also exclude").unwrap();

    let output_path = dir.path().join("output.yaml");

    write_directory_contents_yaml(
        dir.path(),
        &output_path,
        &["*.log".to_string(), "*.tmp".to_string()],
        GitignoreMode::Auto,
        None,
    )
    .unwrap();

    let output = read_yaml_output(&output_path).unwrap();

    assert_file_in_yaml(&output, "include.txt", Some("Include me"));
    assert_file_not_in_yaml(&output, "exclude.log");
    assert_file_not_in_yaml(&output, "test.tmp");
}

#[test]
fn test_ignore_patterns_directories() {
    let dir = tempdir().unwrap();
    create_file(&dir.path().join("visible.txt"), "Visible").unwrap();
    create_file(&dir.path().join("node_modules/package.json"), "Package").unwrap();
    create_file(&dir.path().join("build/output.js"), "Built").unwrap();

    let output_path = dir.path().join("output.yaml");

    write_directory_contents_yaml(
        dir.path(),
        &output_path,
        &["node_modules/**".to_string(), "build/**".to_string()],
        GitignoreMode::Auto,
        None,
    )
    .unwrap();

    let output = read_yaml_output(&output_path).unwrap();

    assert_file_in_yaml(&output, "visible.txt", Some("Visible"));
    assert_file_not_in_yaml(&output, "node_modules/package.json");
    assert_file_not_in_yaml(&output, "build/output.js");
}

#[test]
fn test_empty_directory() {
    let dir = tempdir().unwrap();
    let output_path = dir.path().join("output.yaml");

    write_directory_contents_yaml(dir.path(), &output_path, &[], GitignoreMode::Auto, None)
        .unwrap();

    let output = read_yaml_output(&output_path).unwrap();

    // Build expected header exactly
    let project_name = dir
        .path()
        .canonicalize()
        .unwrap()
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();

    let expected = format!("project: {}\nfiles:\n", project_name);

    // Exact bytes match to catch formatting regressions
    assert_eq!(
        output, expected,
        "YAML header for empty directory should be exactly two lines"
    );

    // Redundant but explicit: ensure exactly two logical lines
    assert_eq!(output.lines().count(), 2);
}

#[test]
fn test_empty_file() {
    let dir = tempdir().unwrap();
    create_file(&dir.path().join("empty.txt"), "").unwrap();

    let output_path = dir.path().join("output.yaml");

    write_directory_contents_yaml(dir.path(), &output_path, &[], GitignoreMode::Auto, None)
        .unwrap();

    let output = read_yaml_output(&output_path).unwrap();

    assert_file_in_yaml(&output, "empty.txt", None);
    assert!(output.contains("lines: 0"));
    assert!(output.contains("size: \"0 B\""));
    assert!(output.contains("tokens: 0"));
}

#[test]
fn test_multiline_content() {
    let dir = tempdir().unwrap();
    let content = "Line 1\nLine 2\nLine 3\n\nLine 5 with spaces  ";
    create_file(&dir.path().join("multiline.txt"), content).unwrap();

    let output_path = dir.path().join("output.yaml");

    write_directory_contents_yaml(dir.path(), &output_path, &[], GitignoreMode::Auto, None)
        .unwrap();

    let output = read_yaml_output(&output_path).unwrap();

    assert_file_in_yaml(&output, "multiline.txt", None);
    assert!(output.contains("lines: 5"));
    assert!(output.contains("      Line 1"));
    assert!(output.contains("      Line 2"));
    assert!(output.contains("      Line 3"));
    assert!(output.contains("      Line 5 with spaces  "));
}

#[test]
fn test_special_characters_in_content() {
    let dir = tempdir().unwrap();
    let content = "Special: !@#$%^&*()\n\"Quotes\" and 'apostrophes'\nBackslash: \\ and pipe: |";
    create_file(&dir.path().join("special.txt"), content).unwrap();

    let output_path = dir.path().join("output.yaml");

    write_directory_contents_yaml(dir.path(), &output_path, &[], GitignoreMode::Auto, None)
        .unwrap();

    let output = read_yaml_output(&output_path).unwrap();

    assert_file_in_yaml(&output, "special.txt", None);
    assert!(output.contains("Special: !@#$%^&*()"));
    assert!(output.contains("\"Quotes\" and 'apostrophes'"));
    assert!(output.contains("Backslash: \\ and pipe: |"));
}

#[test]
fn test_file_size_formatting() {
    let dir = tempdir().unwrap();

    // Small file (bytes)
    create_file(&dir.path().join("small.txt"), "Hi").unwrap();

    // Larger file (KB)
    let large_content = "x".repeat(2048);
    create_file(&dir.path().join("large.txt"), &large_content).unwrap();

    let output_path = dir.path().join("output.yaml");

    write_directory_contents_yaml(dir.path(), &output_path, &[], GitignoreMode::Auto, None)
        .unwrap();

    let output = read_yaml_output(&output_path).unwrap();

    fn section_for<'a>(output: &'a str, filename: &'a str) -> &'a str {
        let start = output
            .find(&format!("path: {}", filename))
            .or_else(|| output.find(&format!("path: \"{}\"", filename)))
            .unwrap();
        let rest = &output[start..];
        // end at next file entry or EOF
        rest.split("\n  - path:").next().unwrap()
    }

    let small_section = section_for(&output, "small.txt");
    assert!(small_section.contains("size: \"2 B\"") || small_section.contains("size: 2 B"));
    assert!(output.contains("size: \"2.0 KB\"") || output.contains("size: 2.0 KB"));
}

#[test]
fn test_binary_file_handling() {
    let dir = tempdir().unwrap();

    // Create a binary file
    let binary_path = dir.path().join("binary.bin");
    let binary_data = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10]; // JPEG magic bytes
    fs::write(&binary_path, binary_data).unwrap();

    let output_path = dir.path().join("output.yaml");

    write_directory_contents_yaml(dir.path(), &output_path, &[], GitignoreMode::Auto, None)
        .unwrap();

    let output = read_yaml_output(&output_path).unwrap();

    assert_file_in_yaml(&output, "binary.bin", None);
    assert!(output.contains("Binary or inaccessible file"));
    assert!(output.contains("lines: 0"));
    assert!(output.contains("tokens: 0"));
}

#[test]
fn test_output_file_excluded() {
    let dir = tempdir().unwrap();
    create_file(&dir.path().join("test.txt"), "Test content").unwrap();

    // Create output file in the same directory being scanned
    let output_path = dir.path().join("output.yaml");

    write_directory_contents_yaml(dir.path(), &output_path, &[], GitignoreMode::Auto, None)
        .unwrap();

    let output = read_yaml_output(&output_path).unwrap();

    // Output file should not be included in its own contents
    assert_file_in_yaml(&output, "test.txt", Some("Test content"));
    assert_file_not_in_yaml(&output, "output.yaml");
}

#[test]
fn test_unicode_filenames_and_content() {
    let dir = tempdir().unwrap();
    create_file(&dir.path().join("日本語.txt"), "こんにちは").unwrap();
    create_file(&dir.path().join("emoji😀.txt"), "Hello 👋 World 🌍").unwrap();
    create_file(&dir.path().join("français.txt"), "Café résumé naïve").unwrap();

    let output_path = dir.path().join("output.yaml");

    write_directory_contents_yaml(dir.path(), &output_path, &[], GitignoreMode::Auto, None)
        .unwrap();

    let output = read_yaml_output(&output_path).unwrap();

    assert_file_in_yaml(&output, "日本語.txt", Some("こんにちは"));
    assert_file_in_yaml(&output, "emoji😀.txt", Some("Hello 👋 World 🌍"));
    assert_file_in_yaml(&output, "français.txt", Some("Café résumé naïve"));
}

#[test]
fn test_dumpignore_file() {
    let dir = tempdir().unwrap();
    create_file(&dir.path().join("include.txt"), "Include").unwrap();
    create_file(&dir.path().join("exclude.txt"), "Exclude").unwrap();
    create_file(&dir.path().join("also_exclude.log"), "Exclude log").unwrap();

    // Create .dumpignore file
    create_file(&dir.path().join(".dumpignore"), "exclude.txt\n*.log").unwrap();

    let output_path = dir.path().join("output.yaml");

    write_directory_contents_yaml(
        dir.path(),
        &output_path,
        &[],
        GitignoreMode::Auto,
        Some(&dir.path().join(".dumpignore")),
    )
    .unwrap();

    let output = read_yaml_output(&output_path).unwrap();

    assert_file_in_yaml(&output, "include.txt", Some("Include"));
    assert_file_not_in_yaml(&output, "exclude.txt");
    assert_file_not_in_yaml(&output, "also_exclude.log");
}

#[test]
fn test_token_counting() {
    let dir = tempdir().unwrap();

    // Create file with known content for token counting
    // "Hello, world!" typically tokenizes to a few tokens
    create_file(&dir.path().join("test.txt"), "Hello, world!").unwrap();

    let output_path = dir.path().join("output.yaml");

    write_directory_contents_yaml(dir.path(), &output_path, &[], GitignoreMode::Auto, None)
        .unwrap();

    let output = read_yaml_output(&output_path).unwrap();

    // Check that tokens field exists and is non-zero
    assert!(output.contains("tokens: "));

    // Extract token count to verify it's reasonable
    if let Some(token_line) = output.lines().find(|l| l.contains("tokens: ")) {
        let token_str = token_line.split("tokens: ").nth(1).unwrap();
        let token_count: usize = token_str.parse().unwrap();
        assert!(token_count > 0, "Token count should be greater than 0");
        assert!(
            token_count < 20,
            "Token count seems unreasonably high for 'Hello, world!'"
        );
    }
}

#[test]
fn test_project_name_from_directory() {
    let dir = tempdir().unwrap();
    let named_dir = dir.path().join("my_project");
    fs::create_dir_all(&named_dir).unwrap();
    create_file(&named_dir.join("file.txt"), "content").unwrap();

    let output_path = named_dir.join("output.yaml");

    write_directory_contents_yaml(&named_dir, &output_path, &[], GitignoreMode::Auto, None)
        .unwrap();

    let output = read_yaml_output(&output_path).unwrap();

    assert!(output.starts_with("project: my_project"));
}

#[test]
fn test_nonexistent_directory() {
    let dir = tempdir().unwrap();
    let nonexistent = dir.path().join("does_not_exist");
    let output_path = dir.path().join("output.yaml");

    let result =
        write_directory_contents_yaml(&nonexistent, &output_path, &[], GitignoreMode::Auto, None);

    assert!(result.is_err());
    assert!(result
        .unwrap_err()
        .to_string()
        .contains("Failed to get absolute path"));
}

#[test]
fn test_permission_denied() {
    // This test is platform-specific and may not work in all environments
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempdir().unwrap();
        let restricted_file = dir.path().join("restricted.txt");
        create_file(&restricted_file, "Secret").unwrap();

        // Remove read permissions
        let mut perms = fs::metadata(&restricted_file).unwrap().permissions();
        perms.set_mode(0o000);
        fs::set_permissions(&restricted_file, perms).unwrap();

        let output_path = dir.path().join("output.yaml");

        // This should still succeed, but the file will be marked as inaccessible
        let result =
            write_directory_contents_yaml(dir.path(), &output_path, &[], GitignoreMode::Auto, None);

        // Restore permissions for cleanup
        let mut perms = fs::metadata(&restricted_file).unwrap().permissions();
        perms.set_mode(0o644);
        fs::set_permissions(&restricted_file, perms).unwrap();

        assert!(result.is_ok());

        let output = read_yaml_output(&output_path).unwrap();
        assert!(output.contains("restricted.txt"));
        assert!(output.contains("Binary or inaccessible file"));
    }
}

#[test]
fn test_gitignore_on_off() {
    let dir = tempdir().unwrap();
    // Files: one that should be ignored by .gitignore, one that should be kept
    create_file(&dir.path().join("keep.txt"), "keep").unwrap();
    create_file(&dir.path().join("secret.log"), "top secret").unwrap();

    // Create a .gitignore that ignores *.log
    let gitignore_path = dir.path().join(".gitignore");
    create_file(&gitignore_path, "*.log\n").unwrap();

    // With .gitignore enabled via explicit path: *.log should be excluded
    let output_with = dir.path().join("with_gitignore.yaml");
    write_directory_contents_yaml(
        dir.path(),
        &output_with,
        &[],
        GitignoreMode::Path(gitignore_path),
        None,
    )
    .unwrap();

    let out_with = read_yaml_output(&output_with).unwrap();
    assert_file_in_yaml(&out_with, "keep.txt", Some("keep"));
    assert_file_not_in_yaml(&out_with, "secret.log");

    // With gitignore disabled (None): *.log should be included
    let output_without = dir.path().join("without_gitignore.yaml");
    write_directory_contents_yaml(
        dir.path(),
        &output_without,
        &[],
        GitignoreMode::Disabled,
        None,
    )
    .unwrap();

    let out_without = read_yaml_output(&output_without).unwrap();
    assert_file_in_yaml(&out_without, "keep.txt", Some("keep"));
    assert_file_in_yaml(&out_without, "secret.log", Some("top secret"));
}

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

        let dir = tempdir().unwrap();

        // Real file and a symlink to it
        create_file(&dir.path().join("target.txt"), "real file").unwrap();
        symlink(
            dir.path().join("target.txt"),
            dir.path().join("symlink.txt"),
        )
        .unwrap();

        // Real dir with a file and a symlinked dir pointing to it
        create_file(&dir.path().join("realdir/sub.txt"), "inside realdir").unwrap();
        symlink(dir.path().join("realdir"), dir.path().join("linkdir")).unwrap();

        let output_path = dir.path().join("output.yaml");
        write_directory_contents_yaml(dir.path(), &output_path, &[], GitignoreMode::Auto, None)
            .unwrap();

        let output = read_yaml_output(&output_path).unwrap();

        // We should include real files
        assert_file_in_yaml(&output, "target.txt", Some("real file"));
        assert_file_in_yaml(&output, "realdir/sub.txt", Some("inside realdir"));

        // but not include the file symlink itself
        assert_file_not_in_yaml(&output, "symlink.txt");

        // and not traverse the symlinked dir
        assert!(
            !output.contains("linkdir/"),
            "Should not traverse into symlinked directories (linkdir/*)"
        );
    }

    #[cfg(not(unix))]
    {
        eprintln!("symlink test skipped on non-Unix platforms");
    }
}