swdir 0.11.2

Swiftly traverse and scan directories recursively. Sway 🪭, swing 🎷 or swim 🪼 in directories.
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
//! Integration tests for the high-level [`swdir::Swdir`] / walk API.
//!
//! Organized by product-contract section, not by implementation
//! boundary. Keeping this as a single binary — rather than a
//! `tests/walk/` directory — reflects the cohesion of the walk API:
//! it's one builder and one `walk()` method, and the sections below
//! are just facets of that single surface.
//!
//! * Defaults & the default-`SkipHidden` contract
//! * Recurse policy
//! * FilterRule composition (default on: the `filter` feature gates this file)
//! * Decision axes (include vs descend)
//! * MaxDepth filter
//! * WalkReport — errors collected, not printed
//! * Flatten / count helpers on DirNode
//! * SortOrder
//!
//! If a new walk test needs temp-directory fixtures, add
//! `#[path = "common/mod.rs"] mod common;` the same way `scan_dir.rs`
//! does. Today's walk tests only touch the checked-in `tests/fixtures/`
//! tree, so the helper isn't loaded here.

#![cfg(feature = "filter")]

use std::path::PathBuf;

use swdir::{
    Decision, DirNodeCount, EntryKind, FilterRule, Recurse, SortOrder, Swdir, SwdirError,
    WalkReport,
};

// ---------------------------------------------------------------------------
// Defaults & the "SkipHidden is on by default" contract
// ---------------------------------------------------------------------------

#[test]
fn walk_current_directory_ok() {
    let report = Swdir::new().root_path(".").walk();
    assert_eq!(report.tree.path, std::path::Path::new(".").to_path_buf());
}

#[test]
fn default_skip_hidden_is_installed() {
    // `Swdir::new()` must ship a single SkipHidden rule so the common
    // case is one line.
    let s = Swdir::new();
    let rules = s.filter_rules();
    assert_eq!(rules.len(), 1);
    assert_eq!(rules[0], FilterRule::SkipHidden);
}

#[test]
fn walk_not_recurse_ok() {
    let report = Swdir::new().root_path("tests/fixtures").walk();
    assert_eq!(
        report.tree.files.as_slice(),
        &[
            PathBuf::from("tests/fixtures/test"),
            PathBuf::from("tests/fixtures/test.md"),
            PathBuf::from("tests/fixtures/test.txt"),
        ]
    );
    // No recursion → no sub_dirs.
    assert!(report.tree.sub_dirs.is_empty());
}

#[test]
fn walk_default_skips_hidden() {
    // Fixture has .hidden-file and .hidden-dir at root; default must drop them.
    let report = Swdir::new()
        .root_path("tests/fixtures")
        .recurse(Recurse::Depth(1))
        .walk();
    assert_eq!(
        report.tree.files.as_slice(),
        &[
            PathBuf::from("tests/fixtures/test"),
            PathBuf::from("tests/fixtures/test.md"),
            PathBuf::from("tests/fixtures/test.txt"),
        ]
    );
    // Only the visible subdir should be present.
    assert_eq!(report.tree.sub_dirs.len(), 1);
    assert_eq!(
        report.tree.sub_dirs[0].files.as_slice(),
        &[PathBuf::from("tests/fixtures/subdir/subdir.txt")]
    );
}

#[test]
fn clear_filters_exposes_hidden() {
    // 0.9 had `include_hidden()`; the 0.10 equivalent is "drop the default rule".
    let report = Swdir::new()
        .root_path("tests/fixtures")
        .recurse(Recurse::Depth(1))
        .clear_filters()
        .walk();
    assert_eq!(
        report.tree.files.as_slice(),
        &[
            PathBuf::from("tests/fixtures/.hidden-file"),
            PathBuf::from("tests/fixtures/test"),
            PathBuf::from("tests/fixtures/test.md"),
            PathBuf::from("tests/fixtures/test.txt"),
        ]
    );
    // Both .hidden-dir and subdir are present, sorted by path.
    assert_eq!(report.tree.sub_dirs.len(), 2);
    assert_eq!(
        report.tree.sub_dirs[0].files.as_slice(),
        &[PathBuf::from("tests/fixtures/.hidden-dir/dummy")]
    );
    assert_eq!(
        report.tree.sub_dirs[1].files.as_slice(),
        &[PathBuf::from("tests/fixtures/subdir/subdir.txt")]
    );
}

// ---------------------------------------------------------------------------
// Recurse — enum replaces 0.9's two-field struct; cover every variant.
// ---------------------------------------------------------------------------

#[test]
fn recurse_none_leaves_sub_dirs_empty() {
    let report = Swdir::new()
        .root_path("tests/fixtures")
        .recurse(Recurse::None)
        .walk();
    assert!(report.tree.sub_dirs.is_empty());
    assert_eq!(report.tree.files.len(), 3);
}

