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
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
//! Configuration management with layered sources (CLI > Env > Config File > Defaults)

mod file;
mod patterns;

use crate::{
    format::OutputFormat,
    printer::{PrinterOptions, SkipPatterns},
};
use std::path::{Path, PathBuf};

#[cfg(feature = "cli")]
use crate::{
    cli::Args,
    env::{EnvProvider, RealEnv},
    error::{Error, Result},
};
#[cfg(feature = "cli")]
use figment::{
    Figment, Metadata, Profile, Provider,
    providers::Serialized,
    value::{Dict, Map, Value},
};

pub use file::{CliOverride, ConfigFile, ConfigFormat, ValidatedConfig, load_config_file};
pub use patterns::IgnorePatterns;

/// Figment [`Provider`] that reads `LUFF_*` environment variables through
/// our [`EnvProvider`] trait, enabling test isolation.
///
/// This replaces `figment::providers::Env::prefixed("LUFF_")` so that
/// `from_args_with_env` genuinely honours the injected environment.
///
/// ## Supported variables
///
/// - `LUFF_INCLUDE_DOTFILES` (bool)
/// - `LUFF_RESPECT_GITIGNORE` (bool)
/// - `LUFF_FORMAT` (string: "markdown" or "tree")
/// - `LUFF_MAX_DEPTH` (u64)
/// - `LUFF_MAX_FILES` (u64)
/// - `LUFF_MAX_CLIPBOARD_MB` (u64)
///
/// Pattern lists (`ignore_extensions`, `ignore_directories`,
/// `ignore_files`, `ignore_globs`) are intentionally **not** exposed as
/// env vars — comma-separated list parsing in env vars is ambiguous and
/// error-prone.  Use a config file for custom patterns.
///
/// ## Parse failures
///
/// Malformed values (e.g. `LUFF_MAX_DEPTH=abc`) are logged at `warn`
/// level and ignored, so the next layer down in the precedence chain
/// takes effect.  This avoids hard-failing on a stray env var while
/// still giving the user a diagnostic when something looks wrong.
#[cfg(feature = "cli")]
struct EnvOverrides<'a> {
    /// The environment provider used to resolve `LUFF_*` variables
    env: &'a dyn EnvProvider,
}

#[cfg(feature = "cli")]
impl EnvOverrides<'_> {
    /// Try to parse a boolean env var, warning on malformed values.
    fn parse_bool(&self, key: &str) -> Option<bool> {
        let val = self.env.var(key)?;
        val.parse::<bool>().map_or_else(
            |_| {
                log::warn!(
                    "Ignoring environment variable {key}={val:?}: expected \"true\" or \"false\""
                );
                None
            },
            Some,
        )
    }

    /// Try to parse a `u64` env var, warning on malformed values.
    fn parse_u64(&self, key: &str) -> Option<u64> {
        let val = self.env.var(key)?;
        val.parse::<u64>().map_or_else(
            |_| {
                log::warn!(
                    "Ignoring environment variable {key}={val:?}: expected a non-negative integer"
                );
                None
            },
            Some,
        )
    }
}

#[cfg(feature = "cli")]
impl Provider for EnvOverrides<'_> {
    fn metadata(&self) -> Metadata {
        Metadata::named("environment (LUFF_*)")
    }

    fn data(&self) -> std::result::Result<Map<Profile, Dict>, figment::Error> {
        let mut dict = Dict::new();

        if let Some(b) = self.parse_bool("LUFF_INCLUDE_DOTFILES") {
            let _ = dict.insert("include_dotfiles".into(), Value::from(b));
        }

        if let Some(b) = self.parse_bool("LUFF_RESPECT_GITIGNORE") {
            let _ = dict.insert("respect_gitignore".into(), Value::from(b));
        }

        // Format is a free-form string validated downstream by Figment/serde.
        if let Some(val) = self.env.var("LUFF_FORMAT") {
            let _ = dict.insert("format".into(), Value::from(val));
        }

        if let Some(n) = self.parse_u64("LUFF_MAX_DEPTH") {
            let _ = dict.insert("max_depth".into(), Value::from(n));
        }

        if let Some(n) = self.parse_u64("LUFF_MAX_FILES") {
            let _ = dict.insert("max_files".into(), Value::from(n));
        }

        if let Some(n) = self.parse_u64("LUFF_MAX_CLIPBOARD_MB") {
            let _ = dict.insert("max_clipboard_mb".into(), Value::from(n));
        }

        Ok(Profile::Default.collect(dict))
    }
}

/// Main configuration for luff operations
///
/// Owns a [`ValidatedConfig`] for all settings that come through the
/// config-file / env / CLI pipeline, plus the few fields that are
/// derived outside that pipeline (`root`, `skip_patterns`).
///
/// `max_clipboard_bytes` is computed on access from the validated
/// `max_clipboard_mb` value rather than stored, eliminating a class
/// of stale-cache bugs.
#[derive(Debug, Clone)]
pub struct Config {
    /// Validated configuration from the layered provider chain
    validated: ValidatedConfig,
    /// Root directory for all file operations (absolute path)
    root: PathBuf,
    /// Whether to apply pattern-based filtering (disabled for explicit file lists)
    skip_patterns: SkipPatterns,
}

