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
//! Common utilities shared between traverse and tree modules.
//!
//! This module provides shared functionality for directory traversal operations.
use ;
use globset;
use WalkBuilder;
use ;
use crate;
/// Checks if a path matches any of the provided glob patterns.
///
/// This function is useful for filtering files based on glob patterns.
/// It supports standard glob syntax including wildcards, character classes, and brace expansion.
///
/// ## Path Type Expectations
///
/// This function can work with both absolute and relative paths, but for consistency across
/// the codebase, it's recommended to use **relative paths** when possible. Most callers in
/// this codebase convert absolute paths to relative paths using `path.strip_prefix(directory)`
/// before calling this function to ensure predictable pattern matching behavior.
///
/// # Arguments
///
/// * `path` - The file path to check (can be absolute or relative, but relative is recommended)
/// * `glob_patterns` - A slice of glob patterns to match against
/// * `case_sensitive` - Whether the glob matching should be case sensitive
///
/// # Returns
///
/// `true` if the path matches any of the provided patterns, `false` otherwise
///
/// # Errors
///
/// Returns an error if there's an issue compiling the glob patterns
///
/// # Examples
///
/// ```no_run
/// use anyhow::Result;
/// use lumin::traverse::common::path_matches_any_glob;
/// use std::path::Path;
///
/// fn is_source_file(path: &Path) -> Result<bool> {
/// let patterns = vec!["**/*.rs".to_string(), "**/*.toml".to_string()];
/// path_matches_any_glob(path, &patterns, false)
/// }
/// ```
/// Builds a configured file system walker based on the provided options.
///
/// # Arguments
///
/// * `directory` - The directory path to traverse
/// * `respect_gitignore` - Whether to respect gitignore rules
/// * `case_sensitive` - Whether file path matching should be case sensitive
/// * `max_depth` - Optional maximum directory depth to traverse
///
/// # Returns
///
/// A configured WalkBuilder for traversing the file system
///
/// # Errors
///
/// Returns an error if there's an issue setting up the walker
/// Determines if a path is hidden (starts with a dot or is in a hidden directory).
///
/// # Arguments
///
/// * `path` - The path to check
///
/// # Returns
///
/// `true` if the path is hidden, `false` otherwise
/// Traverses a directory and collects results using a callback function.
///
/// This generic function applies gitignore filtering and exclude_glob filtering based on the provided options,
/// and uses a callback to process each valid file entry, accumulating results of any type.
/// It uses the `try_fold` method for efficient traversal and result accumulation.
///
/// ## Path Matching Behavior
///
/// **Important**: Glob patterns in `exclude_glob` are matched against paths that are **relative to the directory**.
/// This ensures consistent behavior with other parts of the codebase (search module's `include_glob` and `exclude_glob`,
/// traverse module's `pattern` field) and makes patterns predictable.
///
/// For example, when traversing `/home/user/project`:
/// - A file at `/home/user/project/src/main.rs` is matched against the relative path `src/main.rs`
/// - Pattern `**/*.rs` will match all Rust files in any subdirectory
/// - Pattern `src/**` will match all files in the src directory
///
/// # Type Parameters
///
/// * `T` - The type of the accumulated result
/// * `F` - The type of the callback function that processes each file
///
/// # Arguments
///
/// * `directory` - The directory path to traverse
/// * `respect_gitignore` - Whether to respect gitignore rules
/// * `case_sensitive` - Whether file path matching should be case sensitive
/// * `max_depth` - Optional maximum directory depth to traverse
/// * `exclude_glob` - Optional list of glob patterns to exclude files from the results (uses relative paths)
/// * `initial` - The initial value for the result accumulator
/// * `callback` - A function that processes each entry and updates the accumulator. This function
/// should take two parameters: the current accumulator value and a reference to the file path,
/// and return a Result containing the updated accumulator value.
///
/// # Returns
///
/// The accumulated result of type T after processing all relevant files
///
/// # Errors
///
/// Returns an error if there's an issue accessing the directory or files, or if there's an error
/// compiling the exclude glob patterns, or if the callback returns an error
///
/// # Examples
///
/// Collecting file paths as strings:
/// ```no_run
/// use anyhow::Result;
/// use lumin::traverse::common::traverse_with_callback;
/// use std::path::Path;
///
/// fn collect_file_names(dir: &Path) -> Result<Vec<String>> {
/// traverse_with_callback(
/// dir,
/// true, // respect_gitignore
/// false, // case_sensitive
/// Some(20), // max_depth
/// None, // exclude_glob
/// Vec::new(),
/// |mut names, path| {
/// if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
/// names.push(name.to_string());
/// }
/// Ok(names)
/// }
/// )
/// }
/// ```
///
/// Counting lines in all non-binary files:
/// ```no_run
/// use anyhow::{Context, Result};
/// use lumin::traverse::common::traverse_with_callback;
/// use std::fs::File;
/// use std::io::{BufRead, BufReader};
/// use std::path::Path;
///
/// fn count_lines(dir: &Path) -> Result<usize> {
/// traverse_with_callback(
/// dir,
/// true, // respect_gitignore
/// false, // case_sensitive
/// None, // max_depth (no limit)
/// Some(&vec!["*.bin".to_string(), "*.jpg".to_string()]),
/// 0,
/// |count, path| {
/// let file = File::open(path)
/// .with_context(|| format!("Failed to open {}", path.display()))?;
/// let reader = BufReader::new(file);
/// let lines = reader.lines().count();
/// Ok(count + lines)
/// }
/// )
/// }
/// ```
/// Collects a list of files within the given directory, with support for exclude glob patterns.
///
/// This function applies gitignore filtering and exclude_glob filtering based on the provided options.
/// It's implemented as a specialization of the more generic `traverse_with_callback` function,
/// providing a simpler interface for the common case of just collecting file paths.
///
/// ## Path Matching Behavior
///
/// **Important**: Glob patterns in `exclude_glob` are matched against paths that are **relative to the directory**.
/// This ensures consistent behavior with other parts of the codebase (search module's `include_glob` and `exclude_glob`,
/// traverse module's `pattern` field) and makes patterns predictable.
///
/// For example, when collecting files in `/home/user/project`:
/// - A file at `/home/user/project/src/main.rs` is matched against the relative path `src/main.rs`
/// - Pattern `**/*.rs` will match all Rust files in any subdirectory
/// - Pattern `src/**` will match all files in the src directory
///
/// # Arguments
///
/// * `directory` - The directory path to collect files from
/// * `respect_gitignore` - Whether to respect gitignore rules
/// * `case_sensitive` - Whether file path matching should be case sensitive
/// * `max_depth` - Optional maximum directory depth to traverse
/// * `exclude_glob` - Optional list of glob patterns to exclude files from the results (uses relative paths)
///
/// # Returns
///
/// A vector of file paths to be searched
///
/// # Errors
///
/// Returns an error if there's an issue accessing the directory or files, or if there's an error
/// compiling the exclude glob patterns
///
/// # Examples
///
/// Basic usage:
/// ```no_run
/// use anyhow::Result;
/// use lumin::traverse::common::collect_files_with_excludes;
/// use std::path::Path;
///
/// fn find_files(dir: &Path) -> Result<Vec<std::path::PathBuf>> {
/// // Find all files, respecting gitignore, case-insensitive, with default depth
/// collect_files_with_excludes(dir, true, false, Some(20), None)
/// }
/// ```
///
/// With exclude patterns:
/// ```no_run
/// use anyhow::Result;
/// use lumin::traverse::common::collect_files_with_excludes;
/// use std::path::Path;
///
/// fn find_source_files(dir: &Path) -> Result<Vec<std::path::PathBuf>> {
/// // Find all files except build outputs and test files, limit to 5 levels deep
/// let excludes = vec![
/// "**/target/**".to_string(),
/// "**/*.test.*".to_string(),
/// "**/*_test.*".to_string(),
/// ];
///
/// collect_files_with_excludes(dir, true, false, Some(5), Some(&excludes))
/// }
/// ```