walkkit 0.1.3

Parallel filesystem walker with ignore-aware traversal and bounded work queues
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
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

use ignore::overrides::OverrideBuilder;
use ignore::WalkBuilder;

use super::{FileEntry, WalkConfig};
use crate::filter::{code_entry_allowed, code_process_path};

/// Slot used to propagate errors from the infallible `ignore::WalkBuilder::filter_entry` closure.
#[derive(Clone)]
pub(crate) struct FilterErrorSlot(Arc<Mutex<Option<crate::error::CodewalkError>>>);

impl FilterErrorSlot {
    fn new() -> Self {
        Self(Arc::new(Mutex::new(None)))
    }
    fn take(&self) -> Option<crate::error::CodewalkError> {
        self.0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take()
    }
    fn set(&self, err: crate::error::CodewalkError) {
        *self
            .0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(err);
    }
}

/// Iterator wrapper that surfaces errors stashed by `filter_entry`.
struct CodeWalkIter {
    inner: ignore::Walk,
    error_slot: FilterErrorSlot,
    buffered: Option<Result<ignore::DirEntry, ignore::Error>>,
    final_error_yielded: bool,
}

impl Iterator for CodeWalkIter {
    type Item = crate::error::Result<ignore::DirEntry>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.final_error_yielded {
            return None;
        }
        if let Some(buf) = self.buffered.take() {
            return Some(buf.map_err(crate::error::CodewalkError::Ignore));
        }
        match self.inner.next() {
            Some(res) => {
                if let Some(err) = self.error_slot.take() {
                    self.buffered = Some(res);
                    return Some(Err(err));
                }
                Some(res.map_err(crate::error::CodewalkError::Ignore))
            }
            None => {
                if let Some(err) = self.error_slot.take() {
                    self.final_error_yielded = true;
                    return Some(Err(err));
                }
                None
            }
        }
    }
}

/// File tree walker for codebase scanning.
pub struct CodeWalker {
    pub(crate) root: PathBuf,
    pub(crate) config: WalkConfig,
}

impl CodeWalker {
    /// Create a new walker rooted at the given path.
    pub fn new(root: impl Into<PathBuf>, config: WalkConfig) -> Self {
        Self {
            root: root.into(),
            config,
        }
    }

    /// Walk the tree, yielding file entries.
    ///
    /// # Errors
    /// Returns an error if directory traversal fails or a file cannot be processed.
    pub fn walk(&self) -> crate::error::Result<Vec<FileEntry>> {
        self.walk_iter().collect()
    }

    /// Walk the tree and return entries sorted by absolute path.
    ///
    /// # Errors
    /// Returns an error if directory traversal fails or a file cannot be processed.
    pub fn walk_sorted(&self) -> crate::error::Result<Vec<FileEntry>> {
        let mut entries = self.walk()?;
        entries.sort_by(|left, right| left.path.cmp(&right.path));
        Ok(entries)
    }

