luff 0.2.1

Print files with formatting
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
//! Directory walking and file iteration
//!
//! This module provides a unified interface for iterating over files,
//! supporting both directory walking and explicit file lists.

mod builder;
mod dir;
mod file_list;
mod output_guard;

use crate::{config::Config, error::Result};
use std::path::PathBuf;

pub use dir::DirectoryWalker;
pub use file_list::FileListWalker;

/// Entry representing a file or directory to be processed
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WalkerEntry {
    /// Absolute, canonical path to the file or directory
    pub path: PathBuf,
    /// Path relative to the root directory for display purposes
    pub relative_path: PathBuf,
    /// Whether this entry is a directory
    pub is_dir: bool,
}

/// Unified walker interface for directory or file list iteration
///
/// This enum provides a zero-cost abstraction over two walker types.
/// `DirectoryWalker` is boxed because it is large (~1KB due to ignore crate state),
/// while `FileListWalker` is small and embedded directly to avoid heap allocation.
pub enum Walker {
    /// Directory tree walker (boxed to reduce enum size)
    Directory(Box<DirectoryWalker>),
    /// Explicit file list walker (embedded, no extra allocation)
    FileList(FileListWalker),
}

impl std::fmt::Debug for Walker {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Directory(_) => f.debug_tuple("Walker::Directory").field(&"..").finish(),
            Self::FileList(w) => f
                .debug_tuple("Walker::FileList")
                .field(&format_args!("{} remaining", w.len()))
                .finish(),
        }
    }
}

impl Walker {
    /// Create a walker from a directory
    ///
    /// # Errors
    ///
    /// Returns an error if the directory walker cannot be initialized
    pub fn from_dir(config: &Config) -> Result<Self> {
        Ok(Self::Directory(Box::new(DirectoryWalker::new(config)?)))
    }

    /// Create a walker from a file list
    ///
    /// # Errors
    ///
    /// Returns an error if any file paths are invalid or inaccessible
    pub fn from_file_list(files: &[PathBuf], config: &Config) -> Result<Self> {
        Ok(Self::FileList(FileListWalker::new(files, config)?))
    }
}

/// Item yielded by the walker iterator
///
/// Separates successful entries from non-fatal errors for proper error surfacing
/// in streaming mode.
#[derive(Debug)]
pub enum WalkerItem {
    /// A valid file or directory entry
    Entry(WalkerEntry),
    /// A non-fatal walker error with structured diagnostic information
    Error(crate::error::Error),
}

impl From<WalkerEntry> for WalkerItem {
    fn from(entry: WalkerEntry) -> Self {
        Self::Entry(entry)
    }
}

impl From<crate::error::Error> for WalkerItem {
    fn from(error: crate::error::Error) -> Self {
        Self::Error(error)
    }
}

impl WalkerItem {
    /// Convenience method to extract Entry if present
    ///
    /// Returns `Some(WalkerEntry)` if this item is an Entry variant,
    /// `None` otherwise.
    #[must_use]
    pub fn into_entry(self) -> Option<WalkerEntry> {
        match self {
            Self::Entry(e) => Some(e),
            Self::Error(_) => None,
        }
    }

    /// Convenience method to extract Error if present
    ///
    /// Returns `Some(Error)` if this item is an Error variant,
    /// `None` otherwise.
    #[must_use]
    pub fn into_error(self) -> Option<crate::error::Error> {
        match self {
            Self::Entry(_) => None,
            Self::Error(e) => Some(e),
        }
    }
}

impl Iterator for Walker {
    type Item = WalkerItem;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            Self::Directory(walker) => walker.next(),
            Self::FileList(walker) => walker.next(),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        match self {
            Self::Directory(walker) => walker.size_hint(),
            Self::FileList(walker) => walker.size_hint(),
        }
    }
}

// Both `DirectoryWalker` and `FileListWalker` implement `FusedIterator`,
// so the composed enum inherits the guarantee: once `next()` returns
// `None`, all subsequent calls will also return `None`.
impl std::iter::FusedIterator for Walker {}