impl Config {
    /// Create a new configuration from CLI arguments with config file support
    ///
    /// Uses the real system environment for configuration.
    ///
    /// # Precedence Order
    ///
    /// 1. CLI arguments (highest)
    /// 2. Environment variables (LUFF_*)
    /// 3. Config file (if --config specified)
    /// 4. Defaults (lowest)
    ///
    /// # Arguments
    ///
    /// * `args` - Parsed CLI arguments
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Git root cannot be found when `--git` flag is used
    /// - Current directory cannot be determined
    /// - Config file is specified but cannot be loaded or validated
    /// - Config values exceed bounds or are malformed
    #[cfg(feature = "cli")]
    pub fn from_args(args: &Args) -> Result<Self> {
        Self::from_args_with_env(args, &RealEnv)
    }

    /// Create configuration with a specific environment provider (for testing)
    ///
    /// The `env` parameter is used for `LUFF_*` environment variable
    /// resolution via a custom Figment [`Provider`], enabling full test
    /// isolation without modifying the process environment.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The configuration cannot be validated
    /// - The root directory logic fails
    /// - Config file parsing fails
    #[cfg(feature = "cli")]
    pub fn from_args_with_env(args: &Args, env: &dyn EnvProvider) -> Result<Self> {
        // Step 1: Determine root directory
        let root = if args.use_git_root() {
            crate::git::find_repository_root()?
        } else {
            std::env::current_dir().map_err(|e| Error::Config {
                message: format!("Failed to get current directory: {e}"),
            })?
        };

        // Step 2: Build figment provider chain with correct precedence
        // Order: Defaults < Config file < Env vars < CLI (via CliOverride)
        let mut figment = Figment::new().merge(Serialized::defaults(ConfigFile::default()));

        // Add config file if specified (higher priority than defaults).
        // We go through load_config_file() to get security validation
        // (FIFO/socket rejection, size limits, symlink resolution) before
        // Figment ever touches the file.
        if let Some(config_path) = args.config_path() {
            let config_from_file = load_config_file(config_path).map_err(|e| Error::Config {
                message: format!("Failed to load config file: {e}"),
            })?;
            figment = figment.merge(Serialized::defaults(config_from_file));
        }

        // Add environment variables (higher priority than config file)
        // Uses the injected EnvProvider so tests can isolate from the
        // real process environment.
        figment = figment.merge(EnvOverrides { env });

        // Step 3: Extract config from the complete provider chain
        let raw_config: ConfigFile = figment.extract().map_err(|e| Error::Config {
            message: format!("Failed to extract configuration: {e}"),
        })?;

        // Step 4: Create CLI overrides from explicit CLI args
        // Only include values that can be explicitly provided (non-booleans)
        let cli_override = args.to_cli_override();

        // Step 5: Validate and convert to ValidatedConfig
        let validated = raw_config
            .validate(&cli_override)
            .map_err(|e| Error::Config {
                message: format!("Configuration validation failed: {e}"),
            })?;

        // Step 6: Convert to Config
        Ok(Self::from_validated(validated, root, args))
    }

    /// Convert [`ValidatedConfig`] to Config with CLI-derived values
    #[cfg(feature = "cli")]
    fn from_validated(validated: ValidatedConfig, root: PathBuf, args: &Args) -> Self {
        // Determine if we should skip pattern filtering
        // When files are explicitly specified via -f, we respect user intent
        let skip_patterns = if args.has_files() {
            SkipPatterns::DISABLED
        } else {
            SkipPatterns::ENABLED
        };

        Self {
            validated,
            root,
            skip_patterns,
        }
    }

    /// Helper for creating a test configuration with a specific root
    ///
    /// This allows tests to create a valid Config without relying on
    /// `std::env::current_dir()`, preventing race conditions in parallel tests.
    ///
    /// # Panics
    ///
    /// Panics if the default `ConfigFile` fails validation, which should
    /// never happen since all defaults are within valid bounds.
    #[cfg(test)]
    #[must_use]
    pub fn new_for_test(root: PathBuf) -> Self {
        let config_file = ConfigFile::default();
        let validated = config_file
            .validate(&CliOverride::default())
            .expect("default config must validate");

        Self {
            validated,
            root,
            skip_patterns: SkipPatterns::ENABLED,
        }
    }

    /// Get the root directory for file operations
    #[must_use]
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Check if dotfiles should be included in directory traversal
    #[must_use]
    pub const fn include_dotfiles(&self) -> bool {
        self.validated.include_dotfiles()
    }

    /// Check if `.gitignore` patterns should be respected
    #[must_use]
    pub const fn respect_gitignore(&self) -> bool {
        self.validated.respect_gitignore()
    }

