adotenv-lint 0.2.2

Opt-in lint rules and verified fixes for adotenv documents.
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
//! Shared `.adotenv-lint.toml` loading, validation and policy resolution.
//!
//! The CLI and the language server use the same model so they cannot drift on
//! discovery, unknown fields, rule severities or ignored paths.
//!
//! ```
//! use adotenv_lint::config::{ConfigExplicit, LintPolicy, LintConfig};
//!
//! let config = LintConfig::from_toml("key_order = true\n", std::path::Path::new("test.toml"))?;
//! let mut policy = LintPolicy::default();
//! config.apply(&mut policy, ConfigExplicit::default());
//! assert!(policy.lint.key_order);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use std::collections::BTreeMap;
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};

use adotenv::{Dialect, EqualsSpacing, QuoteStyle, Severity};
use globset::{Glob, GlobSet, GlobSetBuilder};
use serde::Deserialize;

use crate::{KeyCase, LintOptions, Rule};

/// The conventional lint configuration file name.
pub const CONFIG_FILE_NAME: &str = ".adotenv-lint.toml";

/// Human, JSON or GitHub output.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum OutputFormat {
    /// Human-readable text.
    Human,
    /// One JSON array.
    Json,
    /// GitHub Actions workflow commands.
    Github,
}

impl OutputFormat {
    /// Returns the stable configuration name.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Human => "human",
            Self::Json => "json",
            Self::Github => "github",
        }
    }
}

impl std::str::FromStr for OutputFormat {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "human" => Ok(Self::Human),
            "json" => Ok(Self::Json),
            "github" => Ok(Self::Github),
            other => Err(format!("unknown format: {other}")),
        }
    }
}

/// A rule severity in configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RuleSeverity {
    /// Disable the rule.
    Off,
    /// Report a warning.
    Warning,
    /// Report an error.
    Error,
}

impl RuleSeverity {
    /// Returns the corresponding lint severity, or `None` when disabled.
    #[must_use]
    pub const fn severity(self) -> Option<Severity> {
        match self {
            Self::Off => None,
            Self::Warning => Some(Severity::Warning),
            Self::Error => Some(Severity::Error),
        }
    }
}

impl std::str::FromStr for RuleSeverity {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "off" => Ok(Self::Off),
            "warning" => Ok(Self::Warning),
            "error" => Ok(Self::Error),
            other => Err(format!("unknown severity: {other}")),
        }
    }
}

/// A loaded and validated `.adotenv-lint.toml`.
///
/// All enum values are parsed while loading. Unknown fields and rules are
/// rejected before a policy can be applied.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LintConfig {
    /// Parser dialect selected by the file.
    pub dialect: Option<Dialect>,
    /// Output format selected by the file.
    pub format: Option<OutputFormat>,
    /// Whether directory paths are searched recursively.
    pub recursive: Option<bool>,
    /// Whether declarations must be sorted.
    pub key_order: Option<bool>,
    /// Key-case policy.
    pub key_case: Option<KeyCase>,
    /// Quote-style policy.
    pub quote_style: Option<QuoteStyle>,
    /// Equals-spacing policy.
    pub equals_spacing: Option<EqualsSpacing>,
    /// Whether trailing whitespace must be removed.
    pub trim_trailing_whitespace: Option<bool>,
    /// Glob patterns excluded from discovery, when present.
    pub ignore: Option<Vec<String>>,
    /// Per-rule severity overrides, keyed by the stable rule name.
    pub rules: Option<BTreeMap<String, RuleSeverity>>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawConfig {
    dialect: Option<String>,
    format: Option<String>,
    recursive: Option<bool>,
    key_order: Option<bool>,
    key_case: Option<String>,
    quote_style: Option<String>,
    equals_spacing: Option<String>,
    trim_trailing_whitespace: Option<bool>,
    ignore: Option<Vec<String>>,
    rules: Option<BTreeMap<String, String>>,
}

/// A validated lint configuration error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigError {
    path: Option<PathBuf>,
    message: String,
}

impl ConfigError {
    fn at(path: &Path, message: impl Into<String>) -> Self {
        Self {
            path: Some(path.to_path_buf()),
            message: message.into(),
        }
    }

    /// Returns the path associated with the error, when one is known.
    #[must_use]
    pub fn path(&self) -> Option<&Path> {
        self.path.as_deref()
    }