    /// Walk the tree as an iterator.
    pub fn walk_iter(&self) -> impl Iterator<Item = crate::error::Result<FileEntry>> + '_ {
        let config = Arc::new(self.config.clone());
        let (walker, error_slot) = self.build_walker_with_slot();
        CodeWalkIter {
            inner: walker,
            error_slot,
            buffered: None,
            final_error_yielded: false,
        }
        .filter_map(move |result| match result {
            Ok(entry) => match entry.file_type() {
                Some(ft) if ft.is_file() => {
                    match code_process_path(entry.path(), config.as_ref()) {
                        Ok(Some(file_entry)) => Some(Ok(file_entry)),
                        Ok(None) => None,
                        Err(err) => Some(Err(err)),
                    }
                }
                _ => None,
            },
            Err(err) => Some(Err(err)),
        })
    }

    /// Total number of files.
    ///
    /// # Performance
    /// This performs a full directory traversal that is independent from
    /// [`Self::walk`], so calling both `count()` and `walk()` on the same
    /// walker will visit the tree twice. For a single traversal that returns
    /// both the entries and the count, use [`Self::walk_and_count`].
    ///
    /// # Panics
    /// Panics if directory traversal or file processing fails. The old
    /// implementation discarded such errors via `filter_map(Result::ok)` and
    /// returned a silent undercount (Law 10); a count that quietly omits files
    /// an operator asked to enumerate is a correctness bug. Use
    /// [`Self::try_count`] for a fallible variant that returns the error.
    #[must_use]
    pub fn count(&self) -> usize {
        self.try_count().unwrap_or_else(|e| {
            panic!("CodeWalker::count: traversal failed: {e}; use try_count for a fallible variant")
        })
    }

    /// Total number of files, propagating traversal/processing errors.
    ///
    /// Unlike [`Self::walk_and_count`] this does not materialize the entries, so
    /// it counts without allocating a `Vec<FileEntry>`.
    ///
    /// # Errors
    /// Returns an error if directory traversal fails or a file cannot be
    /// processed, rather than silently undercounting.
    pub fn try_count(&self) -> crate::error::Result<usize> {
        let mut count = 0usize;
        for result in self.walk_iter() {
            result?;
            count += 1;
        }
        Ok(count)
    }

    /// Walk the tree once and return both the entries and the total count.
    ///
    /// # Errors
    /// Returns an error if directory traversal fails or a file cannot be processed.
    pub fn walk_and_count(&self) -> crate::error::Result<(Vec<FileEntry>, usize)> {
        let mut count = 0usize;
        let entries = self
            .walk_iter()
            .inspect(|result| {
                if result.is_ok() {
                    count += 1;
                }
            })
            .collect::<crate::error::Result<Vec<FileEntry>>>()?;
        Ok((entries, count))
    }

    pub(crate) fn build_walker_with_slot(&self) -> (ignore::Walk, FilterErrorSlot) {
        let error_slot = FilterErrorSlot::new();
        let mut builder = WalkBuilder::new(&self.root);
        builder
            .hidden(self.config.skip_hidden)
            .git_ignore(self.config.respect_gitignore)
            .git_global(self.config.respect_gitignore)
            .git_exclude(self.config.respect_gitignore)
            .follow_links(self.config.follow_symlinks);

        for ignore_file in &self.config.ignore_files {
            builder.add_custom_ignore_filename(ignore_file);
        }

        if !self.config.ignore_patterns.is_empty() {
            let mut ovr = OverrideBuilder::new(&self.root);
            for pattern in &self.config.ignore_patterns {
                if let Err(err) = ovr.add(pattern) {
                    tracing::warn!(pattern = %pattern, error = %err, "invalid ignore pattern");
                }
            }
            match ovr.build() {
                Ok(overrides) => {
                    builder.overrides(overrides);
                }
                Err(err) => {
                    tracing::warn!(error = %err, "failed to build ignore overrides");
                }
            }
        }

        let root = self.root.clone();
        let config = self.config.clone();
        let slot = error_slot.clone();
        builder.filter_entry(move |entry| {
            if entry.file_type().is_some_and(|ft| ft.is_dir()) {
                let name = entry.file_name().to_string_lossy();
                if config.exclude_dirs.contains(name.as_ref()) {
                    return false;
                }
            }
            match code_entry_allowed(entry.path(), &root, &config) {
                Ok(allowed) => allowed,
                Err(e) => {
                    slot.set(e);
                    false
                }
            }
        });
        (builder.build(), error_slot)
    }
}

impl IntoIterator for CodeWalker {
    type Item = crate::error::Result<FileEntry>;
    type IntoIter = Box<dyn Iterator<Item = crate::error::Result<FileEntry>>>;

    fn into_iter(self) -> Self::IntoIter {
        let config = Arc::new(self.config.clone());
        let (walker, error_slot) = self.build_walker_with_slot();
        Box::new(
            CodeWalkIter {
                inner: walker,
                error_slot,
                buffered: None,
                final_error_yielded: false,
            }
            .filter_map(move |result| match result {
                Ok(entry) => match entry.file_type() {
                    Some(ft) if ft.is_file() => {
                        match code_process_path(entry.path(), config.as_ref()) {
                            Ok(Some(file_entry)) => Some(Ok(file_entry)),
                            Ok(None) => None,
                            Err(err) => Some(Err(err)),
                        }
                    }
                    _ => None,
                },
                Err(err) => Some(Err(err)),
            }),
        )
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]
    use super::*;
    use crate::codewalker::test_utils::setup_test_dir;
    use std::fs;
    use std::path::Path;

    #[test]
    fn walks_directory() {
        let dir = setup_test_dir();
        let walker = CodeWalker::new(dir.path(), WalkConfig::default());
        let entries = walker.walk().unwrap();
        // Should find main.rs, lib.rs, src/app.py (not data.bin, not node_modules/)
        assert!(entries.len() >= 2);
        let paths: Vec<String> = entries
            .iter()
            .map(|e| e.path.file_name().unwrap().to_string_lossy().to_string())
            .collect();
        assert!(paths.contains(&"main.rs".to_string()));
        assert!(paths.contains(&"lib.rs".to_string()));
        assert!(!paths.contains(&"data.bin".to_string())); // binary skipped
        assert!(!paths.contains(&"junk.js".to_string())); // node_modules skipped
    }

    #[test]
    fn empty_directory() {
        let dir = tempfile::tempdir().unwrap();
        let walker = CodeWalker::new(dir.path(), WalkConfig::default());
        let entries = walker.walk().unwrap();
        assert!(entries.is_empty());
    }