// NOTE: We deliberately do NOT implement ExactSizeIterator for Walker
// because DirectoryWalker is streaming and cannot know its exact size
// without traversing the entire directory. The size_hint provides a
// conservative upper bound based on max_files.

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

    #[test]
    fn test_walker_entry_creation() {
        let entry = WalkerEntry {
            path: PathBuf::from("/tmp/test.txt"),
            relative_path: PathBuf::from("test.txt"),
            is_dir: false,
        };

        assert_eq!(entry.path, PathBuf::from("/tmp/test.txt"));
        assert_eq!(entry.relative_path, PathBuf::from("test.txt"));
        assert!(!entry.is_dir);
    }

    #[test]
    fn test_walker_entry_directory() {
        let entry = WalkerEntry {
            path: PathBuf::from("/tmp/mydir"),
            relative_path: PathBuf::from("mydir"),
            is_dir: true,
        };

        assert!(entry.is_dir);
    }

    #[test]
    fn test_walker_entry_equality() {
        let a = WalkerEntry {
            path: PathBuf::from("/tmp/test.txt"),
            relative_path: PathBuf::from("test.txt"),
            is_dir: false,
        };
        let b = a.clone();
        assert_eq!(a, b);

        let c = WalkerEntry {
            path: PathBuf::from("/tmp/other.txt"),
            relative_path: PathBuf::from("other.txt"),
            is_dir: false,
        };
        assert_ne!(a, c);
    }

    #[test]
    fn test_walker_enum_size() {
        // Verify that the enum size is reasonable
        // DirectoryWalker is boxed (pointer size).
        // FileListWalker is a vec iterator (3 pointers) + PathBuf (3 pointers) -> ~48 bytes.
        // Discriminant + Padding.
        // Should be around 56-64 bytes. This is acceptable to avoid allocating the small variant.
        let size = std::mem::size_of::<Walker>();
        assert!(
            size < 200,
            "Walker enum should be reasonably small (got {size} bytes)"
        );
    }

    #[test]
    fn test_walker_item_from_entry() {
        let entry = WalkerEntry {
            path: PathBuf::from("/tmp/test.txt"),
            relative_path: PathBuf::from("test.txt"),
            is_dir: false,
        };
        let item: WalkerItem = entry.into();
        assert!(item.into_entry().is_some());
    }

    #[test]
    fn test_walker_item_from_error() {
        let error = crate::error::Error::Printer {
            message: "test".to_string(),
        };
        let item: WalkerItem = error.into();
        assert!(item.into_error().is_some());
    }

    #[test]
    fn test_walker_item_convenience_methods() {
        let entry = WalkerEntry {
            path: PathBuf::from("/tmp/test.txt"),
            relative_path: PathBuf::from("test.txt"),
            is_dir: false,
        };

        let item = WalkerItem::Entry(entry.clone());
        let entry_result = item.into_entry();
        assert!(entry_result.is_some());
        assert_eq!(entry_result.unwrap().path, entry.path);

        let item = WalkerItem::Entry(entry);
        let error_result = item.into_error();
        assert!(error_result.is_none());

        let item = WalkerItem::Error(crate::error::Error::Printer {
            message: "test error".to_string(),
        });
        let entry_result = item.into_entry();
        assert!(entry_result.is_none());

        let item = WalkerItem::Error(crate::error::Error::Printer {
            message: "test error".to_string(),
        });
        let error_result = item.into_error();
        assert!(error_result.is_some());
        match error_result.unwrap() {
            crate::error::Error::Printer { message } => assert_eq!(message, "test error"),
            _ => panic!("Expected Printer error"),
        }
    }

    #[test]
    fn test_walker_item_error_preserves_type() {
        // Verify that structured errors are preserved
        let io_error = crate::error::Error::Io(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "file not found",
        ));

        let item = WalkerItem::Error(io_error);
        let error = item.into_error().unwrap();

        match error {
            crate::error::Error::Io(e) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound),
            _ => panic!("Expected Io error variant"),
        }
    }

    #[test]
    fn test_walker_debug_output() {
        // Verify Debug impls don't panic and produce reasonable output
        let entry = WalkerEntry {
            path: PathBuf::from("/tmp/test.txt"),
            relative_path: PathBuf::from("test.txt"),
            is_dir: false,
        };

        let item = WalkerItem::Entry(entry);
        let debug_str = format!("{item:?}");
        assert!(
            debug_str.contains("Entry"),
            "WalkerItem::Entry debug should contain 'Entry'"
        );

        let item = WalkerItem::Error(crate::error::Error::Printer {
            message: "test".to_string(),
        });
        let debug_str = format!("{item:?}");
        assert!(
            debug_str.contains("Error"),
            "WalkerItem::Error debug should contain 'Error'"
        );
    }
}

#[cfg(test)]
#[cfg(feature = "cli")]
mod cli_tests {
    use super::*;
    use crate::cli::Args;
    use crate::config::Config;
    use crate::env::MockEnv;
    use clap::Parser;
    use serial_test::serial;
    use tempfile::TempDir;