    /// Returns the error message without the path prefix.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for ConfigError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.path {
            Some(path) => write!(formatter, "{}: {}", path.display(), self.message),
            None => formatter.write_str(&self.message),
        }
    }
}

impl std::error::Error for ConfigError {}

fn unknown(name: &str, value: &str) -> String {
    // Kept separate so every configuration error has the same spelling.
    let mut message = String::new();
    message.push_str("unknown ");
    message.push_str(name);
    message.push_str(": ");
    message.push_str(value);
    message
}

impl LintConfig {
    /// Parses and validates a configuration from TOML.
    ///
    /// # Errors
    ///
    /// Returns a [`ConfigError`] for TOML syntax errors, unknown fields,
    /// unknown dialect/format/key-case/quote/spacing values or unknown rules
    /// and severities.
    pub fn from_toml(source: &str, path: &Path) -> Result<Self, ConfigError> {
        let raw: RawConfig =
            toml::from_str(source).map_err(|error| ConfigError::at(path, error.to_string()))?;
        Self::from_raw(raw, path)
    }

    /// Loads and validates a configuration file.
    ///
    /// # Errors
    ///
    /// Returns a [`ConfigError`] when the file cannot be read or does not
    /// validate.
    pub fn load(path: &Path) -> Result<Self, ConfigError> {
        let source =
            fs::read_to_string(path).map_err(|error| ConfigError::at(path, error.to_string()))?;
        Self::from_toml(&source, path)
    }

    /// Applies this configuration to a policy, honoring explicit CLI fields.
    ///
    /// Command-line values represented as `true` in `explicit` are not
    /// overwritten by the file. Rules apply after the corresponding top-level
    /// options, matching the historical CLI behavior. Rule names in a directly
    /// constructed `LintConfig` are skipped if they are not recognized;
    /// [`LintConfig::from_toml`] and [`LintConfig::load`] reject them earlier.
    pub fn apply(&self, policy: &mut LintPolicy, explicit: ConfigExplicit) {
        if !explicit.dialect {
            if let Some(value) = self.dialect {
                policy.dialect = value;
            }
        }
        if !explicit.format {
            if let Some(value) = self.format {
                policy.format = value;
            }
        }
        if !explicit.recursive {
            if let Some(value) = self.recursive {
                policy.recursive = value;
            }
        }
        if !explicit.key_order {
            if let Some(value) = self.key_order {
                policy.lint = policy.lint.with_key_order(value);
            }
        }
        if !explicit.key_case {
            if let Some(value) = self.key_case {
                policy.lint = policy.lint.with_key_case(value);
            }
        }
        if !explicit.quote_style {
            if let Some(value) = self.quote_style {
                policy.lint = policy.lint.with_quote_style(value);
            }
        }
        if !explicit.equals_spacing {
            if let Some(value) = self.equals_spacing {
                policy.lint = policy.lint.with_equals_spacing(value);
            }
        }
        if !explicit.trim_trailing_whitespace {
            if let Some(value) = self.trim_trailing_whitespace {
                policy.lint = policy.lint.with_trim_trailing_whitespace(value);
            }
        }
        if !explicit.ignore {
            if let Some(ignore) = &self.ignore {
                policy.ignore.clone_from(ignore);
            }
        }
        if let Some(rules) = &self.rules {
            apply_rules(policy, rules, explicit);
        }
    }

    fn from_raw(raw: RawConfig, path: &Path) -> Result<Self, ConfigError> {
        let dialect = raw
            .dialect
            .as_deref()
            .map(|value| {
                parse_dialect(value).map_err(|_| ConfigError::at(path, unknown("dialect", value)))
            })
            .transpose()?;
        let format = raw
            .format
            .as_deref()
            .map(|value| {
                value
                    .parse()
                    .map_err(|_| ConfigError::at(path, unknown("format", value)))
            })
            .transpose()?;
        let key_case = raw
            .key_case
            .as_deref()
            .map(|value| {
                parse_key_case(value).map_err(|_| ConfigError::at(path, unknown("key case", value)))
            })
            .transpose()?;
        let quote_style = raw
            .quote_style
            .as_deref()
            .map(|value| {
                parse_quote_style(value)
                    .map_err(|_| ConfigError::at(path, unknown("quote style", value)))
            })
            .transpose()?;
        let equals_spacing = raw
            .equals_spacing
            .as_deref()
            .map(|value| {
                parse_equals_spacing(value)
                    .map_err(|_| ConfigError::at(path, unknown("equals spacing", value)))
            })
            .transpose()?;
        if let Some(ignore) = &raw.ignore {
            IgnoredPaths::new(ignore).map_err(|error| ConfigError::at(path, error))?;
        }
        let mut rules = None;
        if let Some(raw_rules) = raw.rules {
            let mut parsed = BTreeMap::new();
            for (name, value) in raw_rules {
                let rule = parse_rule(&name)
                    .ok_or_else(|| ConfigError::at(path, format!("unknown rule: {name}")))?;
                let severity = value.parse::<RuleSeverity>().map_err(|_| {
                    ConfigError::at(path, unknown(&format!("severity for {name}"), &value))
                })?;
                parsed.insert(rule.as_str().to_owned(), severity);
            }
            rules = Some(parsed);
        }
        Ok(Self {
            dialect,
            format,
            recursive: raw.recursive,
            key_order: raw.key_order,
            key_case,
            quote_style,
            equals_spacing,
            trim_trailing_whitespace: raw.trim_trailing_whitespace,
            ignore: raw.ignore,
            rules,
        })
    }
}