    #[test]
    fn count_matches_walk() {
        let dir = setup_test_dir();
        let walker = CodeWalker::new(dir.path(), WalkConfig::default());
        let count = walker.count();
        let entries = walker.walk().unwrap();
        assert_eq!(count, entries.len());
    }

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

        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("public.txt"), "allowed").unwrap();

        let blocked_dir = dir.path().join("blocked");
        fs::create_dir(&blocked_dir).unwrap();
        fs::write(blocked_dir.join("secret.txt"), "secret").unwrap();

        let original_permissions = fs::metadata(&blocked_dir).unwrap().permissions();
        let mut blocked_permissions = original_permissions.clone();
        blocked_permissions.set_mode(0o000);
        fs::set_permissions(&blocked_dir, blocked_permissions).unwrap();

        // Root can traverse a 0o000 directory; only assert the loud behavior when
        // the subtree is genuinely unreadable for the running user.
        let reproducible = fs::read_dir(&blocked_dir).is_err();

        let walker = CodeWalker::new(dir.path(), WalkConfig::default());
        let try_count_result = walker.try_count();
        // count() must fail closed (panic) rather than silently return an undercount.
        let count_panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _ = walker.count();
        }))
        .is_err();

        let _ = fs::set_permissions(&blocked_dir, original_permissions);

        if reproducible {
            assert!(
                try_count_result.is_err(),
                "try_count must propagate the traversal error, got {try_count_result:?}"
            );
            assert!(
                count_panicked,
                "count() must fail loud on a traversal error, not return a silent undercount"
            );
        }
    }

    #[test]
    fn try_count_matches_walk_on_a_clean_tree() {
        let dir = setup_test_dir();
        let walker = CodeWalker::new(dir.path(), WalkConfig::default());
        let count = walker.try_count().unwrap();
        let entries = walker.walk().unwrap();
        assert_eq!(count, entries.len());
    }

    #[test]
    fn walk_and_count_single_pass() {
        let dir = setup_test_dir();
        let walker = CodeWalker::new(dir.path(), WalkConfig::default());
        let (entries, count) = walker.walk_and_count().unwrap();
        assert_eq!(count, entries.len());
    }

    #[test]
    fn walk_iter_collects_entries() {
        let dir = setup_test_dir();
        let walker = CodeWalker::new(dir.path(), WalkConfig::default());
        let entries: Vec<FileEntry> = walker.walk_iter().collect::<Result<Vec<_>, _>>().unwrap();
        let paths: Vec<&Path> = entries.iter().map(|entry| entry.path.as_path()).collect();
        assert!(paths.iter().any(|p| p.ends_with("main.rs")));
        assert!(paths.iter().any(|p| p.ends_with("lib.rs")));
        assert!(paths.iter().any(|p| p.ends_with("src/app.py")));
    }

    #[cfg(unix)]
    #[test]
    fn handles_non_utf8_filenames() {
        use std::ffi::OsString;
        use std::os::unix::ffi::OsStringExt;

        let dir = tempfile::tempdir().unwrap();
        let invalid_name = {
            let mut raw = b"bad-".to_vec();
            raw.extend_from_slice(b"\xffname.txt");
            OsString::from_vec(raw)
        };
        let path = dir.path().join(&invalid_name);
        fs::write(&path, "unicode").unwrap();

        let walker = CodeWalker::new(dir.path(), WalkConfig::default());
        let entries = walker.walk().unwrap();
        assert!(entries.iter().any(|entry| entry.path == path));
    }

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

        let dir = tempfile::tempdir().unwrap();
        let public_file = dir.path().join("public.txt");
        fs::write(&public_file, "allowed").unwrap();

        let blocked_dir = dir.path().join("blocked");
        fs::create_dir(&blocked_dir).unwrap();
        let blocked_file = blocked_dir.join("secret.txt");
        fs::write(&blocked_file, "secret").unwrap();

        let original_permissions = fs::metadata(&blocked_dir).unwrap().permissions();
        let mut blocked_permissions = original_permissions.clone();
        blocked_permissions.set_mode(0o000);
        fs::set_permissions(&blocked_dir, blocked_permissions).unwrap();

        let can_read_blocked_dir = fs::read_dir(&blocked_dir).is_ok();

        let results: Vec<_> = CodeWalker::new(dir.path(), WalkConfig::default())
            .walk_iter()
            .collect();
        let _ = fs::set_permissions(&blocked_dir, original_permissions);

        let entries: Vec<_> = results
            .iter()
            .filter_map(|result| result.as_ref().ok())
            .collect();
        assert!(entries.iter().any(|entry| entry.path == public_file));
        if !can_read_blocked_dir {
            assert!(!entries
                .iter()
                .any(|entry| entry.path.starts_with(&blocked_dir)));
        }
    }
}