    /// Get the ignore patterns configuration
    #[must_use]
    pub const fn patterns(&self) -> &IgnorePatterns {
        self.validated.patterns()
    }

    /// Get the configured output format
    #[must_use]
    pub const fn output_format(&self) -> OutputFormat {
        self.validated.format()
    }

    /// Get the maximum depth for directory traversal
    #[must_use]
    pub const fn max_depth(&self) -> usize {
        self.validated.max_depth()
    }

    /// Get the maximum number of files to collect during directory walk
    #[must_use]
    pub const fn max_files(&self) -> usize {
        self.validated.max_files()
    }

    /// Get the maximum clipboard size in bytes
    ///
    /// Derived from [`ValidatedConfig::max_clipboard_mb`] on every call.
    /// The multiplication is trivial and this method is called
    /// infrequently (clipboard-copy path only), so computing beats
    /// caching — one fewer field that can drift from its source of truth.
    #[must_use]
    pub const fn max_clipboard_bytes(&self) -> usize {
        self.validated
            .max_clipboard_mb()
            .saturating_mul(1024 * 1024)
    }

    /// Get the pattern filtering configuration
    #[must_use]
    pub const fn skip_patterns(&self) -> SkipPatterns {
        self.skip_patterns
    }

    /// Create printer options from this configuration
    #[must_use]
    pub fn printer_options(&self) -> PrinterOptions {
        PrinterOptions {
            format: self.validated.format(),
            root: self.root.clone(),
            skip_patterns: self.skip_patterns,
            patterns: self.validated.patterns().clone(),
        }
    }
}

#[cfg(test)]
#[cfg(feature = "cli")]
mod tests {
    use super::*;
    use crate::env::MockEnv;
    use serial_test::serial;
    use tempfile::TempDir;

    #[test]
    #[serial] // Serial needed because it modifies CWD
    fn test_config_from_args_with_defaults() {
        use clap::Parser;

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

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

        // Canonicalize temp.path() to handle macOS /var → /private/var symlinks
        assert_eq!(config.root(), temp.path().canonicalize().unwrap().as_path());
        assert!(!config.include_dotfiles());
        assert!(config.respect_gitignore());
        assert_eq!(config.output_format(), OutputFormat::Markdown);
        assert_eq!(config.max_depth(), 0);
        assert_eq!(config.max_files(), 1_000_000);
        assert_eq!(config.max_clipboard_bytes(), 100 * 1024 * 1024);
    }

    #[test]
    #[serial] // Serial needed because it modifies CWD
    fn test_skip_patterns_when_file_list() {
        use clap::Parser;

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

        let args = Args::parse_from(["luff", "-f", "test.png"]);
        let config = Config::from_args_with_env(&args, &env).unwrap();
        assert_eq!(config.skip_patterns(), SkipPatterns::DISABLED);

        let args = Args::parse_from(["luff"]);
        let config = Config::from_args_with_env(&args, &env).unwrap();
        assert_eq!(config.skip_patterns(), SkipPatterns::ENABLED);
    }

    #[test]
    #[serial] // Serial needed because it modifies CWD
    fn test_clipboard_size_conversion() {
        use clap::Parser;

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

        let args = Args::parse_from(["luff", "--max-clipboard-mb", "50"]);
        let config = Config::from_args_with_env(&args, &env).unwrap();
        assert_eq!(config.max_clipboard_bytes(), 50 * 1024 * 1024);
    }

    #[test]
    #[serial]
    fn test_env_provider_overrides_defaults() {
        use clap::Parser;

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

        let env = MockEnv::new()
            .with_var("LUFF_MAX_DEPTH", "42")
            .with_var("LUFF_INCLUDE_DOTFILES", "true");

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

        assert_eq!(config.max_depth(), 42);
        assert!(config.include_dotfiles());
    }

    #[test]
    #[serial]
    fn test_env_provider_isolation() {
        use clap::Parser;

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

        // MockEnv with no vars should produce pure defaults,
        // regardless of any LUFF_* vars in the real process env.
        let env = MockEnv::new();
        let args = Args::parse_from(["luff"]);
        let config = Config::from_args_with_env(&args, &env).unwrap();

        assert_eq!(config.max_depth(), 0);
        assert!(!config.include_dotfiles());
        assert!(config.respect_gitignore());
    }

    #[test]
    #[serial]
    fn test_env_provider_warns_on_malformed_bool() {
        use clap::Parser;

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

        // "yes" is not a valid Rust bool — should be silently skipped
        // (with a log::warn that we can't easily assert here) and the
        // default (false) should be used instead.
        let env = MockEnv::new().with_var("LUFF_INCLUDE_DOTFILES", "yes");

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

        assert!(!config.include_dotfiles());
    }

    #[test]
    #[serial]
    fn test_env_provider_warns_on_malformed_u64() {
        use clap::Parser;

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

        let env = MockEnv::new().with_var("LUFF_MAX_DEPTH", "abc");

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

        // Malformed value ignored, default (0) used
        assert_eq!(config.max_depth(), 0);
    }
}