fn apply_rules(
    policy: &mut LintPolicy,
    rules: &BTreeMap<String, RuleSeverity>,
    explicit: ConfigExplicit,
) {
    for (name, severity) in rules {
        let Some(rule) = parse_rule(name) else {
            // `LintConfig::from_toml` rejects unknown names. The fields are
            // public, so skip rather than panic when a caller builds an
            // unvalidated configuration directly.
            continue;
        };
        let enabled = severity.severity().is_some();
        match rule {
            Rule::DuplicateKey => {
                policy.lint = policy.lint.with_duplicate_keys(enabled);
            }
            Rule::KeyOrder if !explicit.key_order => {
                policy.lint = policy.lint.with_key_order(enabled);
            }
            Rule::KeyCase if !explicit.key_case && !enabled => {
                policy.lint = policy.lint.with_key_case(KeyCase::Off);
            }
            Rule::QuoteStyle if !explicit.quote_style && !enabled => {
                policy.lint = policy.lint.with_quote_style(QuoteStyle::Preserve);
            }
            Rule::Whitespace if !enabled => {
                if !explicit.equals_spacing {
                    policy.lint = policy.lint.with_equals_spacing(EqualsSpacing::Preserve);
                }
                if !explicit.trim_trailing_whitespace {
                    policy.lint = policy.lint.with_trim_trailing_whitespace(false);
                }
            }
            _ => {}
        }
        if let Some(severity) = severity.severity() {
            policy.lint = policy.lint.with_severity(rule, severity);
        }
    }
}

/// Compiled ignore globs shared by the CLI and LSP.
#[derive(Debug, Clone)]
pub struct IgnoredPaths {
    globs: GlobSet,
}

impl IgnoredPaths {
    /// Compiles ignore glob patterns.
    ///
    /// # Errors
    ///
    /// Returns the invalid glob error text.
    pub fn new(patterns: &[String]) -> Result<Self, String> {
        let mut builder = GlobSetBuilder::new();
        for pattern in patterns {
            let glob = Glob::new(pattern).map_err(|error| format!("invalid exclude: {error}"))?;
            builder.add(glob);
        }
        let globs = builder
            .build()
            .map_err(|error| format!("invalid exclude: {error}"))?;
        Ok(Self { globs })
    }

    /// Returns whether `path` matches a configured pattern by full path,
    /// basename, or a path suffix.
    ///
    /// The suffix match is intended for LSP document URIs, which are absolute
    /// and have no workspace root. Use [`is_ignored_with_root`](Self::is_ignored_with_root)
    /// for filesystem discovery, where matching every ancestor suffix would
    /// also match an unrelated directory named like a pattern.
    #[must_use]
    pub fn is_ignored(&self, path: &Path) -> bool {
        if self.matches_path(path) {
            return true;
        }
        let components: Vec<_> = path.components().collect();
        for start in 1..components.len() {
            let suffix: PathBuf = components[start..].iter().collect();
            if self.globs.is_match(&suffix) {
                return true;
            }
        }
        false
    }