#[test]
fn recurse_depth_0_is_root_only() {
    // Depth(0) matches 0.9's depth_limit = Some(0): no descent at all.
    let report = Swdir::new()
        .root_path("tests/fixtures")
        .recurse(Recurse::Depth(0))
        .walk();
    assert_eq!(
        report.tree.files.as_slice(),
        &[
            PathBuf::from("tests/fixtures/test"),
            PathBuf::from("tests/fixtures/test.md"),
            PathBuf::from("tests/fixtures/test.txt"),
        ]
    );
    assert!(report.tree.sub_dirs.is_empty());
}

#[test]
fn recurse_depth_1_reaches_first_level() {
    let report = Swdir::new()
        .root_path("tests/fixtures")
        .recurse(Recurse::Depth(1))
        .walk();
    assert_eq!(
        report.tree.sub_dirs[0].files.as_slice(),
        &[PathBuf::from("tests/fixtures/subdir/subdir.txt")]
    );
}

#[test]
fn recurse_unlimited_descends_whole_tree() {
    // fixtures is shallow so Depth(1) and Unlimited agree here; we just
    // confirm Unlimited doesn't bail early.
    let report = Swdir::new()
        .root_path("tests/fixtures")
        .recurse(Recurse::Unlimited)
        .walk();
    assert_eq!(report.tree.sub_dirs.len(), 1);
    assert_eq!(
        report.tree.sub_dirs[0].files.as_slice(),
        &[PathBuf::from("tests/fixtures/subdir/subdir.txt")]
    );
}

// ---------------------------------------------------------------------------
// FilterRule composition — the 0.10 unified filter model.
// ---------------------------------------------------------------------------

#[test]
fn extension_allowlist_rule_ok() {
    let report = Swdir::new()
        .root_path("tests/fixtures")
        .filter(FilterRule::extension_allowlist(["md"]).unwrap())
        .walk();
    assert_eq!(
        report.tree.files.as_slice(),
        &[PathBuf::from("tests/fixtures/test.md")]
    );
}

#[test]
fn extension_denylist_rule_ok() {
    let report = Swdir::new()
        .root_path("tests/fixtures")
        .filter(FilterRule::extension_denylist(["md"]).unwrap())
        .walk();
    // `test` has no extension → passes denylist.
    assert_eq!(
        report.tree.files.as_slice(),
        &[
            PathBuf::from("tests/fixtures/test"),
            PathBuf::from("tests/fixtures/test.txt"),
        ]
    );
}

#[test]
fn extension_allowlist_and_denylist_stack_freely() {
    // 0.9's `DuplicateExtensionList` error is gone — rules AND, so giving
    // both an allow and a deny for different extensions is sensible and
    // must not error.
    let s = Swdir::new()
        .root_path("tests/fixtures")
        .filter(FilterRule::extension_allowlist(["md", "txt"]).unwrap())
        .filter(FilterRule::extension_denylist(["md"]).unwrap());
    let report = s.walk();
    assert_eq!(
        report.tree.files.as_slice(),
        &[PathBuf::from("tests/fixtures/test.txt")]
    );
}

#[test]
fn allowlist_rejects_leading_period() {
    let err = FilterRule::extension_allowlist([".md"]).unwrap_err();
    assert_eq!(err, SwdirError::InvalidExtensionListItem(".md".to_owned()));
}

#[test]
fn denylist_rejects_leading_period() {
    let err = FilterRule::extension_denylist([".md"]).unwrap_err();
    assert_eq!(err, SwdirError::InvalidExtensionListItem(".md".to_owned()));
}

// ---------------------------------------------------------------------------
// Decision — the include / descend split.
// ---------------------------------------------------------------------------

#[test]
fn decision_constants_are_sensible() {
    assert_eq!(Decision::PASS, Decision::new(true, true));
    assert_eq!(Decision::DROP, Decision::new(false, false));
    assert_eq!(Decision::HIDDEN_PASSTHROUGH, Decision::new(false, true));
}

#[test]
fn only_kinds_file_still_reaches_nested_files() {
    // Proof-of-contract for the "include and descend are separate" rule:
    // OnlyKinds(File) hides directories from output but still descends
    // into them so nested files remain reachable.
    let report = Swdir::new()
        .root_path("tests/fixtures")
        .recurse(Recurse::Unlimited)
        .filter(FilterRule::only_kind(EntryKind::File))
        .walk();

    let flat = report.tree.flatten_paths();
    assert!(
        flat.contains(&PathBuf::from("tests/fixtures/subdir/subdir.txt")),
        "nested file should still be reached: got {:?}",
        flat
    );
}

// ---------------------------------------------------------------------------
// MaxDepth filter — the depth-aware variant of Recurse::Depth.
// ---------------------------------------------------------------------------

#[test]
fn max_depth_filter_zero_drops_nested() {
    // MaxDepth(0) should match Recurse::None behavior: only root-level entries.
    let report = Swdir::new()
        .root_path("tests/fixtures")
        .recurse(Recurse::Unlimited)
        .filter(FilterRule::max_depth(0))
        .walk();

    let flat = report.tree.flatten_paths();
    // No entries under subdir/ should appear.
    for p in &flat {
        assert!(
            !p.to_string_lossy().contains("subdir/"),
            "unexpected nested path: {:?}",
            p
        );
    }
}

