Skip to main content

adotenv_lint/
lib.rs

1//! Opt-in lint rules, schema checks and verified fixes for [`adotenv`] documents.
2//!
3//! The linter is deliberately separate from the parser. A lint finding is
4//! policy, not a parse error, and every suggested fix is applied through
5//! `adotenv`'s verified edit or format APIs.
6//!
7//! The default rule set reports duplicate keys only. Enable ordering, key
8//! case, quoting, whitespace, or [`Schema`] / `.env.example` rules explicitly
9//! through [`LintOptions`], [`lint_with_schema`], and [`lint_with_options`].
10//!
11//! ```
12//! use adotenv_lint::{lint, LintOptions};
13//!
14//! let doc = adotenv::parse_strict("B=2\nA=1\n").unwrap();
15//! let defaults = lint(&doc, LintOptions::default());
16//! assert!(defaults.is_empty());
17//!
18//! let findings = lint(
19//!     &doc,
20//!     LintOptions::default().with_key_order(true),
21//! );
22//! assert_eq!(findings.len(), 1);
23//! assert_eq!(findings[0].rule(), adotenv_lint::Rule::KeyOrder);
24//! ```
25
26pub mod config;
27pub mod schema;
28
29#[cfg(doctest)]
30#[doc = include_str!("../README.md")]
31mod readme_doctests {}
32
33pub use adotenv::EditOptions;
34pub use config::{
35    discover_config, load_effective_config, parse_dialect, parse_equals_spacing, parse_key_case,
36    parse_output_format, parse_quote_style, ConfigError, ConfigExplicit, IgnoredPaths,
37    KeySchemaConfig, LintConfig, LintPolicy, OutputFormat, RuleSeverity, SchemaConfig,
38};
39pub use schema::{KeySchema, Schema, ValueShape};
40
41use std::collections::{BTreeMap, BTreeSet};
42use std::fmt;
43use std::ops::Range;
44
45use adotenv::{
46    parse_strict_with_options, parse_with_options, BlankLines, ColumnEncoding, Diagnostic, Dialect,
47    Document, Edit, EditError, EqualsSpacing, FinalNewline, FormatError, FormatOptions,
48    FormatResult, LineIndex, ParseOptions, Quote, QuoteStyle, Severity, VerifiedEdits,
49};
50
51/// The policy rules understood by the linter.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53#[non_exhaustive]
54pub enum Rule {
55    /// A key is declared more than once.
56    DuplicateKey,
57    /// Keys are not in the configured order.
58    KeyOrder,
59    /// A key does not use the configured ASCII case.
60    KeyCase,
61    /// A value does not use the configured quote style.
62    QuoteStyle,
63    /// Spacing around `=` or trailing whitespace differs from the policy.
64    Whitespace,
65    /// A required key declared by a [`Schema`] is absent from the document.
66    MissingKey,
67    /// A key declared in the document is absent from a closed [`Schema`].
68    UnknownKey,
69    /// A key has an empty or disallowed bare value under a [`Schema`].
70    EmptyValue,
71    /// A key's literal value does not match its [`Schema`] [`ValueShape`].
72    InvalidValue,
73}
74
75impl Rule {
76    const fn index(self) -> usize {
77        match self {
78            Self::DuplicateKey => 0,
79            Self::KeyOrder => 1,
80            Self::KeyCase => 2,
81            Self::QuoteStyle => 3,
82            Self::Whitespace => 4,
83            Self::MissingKey => 5,
84            Self::UnknownKey => 6,
85            Self::EmptyValue => 7,
86            Self::InvalidValue => 8,
87        }
88    }
89    /// Returns the stable rule identifier.
90    #[must_use]
91    pub const fn as_str(self) -> &'static str {
92        match self {
93            Self::DuplicateKey => "duplicate-key",
94            Self::KeyOrder => "key-order",
95            Self::KeyCase => "key-case",
96            Self::QuoteStyle => "quote-style",
97            Self::Whitespace => "whitespace",
98            Self::MissingKey => "missing-key",
99            Self::UnknownKey => "unknown-key",
100            Self::EmptyValue => "empty-value",
101            Self::InvalidValue => "invalid-value",
102        }
103    }
104}
105
106/// The desired ASCII case for keys.
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
108#[non_exhaustive]
109pub enum KeyCase {
110    /// Do not check key case.
111    #[default]
112    Off,
113    /// Require lowercase ASCII letters.
114    Lower,
115    /// Require uppercase ASCII letters.
116    Upper,
117}
118
119/// Linter policy.
120#[allow(clippy::struct_excessive_bools)]
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
122#[non_exhaustive]
123pub struct LintOptions {
124    /// Report later declarations of a repeated key.
125    pub duplicate_keys: bool,
126    /// Require each group's declarations to be in key order.
127    ///
128    /// A group that `Document::sort` cannot reorder, such as one with a
129    /// self-reference or a reference cycle, is still reported, with no fix
130    /// attached.
131    pub key_order: bool,
132    /// Require a key case.
133    pub key_case: KeyCase,
134    /// Require a quote style for non-empty values.
135    pub quote_style: QuoteStyle,
136    /// Require a spacing policy around assignment separators.
137    pub equals_spacing: EqualsSpacing,
138    /// Remove trailing spaces and tabs.
139    pub trim_trailing_whitespace: bool,
140    /// Report missing required keys when a [`Schema`] is supplied.
141    pub missing_keys: bool,
142    /// Report undeclared keys when a [`Schema`] sets `allow_unknown = false`.
143    pub unknown_keys: bool,
144    /// Report disallowed empty or bare values when a [`Schema`] is supplied.
145    pub empty_values: bool,
146    /// Report values failing their configured [`ValueShape`] when a [`Schema`]
147    /// is supplied.
148    pub invalid_values: bool,
149    severities: [Severity; 9],
150}
151
152impl Default for LintOptions {
153    fn default() -> Self {
154        Self::new()
155    }
156}
157
158impl LintOptions {
159    /// Creates the conservative default policy: duplicate-key checks only when
160    /// no [`Schema`] is supplied, with schema rules enabled when a [`Schema`]
161    /// is passed to [`lint_with_schema`] or [`lint_with_options`].
162    #[must_use]
163    pub const fn new() -> Self {
164        Self {
165            duplicate_keys: true,
166            key_order: false,
167            key_case: KeyCase::Off,
168            quote_style: QuoteStyle::Preserve,
169            equals_spacing: EqualsSpacing::Preserve,
170            trim_trailing_whitespace: false,
171            missing_keys: true,
172            unknown_keys: true,
173            empty_values: true,
174            invalid_values: true,
175            severities: [Severity::Warning; 9],
176        }
177    }
178    /// Enables or disables duplicate-key findings.
179    #[must_use]
180    pub const fn with_duplicate_keys(mut self, value: bool) -> Self {
181        self.duplicate_keys = value;
182        self
183    }
184    /// Enables or disables key-order findings.
185    #[must_use]
186    pub const fn with_key_order(mut self, value: bool) -> Self {
187        self.key_order = value;
188        self
189    }
190    /// Sets the key-case policy.
191    #[must_use]
192    pub const fn with_key_case(mut self, value: KeyCase) -> Self {
193        self.key_case = value;
194        self
195    }
196    /// Sets the quote-style policy.
197    #[must_use]
198    pub const fn with_quote_style(mut self, value: QuoteStyle) -> Self {
199        self.quote_style = value;
200        self
201    }
202    /// Sets the assignment-spacing policy.
203    #[must_use]
204    pub const fn with_equals_spacing(mut self, value: EqualsSpacing) -> Self {
205        self.equals_spacing = value;
206        self
207    }
208    /// Enables or disables trailing-whitespace findings.
209    #[must_use]
210    pub const fn with_trim_trailing_whitespace(mut self, value: bool) -> Self {
211        self.trim_trailing_whitespace = value;
212        self
213    }
214    /// Enables or disables missing-key schema findings.
215    #[must_use]
216    pub const fn with_missing_keys(mut self, value: bool) -> Self {
217        self.missing_keys = value;
218        self
219    }
220    /// Enables or disables unknown-key schema findings.
221    #[must_use]
222    pub const fn with_unknown_keys(mut self, value: bool) -> Self {
223        self.unknown_keys = value;
224        self
225    }
226    /// Enables or disables empty- and bare-value schema findings.
227    #[must_use]
228    pub const fn with_empty_values(mut self, value: bool) -> Self {
229        self.empty_values = value;
230        self
231    }
232    /// Enables or disables invalid-value schema findings.
233    #[must_use]
234    pub const fn with_invalid_values(mut self, value: bool) -> Self {
235        self.invalid_values = value;
236        self
237    }
238    /// Sets the severity reported for one rule.
239    #[must_use]
240    pub const fn with_severity(mut self, rule: Rule, severity: Severity) -> Self {
241        self.severities[rule.index()] = severity;
242        self
243    }
244    /// Returns the configured severity for one rule.
245    #[must_use]
246    pub const fn severity_for_rule(self, rule: Rule) -> Severity {
247        self.severities[rule.index()]
248    }
249    fn format_options(self) -> FormatOptions {
250        FormatOptions::default()
251            .with_quote_style(self.quote_style)
252            .with_equals_spacing(self.equals_spacing)
253            .with_trim_trailing_whitespace(self.trim_trailing_whitespace)
254    }
255}
256
257/// A structured lint finding.
258///
259/// Findings never contain values: only the rule, message, key and source span
260/// are retained. A finding may include a fix that can be applied through
261/// [`apply_fix`].
262#[derive(Debug, Clone, PartialEq, Eq)]
263pub struct Finding {
264    rule: Rule,
265    message: &'static str,
266    severity: Severity,
267    span: Range<usize>,
268    line: usize,
269    key: Option<String>,
270    fix: Option<Fix>,
271}
272
273impl Finding {
274    pub(crate) fn new(
275        rule: Rule,
276        message: &'static str,
277        severity: Severity,
278        span: Range<usize>,
279        line: usize,
280        key: Option<&str>,
281        fix: Option<Fix>,
282    ) -> Self {
283        Self {
284            rule,
285            message,
286            severity,
287            span,
288            line,
289            key: key.map(str::to_owned),
290            fix,
291        }
292    }
293    /// Returns the rule that produced this finding.
294    #[must_use]
295    pub const fn rule(&self) -> Rule {
296        self.rule
297    }
298    /// Returns the stable, value-free message.
299    #[must_use]
300    pub const fn message(&self) -> &'static str {
301        self.message
302    }
303    /// Returns the configured finding severity; warnings by default.
304    #[must_use]
305    pub const fn severity(&self) -> Severity {
306        self.severity
307    }
308    /// Returns the byte range of the finding in the document source.
309    #[must_use]
310    pub fn span(&self) -> Range<usize> {
311        self.span.clone()
312    }
313    /// Returns the one-based line of the finding.
314    #[must_use]
315    pub const fn line(&self) -> usize {
316        self.line
317    }
318    /// Returns the key named by the finding, when there is one.
319    #[must_use]
320    pub fn key(&self) -> Option<&str> {
321        self.key.as_deref()
322    }
323    /// Returns a verified-fix request for this finding, when one is available.
324    #[must_use]
325    pub const fn fix(&self) -> Option<&Fix> {
326        self.fix.as_ref()
327    }
328}
329
330/// A fix request for an [`adotenv`] document.
331#[derive(Debug, Clone, PartialEq, Eq)]
332#[non_exhaustive]
333pub enum Fix {
334    /// Sort each group through [`Document::sort`].
335    Sort,
336    /// Apply a format policy through [`Document::format`].
337    Format(FormatOptions),
338    /// Rename one declaration through [`Edit::Rename`].
339    Rename {
340        /// The zero-based entry ID.
341        entry: usize,
342        /// The replacement key.
343        key: String,
344    },
345}
346
347/// A successfully applied fix.
348#[derive(Debug)]
349#[non_exhaustive]
350pub enum FixResult {
351    /// The verified result of [`Document::sort`] or [`Document::format`].
352    Format(FormatResult),
353    /// The verified result of an edit batch.
354    Edits(VerifiedEdits),
355}
356
357impl FixResult {
358    /// Returns the complete verified output text.
359    #[must_use]
360    pub fn as_str(&self) -> &str {
361        match self {
362            Self::Format(result) => result.as_str(),
363            Self::Edits(result) => result.as_str(),
364        }
365    }
366    /// Returns the verified text edits.
367    #[must_use]
368    pub fn edits(&self) -> &[adotenv::TextEdit] {
369        match self {
370            Self::Format(result) => result.edits(),
371            Self::Edits(result) => result.edits(),
372        }
373    }
374}
375
376/// The result of applying compatible fixes in stages.
377///
378/// Each stage is verified against the source at the start of that stage. The
379/// final [`output`](Self::output) is the complete result; stage edits are
380/// relative to their own stage input, not to the original source.
381#[derive(Debug)]
382pub struct BatchResult {
383    output: String,
384    stages: Vec<FixResult>,
385    empty: bool,
386}
387
388impl BatchResult {
389    /// Returns the final verified output text.
390    #[must_use]
391    pub fn output(&self) -> &str {
392        &self.output
393    }
394    /// Returns the verified stages in application order.
395    #[must_use]
396    pub fn stages(&self) -> &[FixResult] {
397        &self.stages
398    }
399    /// Returns `true` when no fix changed anything.
400    #[must_use]
401    pub fn is_empty(&self) -> bool {
402        self.empty
403    }
404}
405
406struct PlannedFixes {
407    renames: Vec<(usize, String)>,
408    format: Option<FormatOptions>,
409    sort: bool,
410}
411
412fn plan_fixes(fixes: &[Fix]) -> Result<PlannedFixes, LintError> {
413    let mut renames: Vec<(usize, String)> = Vec::new();
414    let mut format = None;
415    let mut sort = false;
416    for fix in fixes {
417        match fix {
418            Fix::Rename { entry, key } => {
419                if let Some((_, existing)) = renames.iter().find(|(id, _)| id == entry) {
420                    if existing != key {
421                        return Err(LintError::Conflict(
422                            "one entry has two different replacement keys",
423                        ));
424                    }
425                    continue;
426                }
427                renames.push((*entry, key.clone()));
428            }
429            Fix::Format(options) => {
430                if format.is_some_and(|existing: FormatOptions| existing != *options) {
431                    return Err(LintError::Conflict(
432                        "different format policies cannot be combined",
433                    ));
434                }
435                format = Some(*options);
436            }
437            Fix::Sort => sort = true,
438        }
439    }
440    Ok(PlannedFixes {
441        renames,
442        format,
443        sort,
444    })
445}
446
447fn parse_strict_bounded(
448    source: &str,
449    dialect: Dialect,
450    limits: ParseOptions,
451) -> Result<Document<'_>, LintError> {
452    if limits.max_diagnostics.is_some() {
453        let (document, diagnostics) = parse_with_options(source, dialect, limits);
454        if let Some(limit) = diagnostics.iter().find_map(Diagnostic::limit) {
455            return Err(LintError::Edit(EditError::Limit(limit)));
456        }
457        if diagnostics
458            .iter()
459            .any(|diagnostic| diagnostic.severity() == Severity::Error)
460        {
461            return Err(LintError::Parse);
462        }
463        return Ok(document);
464    }
465    parse_strict_with_options(source, dialect, limits).map_err(|error| map_parse_error(&error))
466}
467
468fn map_format_edit_error(error: EditError) -> LintError {
469    match error {
470        EditError::WouldChangeMeaning => LintError::Format(FormatError::WouldChangeMeaning),
471        other => LintError::Edit(other),
472    }
473}
474
475fn map_parse_error(error: &Diagnostic) -> LintError {
476    error.limit().map_or(LintError::Parse, |limit| {
477        LintError::Edit(EditError::Limit(limit))
478    })
479}
480
481fn needs_two_pass_unquote(options: FormatOptions) -> bool {
482    options.quote_style == QuoteStyle::Unquoted
483        && (options.equals_spacing != EqualsSpacing::Preserve
484            || options.trim_trailing_whitespace
485            || options.blank_lines != BlankLines::Preserve
486            || options.final_newline != FinalNewline::Preserve)
487}
488
489/// Applies renames, sorting and formatting in compatible stages.
490///
491/// Renames are applied together in one edit batch. Sorting and one format
492/// policy can follow; each stage is verified before the next starts. Different
493/// format policies and conflicting replacement keys are rejected. When a format
494/// policy combines [`QuoteStyle::Unquoted`] with other trivia rewrites,
495/// unquoting runs in its own verified stage before the remaining formatting.
496/// This is the multi-stage companion to [`apply_fixes`].
497///
498/// # Errors
499///
500/// Returns [`LintError`] for conflicting fixes, a rejected edit/format, or an
501/// intermediate output that cannot be parsed.
502pub fn apply_batch(document: &Document<'_>, fixes: &[Fix]) -> Result<BatchResult, LintError> {
503    apply_batch_with_options(document, fixes, EditOptions::new())
504}
505
506/// Applies renames, sorting and formatting in compatible stages while
507/// enforcing [`EditOptions`] output, reference-scan and verification limits.
508///
509/// Each stage runs through [`Document::edit_with_options`],
510/// [`Document::sort_with_options`], or [`Document::format_with_options`] and
511/// re-parses intermediate output strictly with [`EditOptions::parse_limits`].
512/// When a format policy combines [`QuoteStyle::Unquoted`] with other trivia
513/// rewrites, unquoting runs in a separate verified stage before the remaining
514/// trivia changes so both converge in one batch. An empty `fixes` slice runs no
515/// stages and returns an empty [`BatchResult`].
516///
517/// # Errors
518///
519/// Returns [`LintError::Edit`] with [`EditError::Limit`] when any configured
520/// output, reference or parse limit is exceeded, [`LintError::Conflict`] for
521/// incompatible fixes, [`LintError::Format`] when formatting/sorting is
522/// refused, or [`LintError::Parse`] when an intermediate output fails strict
523/// parsing for non-limit diagnostics.
524pub fn apply_batch_with_options(
525    document: &Document<'_>,
526    fixes: &[Fix],
527    edit_options: EditOptions,
528) -> Result<BatchResult, LintError> {
529    let PlannedFixes {
530        renames,
531        format,
532        sort,
533    } = plan_fixes(fixes)?;
534    let mut output = document.source().to_owned();
535    let mut stages = Vec::new();
536    if !renames.is_empty() {
537        let current = parse_strict_bounded(&output, document.dialect(), edit_options.parse_limits)?;
538        let edits: Vec<Edit<'_>> = renames
539            .iter()
540            .map(|(entry, key)| Edit::Rename { entry: *entry, key })
541            .collect();
542        let result = current
543            .edit_with_options(&edits, edit_options)
544            .map_err(LintError::Edit)?;
545        output.clear();
546        output.push_str(result.as_str());
547        stages.push(FixResult::Edits(result));
548    }
549    if sort {
550        let current = parse_strict_bounded(&output, document.dialect(), edit_options.parse_limits)?;
551        let result = current
552            .sort_with_options(edit_options)
553            .map_err(map_format_edit_error)?;
554        output.clear();
555        output.push_str(result.as_str());
556        stages.push(FixResult::Format(result));
557    }
558    if let Some(options) = format {
559        if needs_two_pass_unquote(options) {
560            let unquote_only = FormatOptions::default().with_quote_style(QuoteStyle::Unquoted);
561            let rest = options.with_quote_style(QuoteStyle::Preserve);
562            let current =
563                parse_strict_bounded(&output, document.dialect(), edit_options.parse_limits)?;
564            let pass1 = current
565                .format_with_options(&unquote_only, edit_options)
566                .map_err(map_format_edit_error)?;
567            let pass1_changed = !pass1.is_empty();
568            if pass1_changed {
569                output.clear();
570                output.push_str(pass1.as_str());
571                stages.push(FixResult::Format(pass1));
572                let mid =
573                    parse_strict_bounded(&output, document.dialect(), edit_options.parse_limits)?;
574                let pass2 = mid
575                    .format_with_options(&rest, edit_options)
576                    .map_err(map_format_edit_error)?;
577                if !pass2.is_empty() {
578                    output.clear();
579                    output.push_str(pass2.as_str());
580                    stages.push(FixResult::Format(pass2));
581                }
582            } else {
583                let pass2 = current
584                    .format_with_options(&rest, edit_options)
585                    .map_err(map_format_edit_error)?;
586                output.clear();
587                output.push_str(pass2.as_str());
588                stages.push(FixResult::Format(pass2));
589            }
590        } else {
591            let current =
592                parse_strict_bounded(&output, document.dialect(), edit_options.parse_limits)?;
593            let result = current
594                .format_with_options(&options, edit_options)
595                .map_err(map_format_edit_error)?;
596            output.clear();
597            output.push_str(result.as_str());
598            stages.push(FixResult::Format(result));
599        }
600    }
601    Ok(BatchResult {
602        empty: output == document.source(),
603        output,
604        stages,
605    })
606}
607
608/// An error while applying a lint fix.
609#[derive(Debug, Clone, Copy, PartialEq, Eq)]
610#[non_exhaustive]
611pub enum LintError {
612    /// The formatter or sorter refused the output.
613    Format(FormatError),
614    /// The verified edit batch was rejected (including [`EditError::Limit`]).
615    Edit(EditError),
616    /// The supplied fixes cannot be combined in one verified batch.
617    Conflict(&'static str),
618    /// An intermediate verified output could not be parsed again.
619    Parse,
620}
621
622impl fmt::Display for LintError {
623    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
624        match self {
625            Self::Format(error) => write!(formatter, "cannot apply fix: {error}"),
626            Self::Edit(error) => write!(formatter, "cannot apply fix: {error}"),
627            Self::Conflict(message) => write!(formatter, "cannot combine fixes: {message}"),
628            Self::Parse => formatter.write_str("cannot parse an intermediate fix output"),
629        }
630    }
631}
632
633impl std::error::Error for LintError {}
634
635/// Applies one fix request through the document's verified APIs.
636///
637/// Format fixes run a single pass of [`Document::format`]. When a policy
638/// combines [`QuoteStyle::Unquoted`] with other trivia options, use
639/// [`apply_batch`] or [`apply_batch_with_options`] so unquoting runs in its
640/// own verified stage before the remaining trivia rewrites.
641///
642/// # Errors
643///
644/// Returns [`LintError`] when the formatter/sorter refuses the output or the
645/// edit batch is rejected, for example because a rename would collide.
646pub fn apply_fix(document: &Document<'_>, fix: &Fix) -> Result<FixResult, LintError> {
647    apply_fix_with_options(document, fix, EditOptions::new())
648}
649
650/// Applies one fix request through the document's bounded verified APIs.
651///
652/// Format fixes run a single pass of [`Document::format_with_options`]. When a
653/// policy combines [`QuoteStyle::Unquoted`] with other trivia options, use
654/// [`apply_batch_with_options`] so unquoting runs in its own verified stage
655/// before the remaining trivia rewrites.
656///
657/// # Errors
658///
659/// Returns [`LintError::Edit`] with [`EditError::Limit`] when a configured
660/// [`EditOptions`] limit is exceeded, [`LintError::Format`] when the formatter
661/// or sorter refuses the output, or [`LintError::Edit`] when an edit is
662/// rejected.
663pub fn apply_fix_with_options(
664    document: &Document<'_>,
665    fix: &Fix,
666    edit_options: EditOptions,
667) -> Result<FixResult, LintError> {
668    match fix {
669        Fix::Sort => document
670            .sort_with_options(edit_options)
671            .map(FixResult::Format)
672            .map_err(map_format_edit_error),
673        Fix::Format(options) => document
674            .format_with_options(options, edit_options)
675            .map(FixResult::Format)
676            .map_err(map_format_edit_error),
677        Fix::Rename { entry, key } => document
678            .edit_with_options(&[Edit::Rename { entry: *entry, key }], edit_options)
679            .map(FixResult::Edits)
680            .map_err(LintError::Edit),
681    }
682}
683
684/// Applies a batch of compatible fixes in one verified operation.
685///
686/// Multiple renames are applied as one [`Document::edit`] batch, so swaps and
687/// independent renames are verified together. One formatting or sorting fix
688/// can be applied without renames. Mixed rename/format/sort batches and
689/// multiple different format policies return [`LintError::Conflict`]; apply
690/// those with [`apply_batch`] (which also splits combined
691/// [`QuoteStyle::Unquoted`] + trivia policies into two verified stages) or in
692/// separate rounds.
693///
694/// # Errors
695///
696/// Returns [`LintError`] when the fixes conflict, a rename collides, or the
697/// formatter/sorter refuses the output.
698pub fn apply_fixes(document: &Document<'_>, fixes: &[Fix]) -> Result<FixResult, LintError> {
699    apply_fixes_with_options(document, fixes, EditOptions::new())
700}
701
702/// Applies a batch of compatible fixes in one bounded verified operation.
703///
704/// This is [`apply_fixes`] with [`EditOptions`] forwarded to
705/// [`Document::edit_with_options`], [`Document::format_with_options`], or
706/// [`Document::sort_with_options`].
707///
708/// # Errors
709///
710/// Returns [`LintError::Edit`] with [`EditError::Limit`] when a configured
711/// [`EditOptions`] limit is exceeded, [`LintError::Conflict`] when fixes cannot
712/// be combined, [`LintError::Format`] when formatting/sorting is refused, or
713/// [`LintError::Edit`] when an edit is rejected.
714pub fn apply_fixes_with_options(
715    document: &Document<'_>,
716    fixes: &[Fix],
717    edit_options: EditOptions,
718) -> Result<FixResult, LintError> {
719    let PlannedFixes {
720        renames,
721        format,
722        sort,
723    } = plan_fixes(fixes)?;
724    if !renames.is_empty() && (format.is_some() || sort) {
725        return Err(LintError::Conflict(
726            "renames cannot be combined with formatting or sorting",
727        ));
728    }
729    if sort && format.is_some() {
730        return Err(LintError::Conflict(
731            "sorting and formatting cannot be combined in one batch",
732        ));
733    }
734    if !renames.is_empty() {
735        let edits: Vec<Edit<'_>> = renames
736            .iter()
737            .map(|(entry, key)| Edit::Rename { entry: *entry, key })
738            .collect();
739        return document
740            .edit_with_options(&edits, edit_options)
741            .map(FixResult::Edits)
742            .map_err(LintError::Edit);
743    }
744    if let Some(options) = format {
745        return document
746            .format_with_options(&options, edit_options)
747            .map(FixResult::Format)
748            .map_err(map_format_edit_error);
749    }
750    if sort {
751        return document
752            .sort_with_options(edit_options)
753            .map(FixResult::Format)
754            .map_err(map_format_edit_error);
755    }
756    document
757        .edit_with_options(&[], edit_options)
758        .map(FixResult::Edits)
759        .map_err(LintError::Edit)
760}
761
762/// Runs the configured lint rules over `document`.
763///
764/// Findings are ordered by source position. A finding is policy, not a parse
765/// error; parse diagnostics remain available through [`adotenv::parse`].
766#[must_use]
767pub fn lint(document: &Document<'_>, options: LintOptions) -> Vec<Finding> {
768    lint_with_options(document, options, None, EditOptions::new())
769}
770
771/// Runs the configured lint rules and an opt-in [`Schema`] policy over
772/// `document`.
773///
774/// Schema findings never contain document values and never attach automatic
775/// fixes.
776#[must_use]
777pub fn lint_with_schema(
778    document: &Document<'_>,
779    options: LintOptions,
780    schema: &Schema,
781) -> Vec<Finding> {
782    lint_with_options(document, options, Some(schema), EditOptions::new())
783}
784
785/// Runs the configured lint rules and optional [`Schema`] policy over
786/// `document`, using `edit_options` to bound sortability verification for
787/// [`Rule::KeyOrder`].
788///
789/// When `edit_options` prevents a group from being sorted (for example because
790/// `max_references` is exceeded), [`Rule::KeyOrder`] still reports the unsorted
791/// group without attaching [`Fix::Sort`].
792#[must_use]
793pub fn lint_with_options(
794    document: &Document<'_>,
795    options: LintOptions,
796    schema: Option<&Schema>,
797    edit_options: EditOptions,
798) -> Vec<Finding> {
799    let line_index = document.line_index();
800    let mut findings = Vec::new();
801
802    if options.duplicate_keys {
803        let mut entries: BTreeMap<&str, Vec<adotenv::Entry<'_>>> = BTreeMap::new();
804        for entry in document.entries() {
805            entries.entry(entry.key()).or_default().push(entry);
806        }
807        for group in entries.values().filter(|group| group.len() > 1) {
808            for entry in group.iter().skip(1) {
809                findings.push(Finding::new(
810                    Rule::DuplicateKey,
811                    "key is declared more than once",
812                    options.severity_for_rule(Rule::DuplicateKey),
813                    entry.key_span(),
814                    entry.line(),
815                    Some(entry.key()),
816                    None,
817                ));
818            }
819        }
820    }
821
822    if options.key_order {
823        key_order_findings(document, options, edit_options, &line_index, &mut findings);
824    }
825
826    for entry in document.entries() {
827        if options.key_case != KeyCase::Off {
828            let expected = match options.key_case {
829                KeyCase::Off => entry.key().to_owned(),
830                KeyCase::Lower => entry.key().to_ascii_lowercase(),
831                KeyCase::Upper => entry.key().to_ascii_uppercase(),
832            };
833            if expected != entry.key() {
834                findings.push(Finding::new(
835                    Rule::KeyCase,
836                    "key does not use the configured case",
837                    options.severity_for_rule(Rule::KeyCase),
838                    entry.key_span(),
839                    entry.line(),
840                    Some(entry.key()),
841                    Some(Fix::Rename {
842                        entry: entry.id(),
843                        key: expected,
844                    }),
845                ));
846            }
847        }
848
849        if let Some(value) = entry.value() {
850            if !value.is_empty() {
851                let expected = match options.quote_style {
852                    QuoteStyle::Double => Quote::Double,
853                    QuoteStyle::Single => Quote::Single,
854                    QuoteStyle::Unquoted => Quote::None,
855                    _ => entry.quote(),
856                };
857                if entry.quote() != expected {
858                    findings.push(Finding::new(
859                        Rule::QuoteStyle,
860                        "value does not use the configured quote style",
861                        options.severity_for_rule(Rule::QuoteStyle),
862                        entry.value_span().unwrap_or_else(|| entry.key_span()),
863                        entry.line(),
864                        Some(entry.key()),
865                        Some(Fix::Format(options.format_options())),
866                    ));
867                }
868            }
869        }
870
871        if whitespace_differs(document, entry, options) {
872            findings.push(Finding::new(
873                Rule::Whitespace,
874                "assignment spacing or trailing whitespace is not normalized",
875                options.severity_for_rule(Rule::Whitespace),
876                entry.tokens().key.clone(),
877                entry.line(),
878                Some(entry.key()),
879                Some(Fix::Format(options.format_options())),
880            ));
881        }
882    }
883
884    if let Some(schema) = schema {
885        schema::schema_findings(document, options, schema, &mut findings);
886    }
887
888    findings.sort_by(|left, right| {
889        left.span
890            .start
891            .cmp(&right.span.start)
892            .then_with(|| left.rule.as_str().cmp(right.rule.as_str()))
893            .then_with(|| left.key.cmp(&right.key))
894    });
895    findings
896}
897
898fn whitespace_differs(
899    document: &Document<'_>,
900    entry: adotenv::Entry<'_>,
901    options: LintOptions,
902) -> bool {
903    let tokens = entry.tokens();
904    if let Some(_separator) = tokens.eq.as_ref() {
905        let before = &document.source()[tokens.space_before_eq.clone()];
906        let after = &document.source()[tokens.space_after_eq.clone()];
907        match options.equals_spacing {
908            EqualsSpacing::None if !before.is_empty() || !after.is_empty() => return true,
909            EqualsSpacing::Spaces if before != " " || after != " " => return true,
910            _ => {}
911        }
912    }
913    options.trim_trailing_whitespace && !tokens.trailing_space.is_empty()
914}
915
916fn key_order_findings(
917    document: &Document<'_>,
918    options: LintOptions,
919    edit_options: EditOptions,
920    line_index: &LineIndex<'_>,
921    findings: &mut Vec<Finding>,
922) {
923    // A group that `Document::sort_with_options` refuses to reorder, for example
924    // one with a self-reference, a cycle, or an exceeded limit, still has an
925    // observable key order. Report it, but only attach the sorting fix when a
926    // sort edit exists.
927    let sortable = document
928        .sort_with_options(edit_options)
929        .map(|sorted| {
930            sorted
931                .edits()
932                .iter()
933                .map(|edit| edit.range.clone())
934                .collect::<Vec<_>>()
935        })
936        .unwrap_or_default();
937    for group in document.groups() {
938        let entries: Vec<_> = group.entries().collect();
939        if entries.len() < 2 {
940            continue;
941        }
942        let keys: Vec<&str> = entries.iter().map(|entry| entry.key()).collect();
943        if keys.windows(2).all(|pair| pair[0] <= pair[1]) {
944            continue;
945        }
946        if keys.iter().any(|key| key.is_empty()) || duplicate_keys(&keys) {
947            // Duplicate and empty keys belong to the duplicate-key rule, and
948            // `Document::sort` never reorders them.
949            continue;
950        }
951        if group.items().any(|item| {
952            !matches!(
953                item.kind(),
954                adotenv::ItemKind::Entry | adotenv::ItemKind::Comment
955            )
956        }) {
957            continue;
958        }
959        let span = group.span();
960        let fix = sortable.contains(&span).then_some(Fix::Sort);
961        findings.push(Finding::new(
962            Rule::KeyOrder,
963            "declarations are not sorted",
964            options.severity_for_rule(Rule::KeyOrder),
965            span.clone(),
966            line_of(line_index, span.start),
967            None,
968            fix,
969        ));
970    }
971}
972
973fn duplicate_keys(keys: &[&str]) -> bool {
974    let mut seen = BTreeSet::new();
975    !keys.iter().all(|key| seen.insert(*key))
976}
977
978fn line_of(index: &LineIndex<'_>, offset: usize) -> usize {
979    index
980        .to_position(offset, ColumnEncoding::Utf8)
981        .map_or(1, |position| position.line + 1)
982}
983
984#[cfg(test)]
985mod tests {
986    use super::*;
987    use adotenv::{parse_strict, parse_with, Dialect};
988
989    #[test]
990    fn defaults_report_only_duplicate_keys() {
991        let doc = parse_strict("B=2\nA=1\nA=3\n").unwrap();
992        let findings = lint(&doc, LintOptions::default());
993        assert_eq!(findings.len(), 1);
994        assert_eq!(findings[0].rule(), Rule::DuplicateKey);
995        assert_eq!(findings[0].line(), 3);
996        assert_eq!(findings[0].key(), Some("A"));
997    }
998
999    #[test]
1000    fn key_order_fix_sorts_through_verified_output() {
1001        let doc = parse_strict("B=2\nA=1\n").unwrap();
1002        let findings = lint(&doc, LintOptions::new().with_key_order(true));
1003        assert_eq!(findings.len(), 1);
1004        assert_eq!(findings[0].rule(), Rule::KeyOrder);
1005        let fixed = apply_fix(&doc, findings[0].fix().unwrap()).unwrap();
1006        assert_eq!(fixed.as_str(), "A=1\nB=2\n");
1007    }
1008
1009    #[test]
1010    fn key_order_reports_unsortable_groups_without_a_fix() {
1011        for source in ["B=$B\nA=1\n", "B='$A'\nA=1\n", "B=$A\nA=$B\n"] {
1012            let doc = parse_strict(source).unwrap();
1013            let findings = lint(&doc, LintOptions::new().with_key_order(true));
1014            assert_eq!(findings.len(), 1, "{source:?}");
1015            assert_eq!(findings[0].rule(), Rule::KeyOrder, "{source:?}");
1016            assert!(findings[0].fix().is_none(), "{source:?}");
1017        }
1018    }
1019
1020    #[test]
1021    fn key_case_fix_renames_one_declaration() {
1022        let doc = parse_strict("lower=1\n").unwrap();
1023        let findings = lint(&doc, LintOptions::new().with_key_case(KeyCase::Upper));
1024        assert_eq!(findings.len(), 1);
1025        let fixed = apply_fix(&doc, findings[0].fix().unwrap()).unwrap();
1026        assert_eq!(fixed.as_str(), "LOWER=1\n");
1027    }
1028
1029    #[test]
1030    fn quote_style_fix_is_verified() {
1031        let doc = parse_strict("A='one'\n").unwrap();
1032        let findings = lint(
1033            &doc,
1034            LintOptions::new().with_quote_style(QuoteStyle::Double),
1035        );
1036        assert_eq!(findings.len(), 1);
1037        let fixed = apply_fix(&doc, findings[0].fix().unwrap()).unwrap();
1038        assert_eq!(fixed.as_str(), "A=\"one\"\n");
1039    }
1040
1041    #[test]
1042    fn whitespace_fix_uses_verified_formatting() {
1043        let doc = parse_strict("A =  one   \n").unwrap();
1044        let findings = lint(
1045            &doc,
1046            LintOptions::new()
1047                .with_equals_spacing(EqualsSpacing::None)
1048                .with_trim_trailing_whitespace(true),
1049        );
1050        assert_eq!(findings.len(), 1);
1051        let fixed = apply_fix(&doc, findings[0].fix().unwrap()).unwrap();
1052        assert_eq!(fixed.as_str(), "A=one\n");
1053    }
1054
1055    #[test]
1056    fn findings_never_contain_values() {
1057        let doc = parse_strict("TOKEN=secret\nTOKEN=other\n").unwrap();
1058        let findings = lint(&doc, LintOptions::default());
1059        let debug = format!("{findings:?}");
1060        assert!(!debug.contains("secret"));
1061        assert!(!debug.contains("other"));
1062        assert!(debug.contains("TOKEN"));
1063    }
1064
1065    #[test]
1066    fn rename_collision_returns_a_structured_error() {
1067        let doc = parse_strict("A=1\na=2\n").unwrap();
1068        let findings = lint(&doc, LintOptions::new().with_key_case(KeyCase::Upper));
1069        let fix = findings
1070            .iter()
1071            .find_map(Finding::fix)
1072            .expect("the lowercase key has a fix");
1073        assert!(matches!(
1074            apply_fix(&doc, fix),
1075            Err(LintError::Edit(EditError::Duplicate(_)))
1076        ));
1077    }
1078
1079    #[test]
1080    fn python_quoted_keys_keep_their_case_policy() {
1081        let doc = parse_with("'A B'=1\n", Dialect::PYTHON_DOTENV).0;
1082        let findings = lint(&doc, LintOptions::new().with_key_case(KeyCase::Upper));
1083        assert_eq!(findings.len(), 0);
1084    }
1085}
1086
1087#[cfg(test)]
1088use adotenv::parse_strict;
1089
1090#[test]
1091fn apply_fixes_batches_independent_renames() {
1092    let doc = parse_strict("a=1\nb=2\n").unwrap();
1093    let findings = lint(&doc, LintOptions::new().with_key_case(KeyCase::Upper));
1094    let fixes: Vec<Fix> = findings
1095        .iter()
1096        .filter_map(|finding| finding.fix().cloned())
1097        .collect();
1098    assert_eq!(fixes.len(), 2);
1099    let result = apply_fixes(&doc, &fixes).unwrap();
1100    assert_eq!(result.as_str(), "A=1\nB=2\n");
1101}
1102
1103#[test]
1104fn apply_fixes_reports_mixed_fix_conflicts() {
1105    let doc = parse_strict("A='one'\n").unwrap();
1106    let fixes = [
1107        Fix::Rename {
1108            entry: 0,
1109            key: "B".to_owned(),
1110        },
1111        Fix::Format(FormatOptions::default().with_quote_style(QuoteStyle::Double)),
1112    ];
1113    assert!(matches!(
1114        apply_fixes(&doc, &fixes),
1115        Err(LintError::Conflict(
1116            "renames cannot be combined with formatting or sorting"
1117        ))
1118    ));
1119}
1120
1121#[test]
1122fn apply_fixes_reports_two_keys_for_one_entry() {
1123    let doc = parse_strict("a=1\n").unwrap();
1124    let fixes = [
1125        Fix::Rename {
1126            entry: 0,
1127            key: "A".to_owned(),
1128        },
1129        Fix::Rename {
1130            entry: 0,
1131            key: "B".to_owned(),
1132        },
1133    ];
1134    assert!(matches!(
1135        apply_fixes(&doc, &fixes),
1136        Err(LintError::Conflict(
1137            "one entry has two different replacement keys"
1138        ))
1139    ));
1140}
1141
1142#[test]
1143fn rule_severity_is_configurable() {
1144    let doc = parse_strict("A=1\nA=2\n").unwrap();
1145    let findings = lint(
1146        &doc,
1147        LintOptions::new().with_severity(Rule::DuplicateKey, Severity::Error),
1148    );
1149    assert_eq!(findings[0].severity(), Severity::Error);
1150}
1151
1152#[test]
1153fn apply_batch_combines_renames_sorting_and_formatting() {
1154    let doc = parse_strict("b='two'\na='one'\n").unwrap();
1155    let findings = lint(
1156        &doc,
1157        LintOptions::new()
1158            .with_key_case(KeyCase::Upper)
1159            .with_key_order(true)
1160            .with_quote_style(QuoteStyle::Double),
1161    );
1162    let fixes: Vec<Fix> = findings
1163        .iter()
1164        .filter_map(|finding| finding.fix().cloned())
1165        .collect();
1166    let result = apply_batch(&doc, &fixes).unwrap();
1167    assert_eq!(result.output(), "A=\"one\"\nB=\"two\"\n");
1168    assert_eq!(result.stages().len(), 3);
1169}
1170
1171#[test]
1172fn apply_batch_rejects_conflicting_renames() {
1173    let doc = parse_strict("a=1\n").unwrap();
1174    let fixes = [
1175        Fix::Rename {
1176            entry: 0,
1177            key: "A".to_owned(),
1178        },
1179        Fix::Rename {
1180            entry: 0,
1181            key: "B".to_owned(),
1182        },
1183    ];
1184    assert!(matches!(
1185        apply_batch(&doc, &fixes),
1186        Err(LintError::Conflict(
1187            "one entry has two different replacement keys"
1188        ))
1189    ));
1190}
1191
1192#[test]
1193fn apply_batch_rejects_different_format_policies() {
1194    let doc = parse_strict("A='one'\n").unwrap();
1195    let fixes = [
1196        Fix::Format(FormatOptions::default().with_quote_style(QuoteStyle::Double)),
1197        Fix::Format(FormatOptions::default().with_quote_style(QuoteStyle::Single)),
1198    ];
1199    assert!(matches!(
1200        apply_batch(&doc, &fixes),
1201        Err(LintError::Conflict(
1202            "different format policies cannot be combined"
1203        ))
1204    ));
1205}
1206
1207#[test]
1208fn apply_batch_without_fixes_is_empty() {
1209    let doc = parse_strict("A=1\n").unwrap();
1210    let result = apply_batch(&doc, &[]).unwrap();
1211    assert!(result.is_empty());
1212    assert_eq!(result.output(), "A=1\n");
1213}
1214
1215#[test]
1216fn apply_batch_reports_no_change_for_a_noop_format() {
1217    let doc = parse_strict("A='one'\n").unwrap();
1218    let result = apply_batch(&doc, &[Fix::Format(FormatOptions::default())]).unwrap();
1219    assert!(result.is_empty());
1220    assert_eq!(result.output(), "A='one'\n");
1221}
1222
1223#[test]
1224fn mutation_regression_assertions_for_rules_whitespace_quotes_and_order() {
1225    use adotenv::parse_strict;
1226
1227    // 1. Distinct Rule::index slots in LintOptions::with_severity.
1228    let opts = LintOptions::new()
1229        .with_severity(Rule::DuplicateKey, Severity::Error)
1230        .with_severity(Rule::KeyOrder, Severity::Info)
1231        .with_severity(Rule::KeyCase, Severity::Error)
1232        .with_severity(Rule::QuoteStyle, Severity::Info)
1233        .with_severity(Rule::Whitespace, Severity::Error);
1234    assert_eq!(opts.severity_for_rule(Rule::DuplicateKey), Severity::Error);
1235    assert_eq!(opts.severity_for_rule(Rule::KeyOrder), Severity::Info);
1236    assert_eq!(opts.severity_for_rule(Rule::KeyCase), Severity::Error);
1237    assert_eq!(opts.severity_for_rule(Rule::QuoteStyle), Severity::Info);
1238    assert_eq!(opts.severity_for_rule(Rule::Whitespace), Severity::Error);
1239
1240    // 2. Finding::message, FixResult::edits, BatchResult::is_empty, LintError::fmt.
1241    let dup_doc = parse_strict("A=1\nA=2\n").unwrap();
1242    let dup_findings = lint(&dup_doc, LintOptions::default());
1243    assert_eq!(dup_findings[0].message(), "key is declared more than once");
1244
1245    let rename_doc = parse_strict("a=1\n").unwrap();
1246    let rename_fix = Fix::Rename {
1247        entry: 0,
1248        key: "A".to_owned(),
1249    };
1250    let fixed = apply_fix(&rename_doc, &rename_fix).unwrap();
1251    assert_eq!(fixed.edits().len(), 1);
1252    let batched = apply_batch(&rename_doc, &[rename_fix]).unwrap();
1253    assert!(!batched.is_empty());
1254    assert_eq!(
1255        LintError::Conflict("conflict reason").to_string(),
1256        "cannot combine fixes: conflict reason"
1257    );
1258
1259    // 3. apply_fixes with standalone Fix::Sort and standalone Fix::Format.
1260    let unsorted = parse_strict("B=2\nA=1\n").unwrap();
1261    let sorted = apply_fixes(&unsorted, &[Fix::Sort]).unwrap();
1262    assert_eq!(sorted.as_str(), "A=1\nB=2\n");
1263
1264    // 4. QuoteStyle::Single and QuoteStyle::Unquoted detection.
1265    let quoted = parse_strict("A=\"one\"\n").unwrap();
1266    let single_findings = lint(
1267        &quoted,
1268        LintOptions::new().with_quote_style(QuoteStyle::Single),
1269    );
1270    assert_eq!(single_findings.len(), 1);
1271    assert_eq!(single_findings[0].rule(), Rule::QuoteStyle);
1272    let unquoted_findings = lint(
1273        &quoted,
1274        LintOptions::new().with_quote_style(QuoteStyle::Unquoted),
1275    );
1276    assert_eq!(unquoted_findings.len(), 1);
1277    assert_eq!(unquoted_findings[0].rule(), Rule::QuoteStyle);
1278
1279    // 5. whitespace_differs: EqualsSpacing::None / Spaces (before & after) and trailing space.
1280    let eq_none = LintOptions::new().with_equals_spacing(EqualsSpacing::None);
1281    assert_eq!(lint(&parse_strict("A=1\n").unwrap(), eq_none), Vec::new());
1282    assert_eq!(lint(&parse_strict("A =1\n").unwrap(), eq_none).len(), 1);
1283    assert_eq!(lint(&parse_strict("A= 1\n").unwrap(), eq_none).len(), 1);
1284
1285    let eq_spaces = LintOptions::new().with_equals_spacing(EqualsSpacing::Spaces);
1286    assert_eq!(
1287        lint(&parse_strict("A = 1\n").unwrap(), eq_spaces),
1288        Vec::new()
1289    );
1290    assert_eq!(lint(&parse_strict("A= 1\n").unwrap(), eq_spaces).len(), 1);
1291    assert_eq!(lint(&parse_strict("A =1\n").unwrap(), eq_spaces).len(), 1);
1292
1293    let trim_off = LintOptions::new().with_trim_trailing_whitespace(false);
1294    let trim_on = LintOptions::new().with_trim_trailing_whitespace(true);
1295    assert_eq!(lint(&parse_strict("A=1 \n").unwrap(), trim_off), Vec::new());
1296    assert_eq!(lint(&parse_strict("A=1\n").unwrap(), trim_on), Vec::new());
1297    assert_eq!(lint(&parse_strict("A=1 \n").unwrap(), trim_on).len(), 1);
1298
1299    // 6. key_order_findings: 3-entry group, duplicate-key skip, and line_of (> line 1).
1300    let order_only = LintOptions::new()
1301        .with_duplicate_keys(false)
1302        .with_key_order(true);
1303    let three = parse_strict("# header\n\nC=3\nB=2\nA=1\n").unwrap();
1304    let three_findings = lint(&three, order_only);
1305    assert_eq!(three_findings.len(), 1);
1306    assert_eq!(three_findings[0].line(), 3);
1307
1308    let with_dups = parse_strict("B=2\nA=1\nA=3\n").unwrap();
1309    assert_eq!(lint(&with_dups, order_only), Vec::new());
1310}
1311
1312#[test]
1313fn all_nine_rule_indices_and_names_are_distinct() {
1314    let opts = LintOptions::new()
1315        .with_severity(Rule::DuplicateKey, Severity::Error)
1316        .with_severity(Rule::KeyOrder, Severity::Info)
1317        .with_severity(Rule::KeyCase, Severity::Error)
1318        .with_severity(Rule::QuoteStyle, Severity::Info)
1319        .with_severity(Rule::Whitespace, Severity::Error)
1320        .with_severity(Rule::MissingKey, Severity::Info)
1321        .with_severity(Rule::UnknownKey, Severity::Error)
1322        .with_severity(Rule::EmptyValue, Severity::Info)
1323        .with_severity(Rule::InvalidValue, Severity::Error);
1324    assert_eq!(opts.severity_for_rule(Rule::MissingKey), Severity::Info);
1325    assert_eq!(opts.severity_for_rule(Rule::UnknownKey), Severity::Error);
1326    assert_eq!(opts.severity_for_rule(Rule::EmptyValue), Severity::Info);
1327    assert_eq!(opts.severity_for_rule(Rule::InvalidValue), Severity::Error);
1328    assert_eq!(Rule::MissingKey.as_str(), "missing-key");
1329    assert_eq!(Rule::UnknownKey.as_str(), "unknown-key");
1330    assert_eq!(Rule::EmptyValue.as_str(), "empty-value");
1331    assert_eq!(Rule::InvalidValue.as_str(), "invalid-value");
1332}
1333
1334#[test]
1335fn bounded_apply_fix_fixes_and_batch_enforce_edit_options() {
1336    use adotenv::{LimitKind, ParseOptions};
1337
1338    let doc = parse_strict("a='one'\n").unwrap();
1339    let double = Fix::Format(FormatOptions::default().with_quote_style(QuoteStyle::Double));
1340    let rename = Fix::Rename {
1341        entry: 0,
1342        key: "LONG_KEY_NAME".to_owned(),
1343    };
1344
1345    // Output-byte cap on apply_fix_with_options (format and rename).
1346    let tight_bytes = EditOptions::new().with_max_output_bytes(10);
1347    assert!(matches!(
1348        apply_fix_with_options(&doc, &rename, tight_bytes),
1349        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::OutputBytes
1350    ));
1351    let spacing = Fix::Format(FormatOptions::default().with_equals_spacing(EqualsSpacing::Spaces));
1352    assert!(matches!(
1353        apply_fix_with_options(&doc, &spacing, EditOptions::new().with_max_output_bytes(8)),
1354        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::OutputBytes
1355    ));
1356    assert!(matches!(
1357        apply_fixes_with_options(
1358            &doc,
1359            std::slice::from_ref(&spacing),
1360            EditOptions::new().with_max_output_bytes(8)
1361        ),
1362        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::OutputBytes
1363    ));
1364    assert!(matches!(
1365        apply_batch_with_options(&doc, &[rename, double], tight_bytes),
1366        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::OutputBytes
1367    ));
1368
1369    // Output-line cap on apply_fix_with_options.
1370    let two_lines = parse_strict("B=2\nA=1\n").unwrap();
1371    assert!(matches!(
1372        apply_fix_with_options(
1373            &two_lines,
1374            &Fix::Sort,
1375            EditOptions::new().with_max_output_lines(1),
1376        ),
1377        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::Lines
1378    ));
1379
1380    // Reference cap bounds both lint_with_options (KeyOrder fix attachment) and apply_fix/batch.
1381    let with_ref = parse_strict("C=3\nB=$A\nA=1\n").unwrap();
1382    let no_refs = EditOptions::new().with_max_references(0);
1383    let limited_findings = lint_with_options(
1384        &with_ref,
1385        LintOptions::new().with_key_order(true),
1386        None,
1387        no_refs,
1388    );
1389    assert_eq!(limited_findings.len(), 1);
1390    assert_eq!(limited_findings[0].rule(), Rule::KeyOrder);
1391    assert!(limited_findings[0].fix().is_none());
1392
1393    let bounded_ok = lint_with_options(
1394        &with_ref,
1395        LintOptions::new().with_key_order(true),
1396        None,
1397        EditOptions::new().with_max_references(2),
1398    );
1399    assert_eq!(bounded_ok.len(), 1);
1400    assert_eq!(bounded_ok[0].fix(), Some(&Fix::Sort));
1401
1402    assert!(matches!(
1403        apply_fix_with_options(&with_ref, &Fix::Sort, no_refs),
1404        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::References
1405    ));
1406    assert!(matches!(
1407        apply_fixes_with_options(&with_ref, &[Fix::Sort], no_refs),
1408        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::References
1409    ));
1410    assert!(matches!(
1411        apply_batch_with_options(&with_ref, &[Fix::Sort], no_refs),
1412        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::References
1413    ));
1414
1415    // Parse-limit cap during apply_batch_with_options maps to EditError::Limit, not Parse.
1416    let parse_limited = EditOptions::new().with_parse_limits(ParseOptions::new().with_max_lines(1));
1417    assert!(matches!(
1418        apply_batch_with_options(&two_lines, &[Fix::Sort], parse_limited),
1419        Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::Lines
1420    ));
1421
1422    // Non-limit parse failure in apply_batch_with_options still maps to LintError::Parse.
1423    let (invalid_doc, _) = adotenv::parse("BAD LINE\nB=2\nA=1\n");
1424    assert_eq!(
1425        apply_batch_with_options(&invalid_doc, &[Fix::Sort], EditOptions::new()).unwrap_err(),
1426        LintError::Parse
1427    );
1428}
1429
1430#[test]
1431fn apply_batch_handles_two_pass_unquoted_with_trivia_and_renames() {
1432    let doc = parse_strict("b = \"two\"   \na = \"one\"\n").unwrap();
1433    let policy = LintOptions::new()
1434        .with_key_case(KeyCase::Upper)
1435        .with_key_order(true)
1436        .with_quote_style(QuoteStyle::Unquoted)
1437        .with_equals_spacing(EqualsSpacing::None)
1438        .with_trim_trailing_whitespace(true);
1439    let findings = lint(&doc, policy);
1440    let fixes: Vec<Fix> = findings
1441        .iter()
1442        .filter_map(|finding| finding.fix().cloned())
1443        .collect();
1444    let batch = apply_batch(&doc, &fixes).unwrap();
1445    assert_eq!(batch.output(), "A=one\nB=two\n");
1446    assert!(!batch.is_empty());
1447
1448    // Pass 1 (unquote) empty, pass 2 (trivia) changes spacing.
1449    let spacing_only = parse_strict("A = plain   \n").unwrap();
1450    let fmt_fix = Fix::Format(
1451        FormatOptions::default()
1452            .with_quote_style(QuoteStyle::Unquoted)
1453            .with_equals_spacing(EqualsSpacing::None)
1454            .with_trim_trailing_whitespace(true),
1455    );
1456    let res1 = apply_batch(&spacing_only, std::slice::from_ref(&fmt_fix)).unwrap();
1457    assert_eq!(res1.output(), "A=plain\n");
1458    assert_eq!(res1.stages().len(), 1);
1459
1460    // Pass 1 (unquote) changes quotes, pass 2 (trivia) is already normalized.
1461    let unquote_only = parse_strict("A=\"plain\"\n").unwrap();
1462    let res2 = apply_batch(&unquote_only, std::slice::from_ref(&fmt_fix)).unwrap();
1463    assert_eq!(res2.output(), "A=plain\n");
1464    assert_eq!(res2.stages().len(), 1);
1465
1466    // Both passes no-op -> empty batch.
1467    let clean = parse_strict("A=plain\n").unwrap();
1468    let res3 = apply_batch(&clean, &[fmt_fix]).unwrap();
1469    assert!(res3.is_empty());
1470    assert_eq!(res3.output(), "A=plain\n");
1471
1472    // Each trivia option combined individually with QuoteStyle::Unquoted uses two-pass convergence.
1473    let eq_doc = parse_strict("A = \"plain\"\n").unwrap();
1474    let eq_res = apply_batch(
1475        &eq_doc,
1476        &[Fix::Format(
1477            FormatOptions::default()
1478                .with_quote_style(QuoteStyle::Unquoted)
1479                .with_equals_spacing(EqualsSpacing::None),
1480        )],
1481    )
1482    .unwrap();
1483    assert_eq!(eq_res.output(), "A=plain\n");
1484    assert_eq!(eq_res.stages().len(), 2);
1485
1486    let trim_doc = parse_strict("A=\"plain\"   \n").unwrap();
1487    let trim_res = apply_batch(
1488        &trim_doc,
1489        &[Fix::Format(
1490            FormatOptions::default()
1491                .with_quote_style(QuoteStyle::Unquoted)
1492                .with_trim_trailing_whitespace(true),
1493        )],
1494    )
1495    .unwrap();
1496    assert_eq!(trim_res.output(), "A=plain\n");
1497    assert_eq!(trim_res.stages().len(), 2);
1498
1499    let blank_doc = parse_strict("A=\"plain\"\n\n\nB=2\n").unwrap();
1500    let blank_res = apply_batch(
1501        &blank_doc,
1502        &[Fix::Format(
1503            FormatOptions::default()
1504                .with_quote_style(QuoteStyle::Unquoted)
1505                .with_blank_lines(BlankLines::Collapse),
1506        )],
1507    )
1508    .unwrap();
1509    assert_eq!(blank_res.output(), "A=plain\n\nB=2\n");
1510    assert_eq!(blank_res.stages().len(), 2);
1511
1512    let nl_doc = parse_strict("A=\"plain\"").unwrap();
1513    let nl_res = apply_batch(
1514        &nl_doc,
1515        &[Fix::Format(
1516            FormatOptions::default()
1517                .with_quote_style(QuoteStyle::Unquoted)
1518                .with_final_newline(FinalNewline::Ensure),
1519        )],
1520    )
1521    .unwrap();
1522    assert_eq!(nl_res.output(), "A=plain\n");
1523    assert_eq!(nl_res.stages().len(), 2);
1524
1525    // Non-Unquoted quote style with trivia uses a single format stage, not two-pass unquote.
1526    let double_res = apply_batch(
1527        &eq_doc,
1528        &[Fix::Format(
1529            FormatOptions::default()
1530                .with_quote_style(QuoteStyle::Single)
1531                .with_equals_spacing(EqualsSpacing::None),
1532        )],
1533    )
1534    .unwrap();
1535    assert_eq!(double_res.output(), "A='plain'\n");
1536    assert_eq!(double_res.stages().len(), 1);
1537}
1538
1539#[test]
1540fn apply_batch_parse_strict_bounded_distinguishes_warnings_from_errors() {
1541    // parse_strict_bounded with max_diagnostics allows warnings (Severity::Warning)
1542    // while still rejecting errors (Severity::Error).
1543    let warn_opts =
1544        EditOptions::new().with_parse_limits(adotenv::ParseOptions::new().with_max_diagnostics(10));
1545    let dup_doc = parse_strict("A=1\nA=2\n").unwrap();
1546    let dup_res = apply_batch_with_options(
1547        &dup_doc,
1548        &[Fix::Format(
1549            FormatOptions::default().with_equals_spacing(EqualsSpacing::Spaces),
1550        )],
1551        warn_opts,
1552    )
1553    .unwrap();
1554    assert_eq!(dup_res.output(), "A = 1\nA = 2\n");
1555
1556    let (err_doc, _) = adotenv::parse("BAD KEY=1\nA=1\n");
1557    assert_eq!(
1558        apply_batch_with_options(
1559            &err_doc,
1560            &[Fix::Format(
1561                FormatOptions::default().with_equals_spacing(EqualsSpacing::Spaces),
1562            )],
1563            warn_opts,
1564        )
1565        .unwrap_err(),
1566        LintError::Parse
1567    );
1568}