    /// Returns whether `path` matches by full path, basename, or path relative
    /// to `root`.
    ///
    /// Unlike [`is_ignored`](Self::is_ignored), this does not test arbitrary
    /// ancestor suffixes. A pattern such as `src/**` therefore only matches a
    /// `src` below the discovery root, not any ancestor directory that happens
    /// to be named `src`.
    #[must_use]
    pub fn is_ignored_with_root(&self, path: &Path, root: &Path) -> bool {
        if self.matches_path(path) {
            return true;
        }
        path.strip_prefix(root)
            .is_ok_and(|relative| !relative.as_os_str().is_empty() && self.globs.is_match(relative))
    }

    fn matches_path(&self, path: &Path) -> bool {
        self.globs.is_match(path)
            || path
                .file_name()
                .is_some_and(|name| self.globs.is_match(Path::new(name)))
    }
}

/// The policy resolved from a config plus caller-selected defaults.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LintPolicy {
    /// Parser dialect.
    pub dialect: Dialect,
    /// Output format.
    pub format: OutputFormat,
    /// Whether directories are searched recursively.
    pub recursive: bool,
    /// Lint rules and severities.
    pub lint: LintOptions,
    /// Ignored glob patterns.
    pub ignore: Vec<String>,
}

impl Default for LintPolicy {
    fn default() -> Self {
        Self {
            dialect: Dialect::PORTABLE,
            format: OutputFormat::Human,
            recursive: false,
            lint: LintOptions::default(),
            ignore: Vec::new(),
        }
    }
}

impl LintPolicy {
    /// Compiles this policy's ignore patterns.
    ///
    /// # Errors
    ///
    /// Returns an error only if a pattern is not a valid glob.
    pub fn ignored_paths(&self) -> Result<IgnoredPaths, String> {
        IgnoredPaths::new(&self.ignore)
    }
}

/// Which policy fields were set explicitly on the command line.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ConfigExplicit {
    /// Dialect was selected explicitly.
    pub dialect: bool,
    /// Format was selected explicitly.
    pub format: bool,
    /// Recursive mode was selected explicitly.
    pub recursive: bool,
    /// Key-order mode was selected explicitly.
    pub key_order: bool,
    /// Key-case policy was selected explicitly.
    pub key_case: bool,
    /// Quote-style policy was selected explicitly.
    pub quote_style: bool,
    /// Equals-spacing policy was selected explicitly.
    pub equals_spacing: bool,
    /// Trailing-whitespace mode was selected explicitly.
    pub trim_trailing_whitespace: bool,
    /// Ignore patterns were selected explicitly.
    pub ignore: bool,
}

/// Finds the nearest ancestor configuration without reading it.
///
/// `start` may be a file or a directory. The search begins at its directory
/// and walks toward the filesystem root.
#[must_use]
pub fn discover_config(start: &Path) -> Option<PathBuf> {
    let mut directory = if start.is_dir() {
        start.to_path_buf()
    } else {
        start.parent()?.to_path_buf()
    };
    loop {
        let candidate = directory.join(CONFIG_FILE_NAME);
        if candidate.is_file() {
            return Some(candidate);
        }
        if !directory.pop() {
            return None;
        }
    }
}

/// Loads an explicit configuration, or discovers one from `start`.
///
/// Returns `Ok(None)` when no explicit path is supplied and no configuration
/// file exists in `start` or its ancestors.
///
/// # Errors
///
/// Returns a [`ConfigError`] when a file exists or is explicit but cannot be
/// read or validated.
pub fn load_effective_config(
    explicit: Option<&Path>,
    start: &Path,
) -> Result<Option<LintConfig>, ConfigError> {
    let path = match explicit {
        Some(path) => path.to_path_buf(),
        None => match discover_config(start) {
            Some(path) => path,
            None => return Ok(None),
        },
    };
    LintConfig::load(&path).map(Some)
}

fn parse_rule(value: &str) -> Option<Rule> {
    match value {
        "duplicate-key" => Some(Rule::DuplicateKey),
        "key-order" => Some(Rule::KeyOrder),
        "key-case" => Some(Rule::KeyCase),
        "quote-style" => Some(Rule::QuoteStyle),
        "whitespace" => Some(Rule::Whitespace),
        _ => None,
    }
}

/// Parses a dialect configuration/CLI value.
///
/// # Errors
///
/// Returns an error for an unknown dialect name.
pub fn parse_dialect(value: &str) -> Result<Dialect, String> {
    match value {
        "portable" => Ok(Dialect::PORTABLE),
        "node" => Ok(Dialect::NODE_DOTENV),
        "python" => Ok(Dialect::PYTHON_DOTENV),
        "compose" => Ok(Dialect::COMPOSE),
        "docker" | "docker-raw" => Ok(Dialect::DOCKER_RAW),
        other => Err(format!("unknown dialect: {other}")),
    }
}