// ---------------------------------------------------------------------------
// WalkReport — errors are collected, not printed to stderr.
// ---------------------------------------------------------------------------

#[test]
fn walk_missing_root_records_error_not_panic() {
    let report = Swdir::new()
        .root_path("/definitely/does/not/exist/swdir-xyz-123")
        .walk();
    assert!(!report.is_ok(), "missing root must populate errors");
    assert_eq!(report.errors.len(), 1);
    assert_eq!(
        report.errors[0].io_kind(),
        std::io::ErrorKind::NotFound,
        "kind = {:?}",
        report.errors[0].io_kind()
    );
}

#[test]
fn walk_ok_fixture_has_no_errors() {
    let report: WalkReport = Swdir::new().root_path("tests/fixtures").walk();
    assert!(report.is_ok(), "unexpected errors: {:?}", report.errors);
}

#[test]
fn walk_tree_discards_errors() {
    // `walk_tree()` is the "I don't care about errors" shortcut.
    let tree = Swdir::new().root_path("tests/fixtures").walk_tree();
    assert_eq!(tree.path, PathBuf::from("tests/fixtures"));
}

// ---------------------------------------------------------------------------
// Flatten / count — DirNode helpers, routed via WalkReport.
// ---------------------------------------------------------------------------

#[test]
fn flatten_paths_not_recurse_ok() {
    let report = Swdir::new().root_path("tests/fixtures").walk();
    let flat = report.tree.flatten_paths();
    assert_eq!(
        flat,
        vec![
            PathBuf::from("tests/fixtures/test"),
            PathBuf::from("tests/fixtures/test.md"),
            PathBuf::from("tests/fixtures/test.txt"),
        ]
    );
}

#[test]
fn flatten_paths_recurse_ok() {
    let report = Swdir::new()
        .root_path("tests/fixtures")
        .recurse(Recurse::Depth(1))
        .walk();
    let flat = report.tree.flatten_paths();
    assert_eq!(
        flat,
        vec![
            PathBuf::from("tests/fixtures/test"),
            PathBuf::from("tests/fixtures/test.md"),
            PathBuf::from("tests/fixtures/test.txt"),
            PathBuf::from("tests/fixtures/subdir/subdir.txt"),
        ]
    );
}

#[test]
fn count_root_only_ok() {
    let report = Swdir::new().root_path("tests/fixtures").walk();
    let count = report.tree.count();
    assert_eq!(count, DirNodeCount { files: 3, dirs: 1 });
}

#[test]
fn count_sub_dir_included_ok() {
    let report = Swdir::new()
        .root_path("tests/fixtures")
        .recurse(Recurse::Depth(1))
        .walk();
    let count = report.tree.count();
    assert_eq!(count, DirNodeCount { files: 4, dirs: 2 });
}

// ---------------------------------------------------------------------------
// SortOrder — 0.11 walk-level ordering contract.
// ---------------------------------------------------------------------------

#[test]
fn sort_order_default_is_name_asc_dirs_first() {
    // Default must be NameAscDirsFirst so GUI callers get reproducible
    // output out of the box, matching 0.10's behavior.
    let s = Swdir::new();
    assert_eq!(s.sort_order_policy(), SortOrder::NameAscDirsFirst);
}

#[test]
fn sort_order_name_asc_dirs_first_is_reproducible() {
    // Running the same scan twice under NameAscDirsFirst must produce
    // byte-identical trees — the core reproducibility guarantee for
    // GUI widgets.
    let build = || {
        Swdir::new()
            .root_path("tests/fixtures")
            .recurse(Recurse::Depth(1))
            .sort_order(SortOrder::NameAscDirsFirst)
            .walk_tree()
    };
    let a = build();
    let b = build();
    assert_eq!(a.flatten_paths(), b.flatten_paths());

    // And the order must actually be name-ascending within each bucket.
    assert_eq!(
        a.files,
        vec![
            PathBuf::from("tests/fixtures/test"),
            PathBuf::from("tests/fixtures/test.md"),
            PathBuf::from("tests/fixtures/test.txt"),
        ],
        "files must be name-ascending"
    );
}

#[test]
fn sort_order_filesystem_preserves_os_order() {
    // We can't assert any specific OS order — that's the point of
    // Filesystem — but we can assert the result set is the same as
    // under NameAscDirsFirst (just possibly permuted).
    use std::collections::BTreeSet;

    let fs_tree = Swdir::new()
        .root_path("tests/fixtures")
        .recurse(Recurse::Depth(1))
        .sort_order(SortOrder::Filesystem)
        .walk_tree();
    let name_tree = Swdir::new()
        .root_path("tests/fixtures")
        .recurse(Recurse::Depth(1))
        .sort_order(SortOrder::NameAscDirsFirst)
        .walk_tree();

    let fs_set: BTreeSet<_> = fs_tree.flatten_paths().into_iter().collect();
    let name_set: BTreeSet<_> = name_tree.flatten_paths().into_iter().collect();
    assert_eq!(fs_set, name_set);
}