    #[test]
    #[serial]
    fn test_walker_streams_items() {
        // Verify that Walker yields WalkerItem enum
        use std::env;

        let temp = TempDir::new().unwrap();
        env::set_current_dir(temp.path()).unwrap();

        let args = Args::parse_from(["test"]);
        let env = MockEnv::new();
        let config = Config::from_args_with_env(&args, &env).unwrap();
        let mut walker = Walker::from_dir(&config).unwrap();

        // Should compile - proves we're yielding WalkerItem
        let _item: Option<WalkerItem> = walker.next();
    }

    #[test]
    #[serial]
    fn test_walker_constructors() {
        let temp = TempDir::new().unwrap();
        let root = temp.path().canonicalize().unwrap();
        let env = MockEnv::new();

        // Just setup a basic config
        // We need to cheat a bit with current dir for the internal Config logic
        std::env::set_current_dir(&root).unwrap();
        let args = Args::parse_from(["luff"]);
        let config = Config::from_args_with_env(&args, &env).unwrap();

        // Test Directory variant
        let dir_walker = Walker::from_dir(&config);
        assert!(dir_walker.is_ok());
        assert!(matches!(dir_walker.unwrap(), Walker::Directory(_)));

        // Test FileList variant
        // Need a real file
        let file_path = root.join("test.txt");
        std::fs::write(&file_path, "content").unwrap();
        let files = vec![file_path];

        let list_walker = Walker::from_file_list(&files, &config);
        assert!(list_walker.is_ok());
        assert!(matches!(list_walker.unwrap(), Walker::FileList(_)));
    }

    #[test]
    #[serial]
    fn test_walker_debug_impls() {
        let temp = TempDir::new().unwrap();
        let root = temp.path().canonicalize().unwrap();
        let env = MockEnv::new();
        std::env::set_current_dir(&root).unwrap();

        let args = Args::parse_from(["luff"]);
        let config = Config::from_args_with_env(&args, &env).unwrap();

        let dir_walker = Walker::from_dir(&config).unwrap();
        let debug_str = format!("{dir_walker:?}");
        assert!(
            debug_str.contains("Directory"),
            "Walker::Directory debug should contain 'Directory', got: {debug_str}"
        );

        let file_path = root.join("test.txt");
        std::fs::write(&file_path, "content").unwrap();
        let list_walker =
            Walker::from_file_list(std::slice::from_ref(&file_path), &config).unwrap();
        let debug_str = format!("{list_walker:?}");
        assert!(
            debug_str.contains("FileList"),
            "Walker::FileList debug should contain 'FileList', got: {debug_str}"
        );
    }

    /// Regression test: ensure that a `Walker::from_dir` created against
    /// a specific temp directory only yields files from *that* directory,
    /// even when another temp directory exists.  This guards against
    /// global-state (cwd) bleed between tests.
    #[test]
    #[serial]
    fn test_walker_only_yields_files_from_its_root() {
        let temp = TempDir::new().unwrap();
        let root = temp.path().canonicalize().unwrap();
        std::env::set_current_dir(&root).unwrap();

        std::fs::write(root.join("expected.txt"), "content").unwrap();

        let args = Args::parse_from(["test"]);
        let env = MockEnv::new();
        let config = Config::from_args_with_env(&args, &env).unwrap();

        let walker = Walker::from_dir(&config).unwrap();
        let entries: Vec<WalkerEntry> = walker.filter_map(WalkerItem::into_entry).collect();

        let file_entries: Vec<_> = entries.iter().filter(|e| !e.is_dir).collect();

        assert_eq!(
            file_entries.len(),
            1,
            "Should yield exactly the one file we created"
        );
        assert_eq!(
            file_entries[0].relative_path,
            PathBuf::from("expected.txt"),
            "Should find our file, not a file from another test's directory"
        );
    }

    /// Verify that the `FusedIterator` contract holds through the `Walker`
    /// enum dispatch — once exhausted, `next()` must permanently return
    /// `None`.
    #[test]
    #[serial]
    fn test_walker_fused_through_enum() {
        let temp = TempDir::new().unwrap();
        let root = temp.path().canonicalize().unwrap();
        std::env::set_current_dir(&root).unwrap();

        std::fs::write(root.join("file.txt"), "content").unwrap();

        let args = Args::parse_from(["test"]);
        let env = MockEnv::new();
        let config = Config::from_args_with_env(&args, &env).unwrap();

        let mut walker = Walker::from_dir(&config).unwrap();

        // Exhaust
        while walker.next().is_some() {}

        // FusedIterator contract through enum dispatch
        assert!(walker.next().is_none());
        assert!(walker.next().is_none());
    }
}