/// Parses a key-case configuration/CLI value.
///
/// # Errors
///
/// Returns an error for an unknown key-case name.
pub fn parse_key_case(value: &str) -> Result<KeyCase, String> {
    match value {
        "lower" => Ok(KeyCase::Lower),
        "upper" => Ok(KeyCase::Upper),
        other => Err(format!("unknown key case: {other}")),
    }
}

/// Parses a quote-style configuration/CLI value.
///
/// # Errors
///
/// Returns an error for an unknown quote-style name.
pub fn parse_quote_style(value: &str) -> Result<QuoteStyle, String> {
    match value {
        "preserve" => Ok(QuoteStyle::Preserve),
        "double" => Ok(QuoteStyle::Double),
        "single" => Ok(QuoteStyle::Single),
        "unquoted" => Ok(QuoteStyle::Unquoted),
        other => Err(format!("unknown quote style: {other}")),
    }
}

/// Parses an equals-spacing configuration/CLI value.
///
/// # Errors
///
/// Returns an error for an unknown spacing name.
pub fn parse_equals_spacing(value: &str) -> Result<EqualsSpacing, String> {
    match value {
        "preserve" => Ok(EqualsSpacing::Preserve),
        "none" => Ok(EqualsSpacing::None),
        "spaces" => Ok(EqualsSpacing::Spaces),
        other => Err(format!("unknown equals spacing: {other}")),
    }
}

/// Parses a format configuration/CLI value.
///
/// # Errors
///
/// Returns an error for an unknown output format.
pub fn parse_output_format(value: &str) -> Result<OutputFormat, String> {
    value.parse()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    static NEXT: AtomicUsize = AtomicUsize::new(0);

    struct TempDir(PathBuf);

    impl TempDir {
        fn new(name: &str) -> Self {
            let path = std::env::temp_dir().join(format!(
                "adotenv-lint-config-{name}-{}-{}",
                std::process::id(),
                NEXT.fetch_add(1, Ordering::Relaxed)
            ));
            fs::create_dir_all(&path).unwrap();
            Self(path)
        }
        fn file(&self, name: &str, source: &str) -> PathBuf {
            let path = self.0.join(name);
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent).unwrap();
            }
            fs::write(&path, source).unwrap();
            path
        }
        fn path(&self) -> &Path {
            &self.0
        }
    }

    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    #[test]
    fn no_config_uses_defaults() {
        let dir = TempDir::new("defaults");
        let config = load_effective_config(None, dir.path()).unwrap();
        assert!(config.is_none());
        let policy = LintPolicy::default();
        assert_eq!(policy.dialect, Dialect::PORTABLE);
        assert_eq!(policy.format, OutputFormat::Human);
        assert_eq!(policy.ignore.len(), 0);
    }

    #[test]
    fn explicit_path_takes_precedence_over_discovery() {
        let dir = TempDir::new("explicit");
        dir.file(CONFIG_FILE_NAME, "key_order = true\n");
        let explicit = dir.file("other.toml", "key_case = \"upper\"\n");
        let config = load_effective_config(Some(&explicit), dir.path())
            .unwrap()
            .unwrap();
        assert_eq!(config.key_order, None);
        assert_eq!(config.key_case, Some(KeyCase::Upper));
    }

    #[test]
    fn discovery_walks_ancestors() {
        let dir = TempDir::new("discovery");
        dir.file(CONFIG_FILE_NAME, "key_order = true\n");
        let nested = dir.path().join("nested");
        fs::create_dir_all(&nested).unwrap();
        assert_eq!(
            discover_config(&nested.join("app.env")),
            Some(dir.path().join(CONFIG_FILE_NAME))
        );
    }

    #[test]
    fn unknown_fields_and_rules_are_rejected() {
        let path = Path::new("test.toml");
        assert!(LintConfig::from_toml("unknown = true\n", path).is_err());
        assert!(LintConfig::from_toml("[rules]\nunknown = \"warning\"\n", path).is_err());
        assert!(LintConfig::from_toml("[rules]\nkey-order = \"nope\"\n", path).is_err());
        assert!(LintConfig::from_toml("ignore = [\"[\"]\n", path).is_err());
    }

    #[test]
    fn unvalidated_public_rule_maps_do_not_panic() {
        let config = LintConfig {
            dialect: None,
            format: None,
            recursive: None,
            key_order: None,
            key_case: None,
            quote_style: None,
            equals_spacing: None,
            trim_trailing_whitespace: None,
            ignore: None,
            rules: Some(BTreeMap::from([(
                "not-a-rule".to_owned(),
                RuleSeverity::Error,
            )])),
        };
        let mut policy = LintPolicy::default();
        config.apply(&mut policy, ConfigExplicit::default());
    }

    #[test]
    fn disabled_whitespace_rule_keeps_explicit_cli_options() {
        let config =
            LintConfig::from_toml("[rules]\nwhitespace = \"off\"\n", Path::new("test.toml"))
                .unwrap();
        let mut policy = LintPolicy {
            lint: LintOptions::default().with_trim_trailing_whitespace(true),
            ..LintPolicy::default()
        };
        config.apply(
            &mut policy,
            ConfigExplicit {
                trim_trailing_whitespace: true,
                ..ConfigExplicit::default()
            },
        );
        assert!(policy.lint.trim_trailing_whitespace);
    }

    #[test]
    fn rooted_ignores_do_not_match_ancestor_components() {
        let ignores = IgnoredPaths::new(&["src/**".to_owned()]).unwrap();
        let absolute = Path::new("/work/src/project/.env");
        assert!(!ignores.is_ignored_with_root(absolute, Path::new("/work/src/project")));
        assert!(ignores.is_ignored_with_root(
            Path::new("/work/src/project/src/.env"),
            Path::new("/work/src/project")
        ));
        // LSP has no root, so its suffix match stays intentionally broad.
        assert!(ignores.is_ignored(absolute));
    }

    #[test]
    fn severity_and_ignores_apply() {
        let config = LintConfig::from_toml(
            "ignore = [\".env.skip\"]\n[rules]\nduplicate-key = \"error\"\n",
            Path::new("test.toml"),
        )
        .unwrap();
        let mut policy = LintPolicy::default();
        config.apply(&mut policy, ConfigExplicit::default());
        assert_eq!(policy.ignore, [".env.skip"]);
        assert_eq!(
            policy.lint.severity_for_rule(Rule::DuplicateKey),
            Severity::Error
        );
    }

    #[test]
    fn explicit_fields_are_not_overridden() {
        let config = LintConfig::from_toml(
            "format = \"json\"\nkey_order = true\nignore = [\"config\"]\n",
            Path::new("test.toml"),
        )
        .unwrap();
        let mut policy = LintPolicy {
            format: OutputFormat::Human,
            ignore: vec!["cli".to_owned()],
            ..LintPolicy::default()
        };
        config.apply(
            &mut policy,
            ConfigExplicit {
                format: true,
                key_order: true,
                ignore: true,
                ..ConfigExplicit::default()
            },
        );
        assert_eq!(policy.format, OutputFormat::Human);
        assert!(!policy.lint.key_order);
        assert_eq!(policy.ignore, ["cli"]);
    }

    #[test]
    fn parses_dialects_and_spacing() {
        assert_eq!(parse_dialect("portable").unwrap(), Dialect::PORTABLE);
        assert_eq!(parse_dialect("node").unwrap(), Dialect::NODE_DOTENV);
        assert_eq!(parse_dialect("python").unwrap(), Dialect::PYTHON_DOTENV);
        assert_eq!(parse_dialect("compose").unwrap(), Dialect::COMPOSE);
        assert_eq!(parse_dialect("docker").unwrap(), Dialect::DOCKER_RAW);
        assert_eq!(parse_dialect("docker-raw").unwrap(), Dialect::DOCKER_RAW);
        assert!(parse_dialect("nope").is_err());

        assert_eq!(parse_key_case("lower").unwrap(), KeyCase::Lower);
        assert_eq!(parse_key_case("upper").unwrap(), KeyCase::Upper);
        assert!(parse_key_case("mixed").is_err());

        assert_eq!(parse_quote_style("preserve").unwrap(), QuoteStyle::Preserve);
        assert_eq!(parse_quote_style("double").unwrap(), QuoteStyle::Double);
        assert_eq!(parse_quote_style("single").unwrap(), QuoteStyle::Single);
        assert_eq!(parse_quote_style("unquoted").unwrap(), QuoteStyle::Unquoted);
        assert!(parse_quote_style("backtick").is_err());

        assert_eq!(
            parse_equals_spacing("preserve").unwrap(),
            EqualsSpacing::Preserve
        );
        assert_eq!(parse_equals_spacing("none").unwrap(), EqualsSpacing::None);
        assert_eq!(
            parse_equals_spacing("spaces").unwrap(),
            EqualsSpacing::Spaces
        );
        assert!(parse_equals_spacing("tabs").is_err());

        assert_eq!(OutputFormat::Human.as_str(), "human");
        assert_eq!(OutputFormat::Json.as_str(), "json");
        assert_eq!(OutputFormat::Github.as_str(), "github");
        assert_eq!(parse_output_format("human").unwrap(), OutputFormat::Human);
        assert_eq!(parse_output_format("json").unwrap(), OutputFormat::Json);
        assert_eq!(parse_output_format("github").unwrap(), OutputFormat::Github);
        assert!(parse_output_format("xml").is_err());

        assert_eq!(
            "warning".parse::<RuleSeverity>().unwrap().severity(),
            Some(Severity::Warning)
        );
        assert_eq!(
            "error".parse::<RuleSeverity>().unwrap().severity(),
            Some(Severity::Error)
        );
        assert_eq!("off".parse::<RuleSeverity>().unwrap().severity(), None);
        assert!("fatal".parse::<RuleSeverity>().is_err());
    }

    #[test]
    fn config_apply_and_validation_cover_all_fields_and_errors() {
        let full = LintConfig::from_toml(
            "dialect = \"compose\"\n\
             format = \"github\"\n\
             recursive = true\n\
             key_order = true\n\
             key_case = \"lower\"\n\
             quote_style = \"double\"\n\
             equals_spacing = \"spaces\"\n\
             trim_trailing_whitespace = true\n\
             ignore = [\"vendor/**\"]\n\
             [rules]\n\
             key-case = \"warning\"\n\
             quote-style = \"error\"\n\
             whitespace = \"warning\"\n",
            Path::new("full.toml"),
        )
        .unwrap();
        let mut policy = LintPolicy::default();
        full.apply(&mut policy, ConfigExplicit::default());
        assert_eq!(policy.dialect, Dialect::COMPOSE);
        assert_eq!(policy.format, OutputFormat::Github);
        assert!(policy.recursive);
        assert!(policy.lint.key_order);
        assert_eq!(policy.lint.key_case, KeyCase::Lower);
        assert_eq!(policy.lint.quote_style, QuoteStyle::Double);
        assert_eq!(policy.lint.equals_spacing, EqualsSpacing::Spaces);
        assert!(policy.lint.trim_trailing_whitespace);
        assert_eq!(policy.ignore, ["vendor/**"]);

        // Disabling rules via [rules] resets non-explicit top-level policies.
        let disable = LintConfig::from_toml(
            "[rules]\nkey-case = \"off\"\nquote-style = \"off\"\nwhitespace = \"off\"\n",
            Path::new("off.toml"),
        )
        .unwrap();
        disable.apply(&mut policy, ConfigExplicit::default());
        assert_eq!(policy.lint.key_case, KeyCase::Off);
        assert_eq!(policy.lint.quote_style, QuoteStyle::Preserve);
        assert_eq!(policy.lint.equals_spacing, EqualsSpacing::Preserve);
        assert!(!policy.lint.trim_trailing_whitespace);

        // Invalid enum values report ConfigError with path and message.
        for (snippet, expected) in [
            ("dialect = \"nope\"\n", "unknown dialect: nope"),
            ("format = \"nope\"\n", "unknown format: nope"),
            ("key_case = \"nope\"\n", "unknown key case: nope"),
            ("quote_style = \"nope\"\n", "unknown quote style: nope"),
            (
                "equals_spacing = \"nope\"\n",
                "unknown equals spacing: nope",
            ),
            (
                "[rules]\nkey-case = \"nope\"\n",
                "unknown severity for key-case: nope",
            ),
        ] {
            let err = LintConfig::from_toml(snippet, Path::new("bad.toml")).unwrap_err();
            assert_eq!(err.path(), Some(Path::new("bad.toml")));
            assert_eq!(err.message(), expected);
            assert!(err.to_string().contains("bad.toml"));
        }

        let no_path = ConfigError {
            path: None,
            message: "plain error".to_owned(),
        };
        assert_eq!(no_path.path(), None);
        assert_eq!(no_path.to_string(), "plain error");
    }
}