pub mod config;
pub mod schema;
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_doctests {}
pub use adotenv::EditOptions;
pub use config::{
discover_config, load_effective_config, parse_dialect, parse_equals_spacing, parse_key_case,
parse_output_format, parse_quote_style, ConfigError, ConfigExplicit, IgnoredPaths,
KeySchemaConfig, LintConfig, LintPolicy, OutputFormat, RuleSeverity, SchemaConfig,
};
pub use schema::{KeySchema, Schema, ValueShape};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::ops::Range;
use adotenv::{
parse_strict_with_options, parse_with_options, BlankLines, ColumnEncoding, Diagnostic, Dialect,
Document, Edit, EditError, EqualsSpacing, FinalNewline, FormatError, FormatOptions,
FormatResult, InsertPosition, LineIndex, ParseOptions, Quote, QuoteStyle, Severity,
VerifiedEdits,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Rule {
DuplicateKey,
KeyOrder,
KeyCase,
QuoteStyle,
Whitespace,
MissingKey,
UnknownKey,
EmptyValue,
InvalidValue,
DeprecatedKey,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct RuleExplanation {
pub id: &'static str,
pub summary: &'static str,
pub default_behavior: &'static str,
pub autofix: &'static str,
pub config: &'static str,
pub rationale: &'static str,
}
impl Rule {
pub const ALL: &'static [Self] = &[
Self::DuplicateKey,
Self::KeyOrder,
Self::KeyCase,
Self::QuoteStyle,
Self::Whitespace,
Self::MissingKey,
Self::UnknownKey,
Self::EmptyValue,
Self::InvalidValue,
Self::DeprecatedKey,
];
const fn index(self) -> usize {
match self {
Self::DuplicateKey => 0,
Self::KeyOrder => 1,
Self::KeyCase => 2,
Self::QuoteStyle => 3,
Self::Whitespace => 4,
Self::MissingKey => 5,
Self::UnknownKey => 6,
Self::EmptyValue => 7,
Self::InvalidValue => 8,
Self::DeprecatedKey => 9,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::DuplicateKey => "duplicate-key",
Self::KeyOrder => "key-order",
Self::KeyCase => "key-case",
Self::QuoteStyle => "quote-style",
Self::Whitespace => "whitespace",
Self::MissingKey => "missing-key",
Self::UnknownKey => "unknown-key",
Self::EmptyValue => "empty-value",
Self::InvalidValue => "invalid-value",
Self::DeprecatedKey => "deprecated-key",
}
}
#[must_use]
pub fn from_name(name: &str) -> Option<Self> {
match name {
"duplicate-key" => Some(Self::DuplicateKey),
"key-order" => Some(Self::KeyOrder),
"key-case" => Some(Self::KeyCase),
"quote-style" => Some(Self::QuoteStyle),
"whitespace" => Some(Self::Whitespace),
"missing-key" => Some(Self::MissingKey),
"unknown-key" => Some(Self::UnknownKey),
"empty-value" => Some(Self::EmptyValue),
"invalid-value" => Some(Self::InvalidValue),
"deprecated-key" => Some(Self::DeprecatedKey),
_ => None,
}
}
#[must_use]
pub const fn explain(self) -> RuleExplanation {
match self {
Self::DuplicateKey => RuleExplanation {
id: "duplicate-key",
summary: "Reports keys declared more than once in the same document.",
default_behavior: "on (warning)",
autofix: "none",
config: "[rules] duplicate-key = \"off\" | \"warning\" | \"error\"",
rationale: "Repeated declarations are usually accidental and make effective values depend on the active dialect's duplicate-key policy.",
},
Self::KeyOrder => RuleExplanation {
id: "key-order",
summary: "Reports declaration groups whose keys are not in sorted order.",
default_behavior: "off (warning when enabled)",
autofix: "verified sort (when group has no reference cycle or limit exceeded)",
config: "key_order = true, [rules] key-order, CLI --key-order",
rationale: "Keeping each blank-line-separated group sorted reduces merge conflicts and makes large .env files easier to scan while preserving reference dependencies.",
},
Self::KeyCase => RuleExplanation {
id: "key-case",
summary: "Reports keys that do not match the configured ASCII letter case.",
default_behavior: "off (warning when enabled)",
autofix: "verified rename",
config: "key_case = \"upper\" | \"lower\", [rules] key-case = \"off\" | \"warning\" | \"error\", CLI --key-case",
rationale: "Consistent key casing avoids subtle mismatches across shells, deployment platforms, and case-sensitive environments.",
},
Self::QuoteStyle => RuleExplanation {
id: "quote-style",
summary: "Reports non-empty values that do not use the configured quote style.",
default_behavior: "preserve (warning when enabled)",
autofix: "verified format (two-pass when unquoting with trivia options)",
config: "quote_style = \"double\" | \"single\" | \"unquoted\" | \"preserve\", [rules] quote-style, CLI --quote-style",
rationale: "Enforcing a uniform quoting style prevents accidental expansion or escape differences when values are edited.",
},
Self::Whitespace => RuleExplanation {
id: "whitespace",
summary: "Reports non-normalized assignment spacing or trailing whitespace.",
default_behavior: "preserve (warning when enabled)",
autofix: "verified format",
config: "equals_spacing = \"none\" | \"spaces\" | \"preserve\", trim_trailing_whitespace = true, [rules] whitespace, CLI --equals-spacing / --trim-trailing-whitespace",
rationale: "Normalizing spacing around assignment separators and trimming trailing horizontal whitespace eliminates noisy diffs.",
},
Self::MissingKey => RuleExplanation {
id: "missing-key",
summary: "Reports required keys declared in a Schema or .env.example that are absent.",
default_behavior: "schema opt-in (warning when a schema is active)",
autofix: "verified empty placeholder insert (KEY=); explicit via apply_fix, apply_batch_with_policy, or CLI --fix --fix-missing",
config: "[schema] example = \".env.example\", [schema.keys.<KEY>] required = true, [rules] missing-key, CLI --example / --fix-missing",
rationale: "Catching missing required keys before deployment prevents startup failures without ever exposing or copying secret values.",
},
Self::UnknownKey => RuleExplanation {
id: "unknown-key",
summary: "Reports keys absent from a closed Schema (allow_unknown = false).",
default_behavior: "schema opt-in (warning when allow_unknown = false)",
autofix: "none",
config: "[schema] allow_unknown = false, [rules] unknown-key, CLI --no-unknown-keys",
rationale: "Rejecting undeclared keys catches typos and stale variables that are no longer read by the application.",
},
Self::EmptyValue => RuleExplanation {
id: "empty-value",
summary: "Reports disallowed empty (KEY=) or bare (KEY) declarations under a Schema.",
default_behavior: "schema opt-in (warning when a schema disallows empty or bare values)",
autofix: "none",
config: "[schema] allow_empty = false, [schema.keys.<KEY>] allow_empty / allow_bare, [rules] empty-value, CLI --no-empty-values",
rationale: "Typed keys and strict schemas often require explicit non-empty values rather than blank placeholders or bare declarations.",
},
Self::InvalidValue => RuleExplanation {
id: "invalid-value",
summary: "Reports decoded literal values failing their Schema ValueShape or literal bounds.",
default_behavior: "schema opt-in (warning when a schema defines shapes or bounds)",
autofix: "none",
config: "[schema.keys.<KEY>] shape / one_of / prefix / suffix / min_len / max_len, [rules] invalid-value",
rationale: "Validates literal values (such as ports, URLs, IP addresses, hosts, socket addresses, emails, enums, prefixes, suffixes, and length bounds) without expanding references or printing values.",
},
Self::DeprecatedKey => RuleExplanation {
id: "deprecated-key",
summary: "Reports declared keys marked deprecated in the active Schema.",
default_behavior: "schema opt-in (warning when a schema key sets deprecated)",
autofix: "none",
config: "[schema.keys.<KEY>] deprecated = true | \"reason\" (typically with required = false), [rules] deprecated-key",
rationale: "Surfaces migrations away from legacy environment variable names directly in CI and editors without exposing values.",
},
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum KeyCase {
#[default]
Off,
Lower,
Upper,
}
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct LintOptions {
pub duplicate_keys: bool,
pub key_order: bool,
pub key_case: KeyCase,
pub quote_style: QuoteStyle,
pub equals_spacing: EqualsSpacing,
pub trim_trailing_whitespace: bool,
pub missing_keys: bool,
pub unknown_keys: bool,
pub empty_values: bool,
pub invalid_values: bool,
pub deprecated_keys: bool,
severities: [Severity; 10],
}
impl Default for LintOptions {
fn default() -> Self {
Self::new()
}
}
impl LintOptions {
#[must_use]
pub const fn new() -> Self {
Self {
duplicate_keys: true,
key_order: false,
key_case: KeyCase::Off,
quote_style: QuoteStyle::Preserve,
equals_spacing: EqualsSpacing::Preserve,
trim_trailing_whitespace: false,
missing_keys: true,
unknown_keys: true,
empty_values: true,
invalid_values: true,
deprecated_keys: true,
severities: [Severity::Warning; 10],
}
}
#[must_use]
pub const fn with_duplicate_keys(mut self, value: bool) -> Self {
self.duplicate_keys = value;
self
}
#[must_use]
pub const fn with_key_order(mut self, value: bool) -> Self {
self.key_order = value;
self
}
#[must_use]
pub const fn with_key_case(mut self, value: KeyCase) -> Self {
self.key_case = value;
self
}
#[must_use]
pub const fn with_quote_style(mut self, value: QuoteStyle) -> Self {
self.quote_style = value;
self
}
#[must_use]
pub const fn with_equals_spacing(mut self, value: EqualsSpacing) -> Self {
self.equals_spacing = value;
self
}
#[must_use]
pub const fn with_trim_trailing_whitespace(mut self, value: bool) -> Self {
self.trim_trailing_whitespace = value;
self
}
#[must_use]
pub const fn with_missing_keys(mut self, value: bool) -> Self {
self.missing_keys = value;
self
}
#[must_use]
pub const fn with_unknown_keys(mut self, value: bool) -> Self {
self.unknown_keys = value;
self
}
#[must_use]
pub const fn with_empty_values(mut self, value: bool) -> Self {
self.empty_values = value;
self
}
#[must_use]
pub const fn with_invalid_values(mut self, value: bool) -> Self {
self.invalid_values = value;
self
}
#[must_use]
pub const fn with_deprecated_keys(mut self, value: bool) -> Self {
self.deprecated_keys = value;
self
}
#[must_use]
pub const fn with_severity(mut self, rule: Rule, severity: Severity) -> Self {
self.severities[rule.index()] = severity;
self
}
#[must_use]
pub const fn severity_for_rule(self, rule: Rule) -> Severity {
self.severities[rule.index()]
}
fn format_options(self) -> FormatOptions {
FormatOptions::default()
.with_quote_style(self.quote_style)
.with_equals_spacing(self.equals_spacing)
.with_trim_trailing_whitespace(self.trim_trailing_whitespace)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
rule: Rule,
message: &'static str,
detail: Option<String>,
severity: Severity,
span: Range<usize>,
line: usize,
key: Option<String>,
fix: Option<Fix>,
}
impl Finding {
pub(crate) fn new(
rule: Rule,
message: &'static str,
severity: Severity,
span: Range<usize>,
line: usize,
key: Option<&str>,
fix: Option<Fix>,
) -> Self {
Self::with_detail(rule, message, severity, span, line, key, None, fix)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn with_detail(
rule: Rule,
message: &'static str,
severity: Severity,
span: Range<usize>,
line: usize,
key: Option<&str>,
detail: Option<&str>,
fix: Option<Fix>,
) -> Self {
Self {
rule,
message,
detail: detail.map(str::to_owned),
severity,
span,
line,
key: key.map(str::to_owned),
fix,
}
}
#[must_use]
pub const fn rule(&self) -> Rule {
self.rule
}
#[must_use]
pub const fn message(&self) -> &'static str {
self.message
}
#[must_use]
pub fn detail(&self) -> Option<&str> {
self.detail.as_deref()
}
#[must_use]
pub const fn severity(&self) -> Severity {
self.severity
}
#[must_use]
pub fn span(&self) -> Range<usize> {
self.span.clone()
}
#[must_use]
pub const fn line(&self) -> usize {
self.line
}
#[must_use]
pub fn key(&self) -> Option<&str> {
self.key.as_deref()
}
#[must_use]
pub const fn fix(&self) -> Option<&Fix> {
self.fix.as_ref()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Fix {
Sort,
Format(FormatOptions),
Rename {
entry: usize,
key: String,
},
InsertEmpty {
key: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub struct BatchOptions {
pub edit_options: EditOptions,
pub insert_missing: bool,
}
impl BatchOptions {
#[must_use]
pub const fn new() -> Self {
Self {
edit_options: EditOptions::new(),
insert_missing: false,
}
}
#[must_use]
pub const fn with_edit_options(mut self, edit_options: EditOptions) -> Self {
self.edit_options = edit_options;
self
}
#[must_use]
pub const fn with_insert_missing(mut self, insert_missing: bool) -> Self {
self.insert_missing = insert_missing;
self
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum FixResult {
Format(FormatResult),
Edits(VerifiedEdits),
}
impl FixResult {
#[must_use]
pub fn as_str(&self) -> &str {
match self {
Self::Format(result) => result.as_str(),
Self::Edits(result) => result.as_str(),
}
}
#[must_use]
pub fn edits(&self) -> &[adotenv::TextEdit] {
match self {
Self::Format(result) => result.edits(),
Self::Edits(result) => result.edits(),
}
}
}
#[derive(Debug)]
pub struct BatchResult {
output: String,
stages: Vec<FixResult>,
empty: bool,
}
impl BatchResult {
#[must_use]
pub fn output(&self) -> &str {
&self.output
}
#[must_use]
pub fn stages(&self) -> &[FixResult] {
&self.stages
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.empty
}
}
struct PlannedFixes {
renames: Vec<(usize, String)>,
inserts: Vec<String>,
format: Option<FormatOptions>,
sort: bool,
}
fn plan_fixes(fixes: &[Fix]) -> Result<PlannedFixes, LintError> {
let mut renames: Vec<(usize, String)> = Vec::new();
let mut rename_positions: BTreeMap<usize, usize> = BTreeMap::new();
let mut inserts: Vec<String> = Vec::new();
let mut seen_inserts: BTreeSet<&str> = BTreeSet::new();
let mut format = None;
let mut sort = false;
for fix in fixes {
match fix {
Fix::Rename { entry, key } => {
if let Some(&pos) = rename_positions.get(entry) {
if renames[pos].1 != *key {
return Err(LintError::Conflict(
"one entry has two different replacement keys",
));
}
continue;
}
rename_positions.insert(*entry, renames.len());
renames.push((*entry, key.clone()));
}
Fix::InsertEmpty { key } => {
if seen_inserts.insert(key.as_str()) {
inserts.push(key.clone());
}
}
Fix::Format(options) => {
if format.is_some_and(|existing: FormatOptions| existing != *options) {
return Err(LintError::Conflict(
"different format policies cannot be combined",
));
}
format = Some(*options);
}
Fix::Sort => sort = true,
}
}
Ok(PlannedFixes {
renames,
inserts,
format,
sort,
})
}
fn parse_strict_bounded(
source: &str,
dialect: Dialect,
limits: ParseOptions,
) -> Result<Document<'_>, LintError> {
if limits.max_diagnostics.is_some() {
let (document, diagnostics) = parse_with_options(source, dialect, limits);
if let Some(limit) = diagnostics.iter().find_map(Diagnostic::limit) {
return Err(LintError::Edit(EditError::Limit(limit)));
}
if diagnostics
.iter()
.any(|diagnostic| diagnostic.severity() == Severity::Error)
{
return Err(LintError::Parse);
}
return Ok(document);
}
parse_strict_with_options(source, dialect, limits).map_err(|error| map_parse_error(&error))
}
fn map_format_edit_error(error: EditError) -> LintError {
match error {
EditError::WouldChangeMeaning => LintError::Format(FormatError::WouldChangeMeaning),
other => LintError::Edit(other),
}
}
fn map_parse_error(error: &Diagnostic) -> LintError {
error.limit().map_or(LintError::Parse, |limit| {
LintError::Edit(EditError::Limit(limit))
})
}
fn needs_two_pass_unquote(options: FormatOptions) -> bool {
options.quote_style == QuoteStyle::Unquoted
&& (options.equals_spacing != EqualsSpacing::Preserve
|| options.trim_trailing_whitespace
|| options.blank_lines != BlankLines::Preserve
|| options.final_newline != FinalNewline::Preserve)
}
pub fn apply_batch(document: &Document<'_>, fixes: &[Fix]) -> Result<BatchResult, LintError> {
apply_batch_with_options(document, fixes, EditOptions::new())
}
pub fn apply_batch_with_options(
document: &Document<'_>,
fixes: &[Fix],
edit_options: EditOptions,
) -> Result<BatchResult, LintError> {
apply_batch_with_policy(
document,
fixes,
BatchOptions::new().with_edit_options(edit_options),
)
}
#[allow(clippy::too_many_lines)]
pub fn apply_batch_with_policy(
document: &Document<'_>,
fixes: &[Fix],
batch_options: BatchOptions,
) -> Result<BatchResult, LintError> {
let PlannedFixes {
renames,
inserts,
format,
sort,
} = plan_fixes(fixes)?;
let edit_options = batch_options.edit_options;
let mut output = document.source().to_owned();
let mut stages = Vec::new();
if !renames.is_empty() {
let current = parse_strict_bounded(&output, document.dialect(), edit_options.parse_limits)?;
let edits: Vec<Edit<'_>> = renames
.iter()
.map(|(entry, key)| Edit::Rename { entry: *entry, key })
.collect();
let result = current
.edit_with_options(&edits, edit_options)
.map_err(LintError::Edit)?;
output.clear();
output.push_str(result.as_str());
stages.push(FixResult::Edits(result));
}
if batch_options.insert_missing && !inserts.is_empty() {
let current = parse_strict_bounded(&output, document.dialect(), edit_options.parse_limits)?;
let existing: BTreeSet<&str> = current.entries().map(adotenv::Entry::key).collect();
let pending: Vec<Edit<'_>> = inserts
.iter()
.filter(|key| !existing.contains(key.as_str()))
.map(|key| Edit::Insert {
key,
value: Some(""),
position: InsertPosition::End,
})
.collect();
if !pending.is_empty() {
let result = current
.edit_with_options(&pending, edit_options)
.map_err(LintError::Edit)?;
output.clear();
output.push_str(result.as_str());
stages.push(FixResult::Edits(result));
}
}
if sort {
let current = parse_strict_bounded(&output, document.dialect(), edit_options.parse_limits)?;
let result = current
.sort_with_options(edit_options)
.map_err(map_format_edit_error)?;
output.clear();
output.push_str(result.as_str());
stages.push(FixResult::Format(result));
}
if let Some(options) = format {
if needs_two_pass_unquote(options) {
let unquote_only = FormatOptions::default().with_quote_style(QuoteStyle::Unquoted);
let rest = options.with_quote_style(QuoteStyle::Preserve);
let current =
parse_strict_bounded(&output, document.dialect(), edit_options.parse_limits)?;
let pass1 = current
.format_with_options(&unquote_only, edit_options)
.map_err(map_format_edit_error)?;
let pass1_changed = !pass1.is_empty();
if pass1_changed {
output.clear();
output.push_str(pass1.as_str());
stages.push(FixResult::Format(pass1));
let mid =
parse_strict_bounded(&output, document.dialect(), edit_options.parse_limits)?;
let pass2 = mid
.format_with_options(&rest, edit_options)
.map_err(map_format_edit_error)?;
if !pass2.is_empty() {
output.clear();
output.push_str(pass2.as_str());
stages.push(FixResult::Format(pass2));
}
} else {
let pass2 = current
.format_with_options(&rest, edit_options)
.map_err(map_format_edit_error)?;
output.clear();
output.push_str(pass2.as_str());
stages.push(FixResult::Format(pass2));
}
} else {
let current =
parse_strict_bounded(&output, document.dialect(), edit_options.parse_limits)?;
let result = current
.format_with_options(&options, edit_options)
.map_err(map_format_edit_error)?;
output.clear();
output.push_str(result.as_str());
stages.push(FixResult::Format(result));
}
}
Ok(BatchResult {
empty: output == document.source(),
output,
stages,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LintError {
Format(FormatError),
Edit(EditError),
Conflict(&'static str),
Parse,
}
impl fmt::Display for LintError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Format(error) => write!(formatter, "cannot apply fix: {error}"),
Self::Edit(error) => write!(formatter, "cannot apply fix: {error}"),
Self::Conflict(message) => write!(formatter, "cannot combine fixes: {message}"),
Self::Parse => formatter.write_str("cannot parse an intermediate fix output"),
}
}
}
impl std::error::Error for LintError {}
pub fn apply_fix(document: &Document<'_>, fix: &Fix) -> Result<FixResult, LintError> {
apply_fix_with_options(document, fix, EditOptions::new())
}
pub fn apply_fix_with_options(
document: &Document<'_>,
fix: &Fix,
edit_options: EditOptions,
) -> Result<FixResult, LintError> {
match fix {
Fix::Sort => document
.sort_with_options(edit_options)
.map(FixResult::Format)
.map_err(map_format_edit_error),
Fix::Format(options) => document
.format_with_options(options, edit_options)
.map(FixResult::Format)
.map_err(map_format_edit_error),
Fix::Rename { entry, key } => document
.edit_with_options(&[Edit::Rename { entry: *entry, key }], edit_options)
.map(FixResult::Edits)
.map_err(LintError::Edit),
Fix::InsertEmpty { key } => document
.edit_with_options(
&[Edit::Insert {
key,
value: Some(""),
position: InsertPosition::End,
}],
edit_options,
)
.map(FixResult::Edits)
.map_err(LintError::Edit),
}
}
pub fn apply_fixes(document: &Document<'_>, fixes: &[Fix]) -> Result<FixResult, LintError> {
apply_fixes_with_options(document, fixes, EditOptions::new())
}
pub fn apply_fixes_with_options(
document: &Document<'_>,
fixes: &[Fix],
edit_options: EditOptions,
) -> Result<FixResult, LintError> {
let PlannedFixes {
renames,
inserts,
format,
sort,
} = plan_fixes(fixes)?;
let has_edits = !renames.is_empty() || !inserts.is_empty();
if has_edits && (format.is_some() || sort) {
return Err(LintError::Conflict(if inserts.is_empty() {
"renames cannot be combined with formatting or sorting"
} else {
"edits cannot be combined with formatting or sorting"
}));
}
if sort && format.is_some() {
return Err(LintError::Conflict(
"sorting and formatting cannot be combined in one batch",
));
}
if has_edits {
let mut edits: Vec<Edit<'_>> = Vec::with_capacity(renames.len() + inserts.len());
edits.extend(
renames
.iter()
.map(|(entry, key)| Edit::Rename { entry: *entry, key }),
);
edits.extend(inserts.iter().map(|key| Edit::Insert {
key,
value: Some(""),
position: InsertPosition::End,
}));
return document
.edit_with_options(&edits, edit_options)
.map(FixResult::Edits)
.map_err(LintError::Edit);
}
if let Some(options) = format {
return document
.format_with_options(&options, edit_options)
.map(FixResult::Format)
.map_err(map_format_edit_error);
}
if sort {
return document
.sort_with_options(edit_options)
.map(FixResult::Format)
.map_err(map_format_edit_error);
}
document
.edit_with_options(&[], edit_options)
.map(FixResult::Edits)
.map_err(LintError::Edit)
}
#[must_use]
pub fn lint(document: &Document<'_>, options: LintOptions) -> Vec<Finding> {
lint_with_options(document, options, None, EditOptions::new())
}
#[must_use]
pub fn lint_with_schema(
document: &Document<'_>,
options: LintOptions,
schema: &Schema,
) -> Vec<Finding> {
lint_with_options(document, options, Some(schema), EditOptions::new())
}
#[must_use]
pub fn lint_with_options(
document: &Document<'_>,
options: LintOptions,
schema: Option<&Schema>,
edit_options: EditOptions,
) -> Vec<Finding> {
let line_index = document.line_index();
let mut findings = Vec::new();
if options.duplicate_keys {
let mut entries: BTreeMap<&str, Vec<adotenv::Entry<'_>>> = BTreeMap::new();
for entry in document.entries() {
entries.entry(entry.key()).or_default().push(entry);
}
for group in entries.values().filter(|group| group.len() > 1) {
for entry in group.iter().skip(1) {
findings.push(Finding::new(
Rule::DuplicateKey,
"key is declared more than once",
options.severity_for_rule(Rule::DuplicateKey),
entry.key_span(),
entry.line(),
Some(entry.key()),
None,
));
}
}
}
if options.key_order {
key_order_findings(document, options, edit_options, &line_index, &mut findings);
}
for entry in document.entries() {
if options.key_case != KeyCase::Off {
let expected = match options.key_case {
KeyCase::Off => entry.key().to_owned(),
KeyCase::Lower => entry.key().to_ascii_lowercase(),
KeyCase::Upper => entry.key().to_ascii_uppercase(),
};
if expected != entry.key() {
findings.push(Finding::new(
Rule::KeyCase,
"key does not use the configured case",
options.severity_for_rule(Rule::KeyCase),
entry.key_span(),
entry.line(),
Some(entry.key()),
Some(Fix::Rename {
entry: entry.id(),
key: expected,
}),
));
}
}
if let Some(value) = entry.value() {
if !value.is_empty() {
let expected = match options.quote_style {
QuoteStyle::Double => Quote::Double,
QuoteStyle::Single => Quote::Single,
QuoteStyle::Unquoted => Quote::None,
_ => entry.quote(),
};
if entry.quote() != expected {
findings.push(Finding::new(
Rule::QuoteStyle,
"value does not use the configured quote style",
options.severity_for_rule(Rule::QuoteStyle),
entry.value_span().unwrap_or_else(|| entry.key_span()),
entry.line(),
Some(entry.key()),
Some(Fix::Format(options.format_options())),
));
}
}
}
if whitespace_differs(document, entry, options) {
findings.push(Finding::new(
Rule::Whitespace,
"assignment spacing or trailing whitespace is not normalized",
options.severity_for_rule(Rule::Whitespace),
entry.tokens().key.clone(),
entry.line(),
Some(entry.key()),
Some(Fix::Format(options.format_options())),
));
}
}
if let Some(schema) = schema {
schema::schema_findings(document, options, schema, &mut findings);
}
findings.sort_by(|left, right| {
left.span
.start
.cmp(&right.span.start)
.then_with(|| left.rule.as_str().cmp(right.rule.as_str()))
.then_with(|| left.key.cmp(&right.key))
});
findings
}
fn whitespace_differs(
document: &Document<'_>,
entry: adotenv::Entry<'_>,
options: LintOptions,
) -> bool {
let tokens = entry.tokens();
if let Some(_separator) = tokens.eq.as_ref() {
let before = &document.source()[tokens.space_before_eq.clone()];
let after = &document.source()[tokens.space_after_eq.clone()];
match options.equals_spacing {
EqualsSpacing::None if !before.is_empty() || !after.is_empty() => return true,
EqualsSpacing::Spaces if before != " " || after != " " => return true,
_ => {}
}
}
options.trim_trailing_whitespace && !tokens.trailing_space.is_empty()
}
fn key_order_findings(
document: &Document<'_>,
options: LintOptions,
edit_options: EditOptions,
line_index: &LineIndex<'_>,
findings: &mut Vec<Finding>,
) {
let sortable = document
.sort_with_options(edit_options)
.map(|sorted| {
sorted
.edits()
.iter()
.map(|edit| edit.range.clone())
.collect::<Vec<_>>()
})
.unwrap_or_default();
for group in document.groups() {
let entries: Vec<_> = group.entries().collect();
if entries.len() < 2 {
continue;
}
let keys: Vec<&str> = entries.iter().map(|entry| entry.key()).collect();
if keys.windows(2).all(|pair| pair[0] <= pair[1]) {
continue;
}
if keys.iter().any(|key| key.is_empty()) || duplicate_keys(&keys) {
continue;
}
if group.items().any(|item| {
!matches!(
item.kind(),
adotenv::ItemKind::Entry | adotenv::ItemKind::Comment
)
}) {
continue;
}
let span = group.span();
let fix = sortable.contains(&span).then_some(Fix::Sort);
findings.push(Finding::new(
Rule::KeyOrder,
"declarations are not sorted",
options.severity_for_rule(Rule::KeyOrder),
span.clone(),
line_of(line_index, span.start),
None,
fix,
));
}
}
fn duplicate_keys(keys: &[&str]) -> bool {
let mut seen = BTreeSet::new();
!keys.iter().all(|key| seen.insert(*key))
}
fn line_of(index: &LineIndex<'_>, offset: usize) -> usize {
index
.to_position(offset, ColumnEncoding::Utf8)
.map_or(1, |position| position.line + 1)
}
#[cfg(test)]
mod tests {
use super::*;
use adotenv::{parse_strict, parse_with, Dialect};
#[test]
fn defaults_report_only_duplicate_keys() {
let doc = parse_strict("B=2\nA=1\nA=3\n").unwrap();
let findings = lint(&doc, LintOptions::default());
assert_eq!(findings.len(), 1);
assert_eq!(findings[0].rule(), Rule::DuplicateKey);
assert_eq!(findings[0].line(), 3);
assert_eq!(findings[0].key(), Some("A"));
}
#[test]
fn key_order_fix_sorts_through_verified_output() {
let doc = parse_strict("B=2\nA=1\n").unwrap();
let findings = lint(&doc, LintOptions::new().with_key_order(true));
assert_eq!(findings.len(), 1);
assert_eq!(findings[0].rule(), Rule::KeyOrder);
let fixed = apply_fix(&doc, findings[0].fix().unwrap()).unwrap();
assert_eq!(fixed.as_str(), "A=1\nB=2\n");
}
#[test]
fn key_order_reports_unsortable_groups_without_a_fix() {
for source in ["B=$B\nA=1\n", "B='$A'\nA=1\n", "B=$A\nA=$B\n"] {
let doc = parse_strict(source).unwrap();
let findings = lint(&doc, LintOptions::new().with_key_order(true));
assert_eq!(findings.len(), 1, "{source:?}");
assert_eq!(findings[0].rule(), Rule::KeyOrder, "{source:?}");
assert!(findings[0].fix().is_none(), "{source:?}");
}
}
#[test]
fn key_case_fix_renames_one_declaration() {
let doc = parse_strict("lower=1\n").unwrap();
let findings = lint(&doc, LintOptions::new().with_key_case(KeyCase::Upper));
assert_eq!(findings.len(), 1);
let fixed = apply_fix(&doc, findings[0].fix().unwrap()).unwrap();
assert_eq!(fixed.as_str(), "LOWER=1\n");
}
#[test]
fn quote_style_fix_is_verified() {
let doc = parse_strict("A='one'\n").unwrap();
let findings = lint(
&doc,
LintOptions::new().with_quote_style(QuoteStyle::Double),
);
assert_eq!(findings.len(), 1);
let fixed = apply_fix(&doc, findings[0].fix().unwrap()).unwrap();
assert_eq!(fixed.as_str(), "A=\"one\"\n");
}
#[test]
fn whitespace_fix_uses_verified_formatting() {
let doc = parse_strict("A = one \n").unwrap();
let findings = lint(
&doc,
LintOptions::new()
.with_equals_spacing(EqualsSpacing::None)
.with_trim_trailing_whitespace(true),
);
assert_eq!(findings.len(), 1);
let fixed = apply_fix(&doc, findings[0].fix().unwrap()).unwrap();
assert_eq!(fixed.as_str(), "A=one\n");
}
#[test]
fn findings_never_contain_values() {
let doc = parse_strict("TOKEN=secret\nTOKEN=other\n").unwrap();
let findings = lint(&doc, LintOptions::default());
let debug = format!("{findings:?}");
assert!(!debug.contains("secret"));
assert!(!debug.contains("other"));
assert!(debug.contains("TOKEN"));
}
#[test]
fn rename_collision_returns_a_structured_error() {
let doc = parse_strict("A=1\na=2\n").unwrap();
let findings = lint(&doc, LintOptions::new().with_key_case(KeyCase::Upper));
let fix = findings
.iter()
.find_map(Finding::fix)
.expect("the lowercase key has a fix");
assert!(matches!(
apply_fix(&doc, fix),
Err(LintError::Edit(EditError::Duplicate(_)))
));
}
#[test]
fn python_quoted_keys_keep_their_case_policy() {
let doc = parse_with("'A B'=1\n", Dialect::PYTHON_DOTENV).0;
let findings = lint(&doc, LintOptions::new().with_key_case(KeyCase::Upper));
assert_eq!(findings.len(), 0);
}
}
#[cfg(test)]
use adotenv::parse_strict;
#[test]
fn apply_fixes_batches_independent_renames() {
let doc = parse_strict("a=1\nb=2\n").unwrap();
let findings = lint(&doc, LintOptions::new().with_key_case(KeyCase::Upper));
let fixes: Vec<Fix> = findings
.iter()
.filter_map(|finding| finding.fix().cloned())
.collect();
assert_eq!(fixes.len(), 2);
let result = apply_fixes(&doc, &fixes).unwrap();
assert_eq!(result.as_str(), "A=1\nB=2\n");
}
#[test]
fn apply_fixes_reports_mixed_fix_conflicts() {
let doc = parse_strict("A='one'\n").unwrap();
let fixes = [
Fix::Rename {
entry: 0,
key: "B".to_owned(),
},
Fix::Format(FormatOptions::default().with_quote_style(QuoteStyle::Double)),
];
assert!(matches!(
apply_fixes(&doc, &fixes),
Err(LintError::Conflict(
"renames cannot be combined with formatting or sorting"
))
));
}
#[test]
fn apply_fixes_reports_two_keys_for_one_entry() {
let doc = parse_strict("a=1\n").unwrap();
let fixes = [
Fix::Rename {
entry: 0,
key: "A".to_owned(),
},
Fix::Rename {
entry: 0,
key: "B".to_owned(),
},
];
assert!(matches!(
apply_fixes(&doc, &fixes),
Err(LintError::Conflict(
"one entry has two different replacement keys"
))
));
}
#[test]
fn rule_severity_is_configurable() {
let doc = parse_strict("A=1\nA=2\n").unwrap();
let findings = lint(
&doc,
LintOptions::new().with_severity(Rule::DuplicateKey, Severity::Error),
);
assert_eq!(findings[0].severity(), Severity::Error);
}
#[test]
fn apply_batch_combines_renames_sorting_and_formatting() {
let doc = parse_strict("b='two'\na='one'\n").unwrap();
let findings = lint(
&doc,
LintOptions::new()
.with_key_case(KeyCase::Upper)
.with_key_order(true)
.with_quote_style(QuoteStyle::Double),
);
let fixes: Vec<Fix> = findings
.iter()
.filter_map(|finding| finding.fix().cloned())
.collect();
let result = apply_batch(&doc, &fixes).unwrap();
assert_eq!(result.output(), "A=\"one\"\nB=\"two\"\n");
assert_eq!(result.stages().len(), 3);
}
#[test]
fn apply_batch_rejects_conflicting_renames() {
let doc = parse_strict("a=1\n").unwrap();
let fixes = [
Fix::Rename {
entry: 0,
key: "A".to_owned(),
},
Fix::Rename {
entry: 0,
key: "B".to_owned(),
},
];
assert!(matches!(
apply_batch(&doc, &fixes),
Err(LintError::Conflict(
"one entry has two different replacement keys"
))
));
}
#[test]
fn apply_batch_rejects_different_format_policies() {
let doc = parse_strict("A='one'\n").unwrap();
let fixes = [
Fix::Format(FormatOptions::default().with_quote_style(QuoteStyle::Double)),
Fix::Format(FormatOptions::default().with_quote_style(QuoteStyle::Single)),
];
assert!(matches!(
apply_batch(&doc, &fixes),
Err(LintError::Conflict(
"different format policies cannot be combined"
))
));
}
#[test]
fn apply_batch_without_fixes_is_empty() {
let doc = parse_strict("A=1\n").unwrap();
let result = apply_batch(&doc, &[]).unwrap();
assert!(result.is_empty());
assert_eq!(result.output(), "A=1\n");
}
#[test]
fn apply_batch_reports_no_change_for_a_noop_format() {
let doc = parse_strict("A='one'\n").unwrap();
let result = apply_batch(&doc, &[Fix::Format(FormatOptions::default())]).unwrap();
assert!(result.is_empty());
assert_eq!(result.output(), "A='one'\n");
}
#[test]
fn mutation_regression_assertions_for_rules_whitespace_quotes_and_order() {
use adotenv::parse_strict;
let opts = LintOptions::new()
.with_severity(Rule::DuplicateKey, Severity::Error)
.with_severity(Rule::KeyOrder, Severity::Info)
.with_severity(Rule::KeyCase, Severity::Error)
.with_severity(Rule::QuoteStyle, Severity::Info)
.with_severity(Rule::Whitespace, Severity::Error);
assert_eq!(opts.severity_for_rule(Rule::DuplicateKey), Severity::Error);
assert_eq!(opts.severity_for_rule(Rule::KeyOrder), Severity::Info);
assert_eq!(opts.severity_for_rule(Rule::KeyCase), Severity::Error);
assert_eq!(opts.severity_for_rule(Rule::QuoteStyle), Severity::Info);
assert_eq!(opts.severity_for_rule(Rule::Whitespace), Severity::Error);
let dup_doc = parse_strict("A=1\nA=2\n").unwrap();
let dup_findings = lint(&dup_doc, LintOptions::default());
assert_eq!(dup_findings[0].message(), "key is declared more than once");
let rename_doc = parse_strict("a=1\n").unwrap();
let rename_fix = Fix::Rename {
entry: 0,
key: "A".to_owned(),
};
let fixed = apply_fix(&rename_doc, &rename_fix).unwrap();
assert_eq!(fixed.edits().len(), 1);
let batched = apply_batch(&rename_doc, &[rename_fix]).unwrap();
assert!(!batched.is_empty());
assert_eq!(
LintError::Conflict("conflict reason").to_string(),
"cannot combine fixes: conflict reason"
);
let unsorted = parse_strict("B=2\nA=1\n").unwrap();
let sorted = apply_fixes(&unsorted, &[Fix::Sort]).unwrap();
assert_eq!(sorted.as_str(), "A=1\nB=2\n");
let quoted = parse_strict("A=\"one\"\n").unwrap();
let single_findings = lint(
"ed,
LintOptions::new().with_quote_style(QuoteStyle::Single),
);
assert_eq!(single_findings.len(), 1);
assert_eq!(single_findings[0].rule(), Rule::QuoteStyle);
let unquoted_findings = lint(
"ed,
LintOptions::new().with_quote_style(QuoteStyle::Unquoted),
);
assert_eq!(unquoted_findings.len(), 1);
assert_eq!(unquoted_findings[0].rule(), Rule::QuoteStyle);
let eq_none = LintOptions::new().with_equals_spacing(EqualsSpacing::None);
assert_eq!(lint(&parse_strict("A=1\n").unwrap(), eq_none), Vec::new());
assert_eq!(lint(&parse_strict("A =1\n").unwrap(), eq_none).len(), 1);
assert_eq!(lint(&parse_strict("A= 1\n").unwrap(), eq_none).len(), 1);
let eq_spaces = LintOptions::new().with_equals_spacing(EqualsSpacing::Spaces);
assert_eq!(
lint(&parse_strict("A = 1\n").unwrap(), eq_spaces),
Vec::new()
);
assert_eq!(lint(&parse_strict("A= 1\n").unwrap(), eq_spaces).len(), 1);
assert_eq!(lint(&parse_strict("A =1\n").unwrap(), eq_spaces).len(), 1);
let trim_off = LintOptions::new().with_trim_trailing_whitespace(false);
let trim_on = LintOptions::new().with_trim_trailing_whitespace(true);
assert_eq!(lint(&parse_strict("A=1 \n").unwrap(), trim_off), Vec::new());
assert_eq!(lint(&parse_strict("A=1\n").unwrap(), trim_on), Vec::new());
assert_eq!(lint(&parse_strict("A=1 \n").unwrap(), trim_on).len(), 1);
let order_only = LintOptions::new()
.with_duplicate_keys(false)
.with_key_order(true);
let three = parse_strict("# header\n\nC=3\nB=2\nA=1\n").unwrap();
let three_findings = lint(&three, order_only);
assert_eq!(three_findings.len(), 1);
assert_eq!(three_findings[0].line(), 3);
let with_dups = parse_strict("B=2\nA=1\nA=3\n").unwrap();
assert_eq!(lint(&with_dups, order_only), Vec::new());
}
#[test]
fn all_ten_rule_indices_names_and_explanations_are_complete() {
assert_eq!(Rule::ALL.len(), 10);
let opts = LintOptions::new()
.with_severity(Rule::DuplicateKey, Severity::Error)
.with_severity(Rule::KeyOrder, Severity::Info)
.with_severity(Rule::KeyCase, Severity::Error)
.with_severity(Rule::QuoteStyle, Severity::Info)
.with_severity(Rule::Whitespace, Severity::Error)
.with_severity(Rule::MissingKey, Severity::Info)
.with_severity(Rule::UnknownKey, Severity::Error)
.with_severity(Rule::EmptyValue, Severity::Info)
.with_severity(Rule::InvalidValue, Severity::Error)
.with_severity(Rule::DeprecatedKey, Severity::Info);
assert_eq!(opts.severity_for_rule(Rule::MissingKey), Severity::Info);
assert_eq!(opts.severity_for_rule(Rule::UnknownKey), Severity::Error);
assert_eq!(opts.severity_for_rule(Rule::EmptyValue), Severity::Info);
assert_eq!(opts.severity_for_rule(Rule::InvalidValue), Severity::Error);
assert_eq!(opts.severity_for_rule(Rule::DeprecatedKey), Severity::Info);
assert_eq!(Rule::MissingKey.as_str(), "missing-key");
assert_eq!(Rule::UnknownKey.as_str(), "unknown-key");
assert_eq!(Rule::EmptyValue.as_str(), "empty-value");
assert_eq!(Rule::InvalidValue.as_str(), "invalid-value");
assert_eq!(Rule::DeprecatedKey.as_str(), "deprecated-key");
let mut seen_ids = BTreeSet::new();
for (idx, &rule) in Rule::ALL.iter().enumerate() {
assert_eq!(rule.index(), idx);
assert_eq!(Rule::from_name(rule.as_str()), Some(rule));
let info = rule.explain();
assert_eq!(info.id, rule.as_str());
assert!(seen_ids.insert(info.id));
assert_ne!(info.summary, "");
assert_ne!(info.default_behavior, "");
assert_ne!(info.autofix, "");
assert_ne!(info.config, "");
assert_ne!(info.rationale, "");
}
assert_eq!(Rule::from_name("not-a-rule"), None);
}
#[test]
fn bounded_apply_fix_fixes_and_batch_enforce_edit_options() {
use adotenv::{LimitKind, ParseOptions};
let doc = parse_strict("a='one'\n").unwrap();
let double = Fix::Format(FormatOptions::default().with_quote_style(QuoteStyle::Double));
let rename = Fix::Rename {
entry: 0,
key: "LONG_KEY_NAME".to_owned(),
};
let tight_bytes = EditOptions::new().with_max_output_bytes(10);
assert!(matches!(
apply_fix_with_options(&doc, &rename, tight_bytes),
Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::OutputBytes
));
let spacing = Fix::Format(FormatOptions::default().with_equals_spacing(EqualsSpacing::Spaces));
assert!(matches!(
apply_fix_with_options(&doc, &spacing, EditOptions::new().with_max_output_bytes(8)),
Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::OutputBytes
));
assert!(matches!(
apply_fixes_with_options(
&doc,
std::slice::from_ref(&spacing),
EditOptions::new().with_max_output_bytes(8)
),
Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::OutputBytes
));
assert!(matches!(
apply_batch_with_options(&doc, &[rename, double], tight_bytes),
Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::OutputBytes
));
let two_lines = parse_strict("B=2\nA=1\n").unwrap();
assert!(matches!(
apply_fix_with_options(
&two_lines,
&Fix::Sort,
EditOptions::new().with_max_output_lines(1),
),
Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::Lines
));
let with_ref = parse_strict("C=3\nB=$A\nA=1\n").unwrap();
let no_refs = EditOptions::new().with_max_references(0);
let limited_findings = lint_with_options(
&with_ref,
LintOptions::new().with_key_order(true),
None,
no_refs,
);
assert_eq!(limited_findings.len(), 1);
assert_eq!(limited_findings[0].rule(), Rule::KeyOrder);
assert!(limited_findings[0].fix().is_none());
let bounded_ok = lint_with_options(
&with_ref,
LintOptions::new().with_key_order(true),
None,
EditOptions::new().with_max_references(2),
);
assert_eq!(bounded_ok.len(), 1);
assert_eq!(bounded_ok[0].fix(), Some(&Fix::Sort));
assert!(matches!(
apply_fix_with_options(&with_ref, &Fix::Sort, no_refs),
Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::References
));
assert!(matches!(
apply_fixes_with_options(&with_ref, &[Fix::Sort], no_refs),
Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::References
));
assert!(matches!(
apply_batch_with_options(&with_ref, &[Fix::Sort], no_refs),
Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::References
));
let parse_limited = EditOptions::new().with_parse_limits(ParseOptions::new().with_max_lines(1));
assert!(matches!(
apply_batch_with_options(&two_lines, &[Fix::Sort], parse_limited),
Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::Lines
));
let (invalid_doc, _) = adotenv::parse("BAD LINE\nB=2\nA=1\n");
assert_eq!(
apply_batch_with_options(&invalid_doc, &[Fix::Sort], EditOptions::new()).unwrap_err(),
LintError::Parse
);
}
#[test]
fn apply_batch_handles_two_pass_unquoted_with_trivia_and_renames() {
let doc = parse_strict("b = \"two\" \na = \"one\"\n").unwrap();
let policy = LintOptions::new()
.with_key_case(KeyCase::Upper)
.with_key_order(true)
.with_quote_style(QuoteStyle::Unquoted)
.with_equals_spacing(EqualsSpacing::None)
.with_trim_trailing_whitespace(true);
let findings = lint(&doc, policy);
let fixes: Vec<Fix> = findings
.iter()
.filter_map(|finding| finding.fix().cloned())
.collect();
let batch = apply_batch(&doc, &fixes).unwrap();
assert_eq!(batch.output(), "A=one\nB=two\n");
assert!(!batch.is_empty());
let spacing_only = parse_strict("A = plain \n").unwrap();
let fmt_fix = Fix::Format(
FormatOptions::default()
.with_quote_style(QuoteStyle::Unquoted)
.with_equals_spacing(EqualsSpacing::None)
.with_trim_trailing_whitespace(true),
);
let res1 = apply_batch(&spacing_only, std::slice::from_ref(&fmt_fix)).unwrap();
assert_eq!(res1.output(), "A=plain\n");
assert_eq!(res1.stages().len(), 1);
let unquote_only = parse_strict("A=\"plain\"\n").unwrap();
let res2 = apply_batch(&unquote_only, std::slice::from_ref(&fmt_fix)).unwrap();
assert_eq!(res2.output(), "A=plain\n");
assert_eq!(res2.stages().len(), 1);
let clean = parse_strict("A=plain\n").unwrap();
let res3 = apply_batch(&clean, &[fmt_fix]).unwrap();
assert!(res3.is_empty());
assert_eq!(res3.output(), "A=plain\n");
let eq_doc = parse_strict("A = \"plain\"\n").unwrap();
let eq_res = apply_batch(
&eq_doc,
&[Fix::Format(
FormatOptions::default()
.with_quote_style(QuoteStyle::Unquoted)
.with_equals_spacing(EqualsSpacing::None),
)],
)
.unwrap();
assert_eq!(eq_res.output(), "A=plain\n");
assert_eq!(eq_res.stages().len(), 2);
let trim_doc = parse_strict("A=\"plain\" \n").unwrap();
let trim_res = apply_batch(
&trim_doc,
&[Fix::Format(
FormatOptions::default()
.with_quote_style(QuoteStyle::Unquoted)
.with_trim_trailing_whitespace(true),
)],
)
.unwrap();
assert_eq!(trim_res.output(), "A=plain\n");
assert_eq!(trim_res.stages().len(), 2);
let blank_doc = parse_strict("A=\"plain\"\n\n\nB=2\n").unwrap();
let blank_res = apply_batch(
&blank_doc,
&[Fix::Format(
FormatOptions::default()
.with_quote_style(QuoteStyle::Unquoted)
.with_blank_lines(BlankLines::Collapse),
)],
)
.unwrap();
assert_eq!(blank_res.output(), "A=plain\n\nB=2\n");
assert_eq!(blank_res.stages().len(), 2);
let nl_doc = parse_strict("A=\"plain\"").unwrap();
let nl_res = apply_batch(
&nl_doc,
&[Fix::Format(
FormatOptions::default()
.with_quote_style(QuoteStyle::Unquoted)
.with_final_newline(FinalNewline::Ensure),
)],
)
.unwrap();
assert_eq!(nl_res.output(), "A=plain\n");
assert_eq!(nl_res.stages().len(), 2);
let double_res = apply_batch(
&eq_doc,
&[Fix::Format(
FormatOptions::default()
.with_quote_style(QuoteStyle::Single)
.with_equals_spacing(EqualsSpacing::None),
)],
)
.unwrap();
assert_eq!(double_res.output(), "A='plain'\n");
assert_eq!(double_res.stages().len(), 1);
}
#[test]
fn apply_batch_parse_strict_bounded_distinguishes_warnings_from_errors() {
let warn_opts =
EditOptions::new().with_parse_limits(adotenv::ParseOptions::new().with_max_diagnostics(10));
let dup_doc = parse_strict("A=1\nA=2\n").unwrap();
let dup_res = apply_batch_with_options(
&dup_doc,
&[Fix::Format(
FormatOptions::default().with_equals_spacing(EqualsSpacing::Spaces),
)],
warn_opts,
)
.unwrap();
assert_eq!(dup_res.output(), "A = 1\nA = 2\n");
let (err_doc, _) = adotenv::parse("BAD KEY=1\nA=1\n");
assert_eq!(
apply_batch_with_options(
&err_doc,
&[Fix::Format(
FormatOptions::default().with_equals_spacing(EqualsSpacing::Spaces),
)],
warn_opts,
)
.unwrap_err(),
LintError::Parse
);
}
#[test]
fn insert_empty_fix_works_explicitly_and_is_opt_in_for_batches() {
use adotenv::LimitKind;
let doc = parse_strict("B=2\n").unwrap();
let insert_a = Fix::InsertEmpty {
key: "A".to_owned(),
};
let single = apply_fix(&doc, &insert_a).unwrap();
assert_eq!(single.as_str(), "B=2\nA=\n");
assert_eq!(single.edits().len(), 1);
assert!(matches!(
apply_fix_with_options(&doc, &insert_a, EditOptions::new().with_max_output_bytes(5)),
Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::OutputBytes
));
assert!(matches!(
apply_fix(
&doc,
&Fix::InsertEmpty {
key: "BAD KEY".to_owned()
}
),
Err(LintError::Edit(EditError::InvalidKey))
));
let dedup = apply_fixes(&doc, &[insert_a.clone(), insert_a.clone()]).unwrap();
assert_eq!(dedup.as_str(), "B=2\nA=\n");
let lower_doc = parse_strict("b=2\n").unwrap();
let combined_edits = apply_fixes(
&lower_doc,
&[
Fix::Rename {
entry: 0,
key: "B".to_owned(),
},
insert_a.clone(),
],
)
.unwrap();
assert_eq!(combined_edits.as_str(), "B=2\nA=\n");
assert!(matches!(
apply_fixes(&doc, &[insert_a.clone(), Fix::Sort]),
Err(LintError::Conflict(
"edits cannot be combined with formatting or sorting"
))
));
assert!(matches!(
apply_fixes(
&doc,
&[
insert_a.clone(),
Fix::Format(FormatOptions::default().with_equals_spacing(EqualsSpacing::Spaces))
]
),
Err(LintError::Conflict(
"edits cannot be combined with formatting or sorting"
))
));
}
#[test]
fn apply_batch_with_policy_gates_insert_missing_and_avoids_rename_collisions() {
use adotenv::LimitKind;
let doc = parse_strict("B=2\n").unwrap();
let insert_a = Fix::InsertEmpty {
key: "A".to_owned(),
};
let default_batch = apply_batch(&doc, std::slice::from_ref(&insert_a)).unwrap();
assert!(default_batch.is_empty());
assert_eq!(default_batch.output(), "B=2\n");
assert_eq!(default_batch.stages().len(), 0);
let rename_and_missing = parse_strict("port='8080'\n").unwrap();
let schema = Schema::new()
.with_key("HOST", KeySchema::new())
.with_key("PORT", KeySchema::new());
let policy = LintOptions::new()
.with_key_case(KeyCase::Upper)
.with_key_order(true)
.with_quote_style(QuoteStyle::Double);
let findings = lint_with_schema(&rename_and_missing, policy, &schema);
let mut fixes: Vec<Fix> = findings.iter().filter_map(|f| f.fix().cloned()).collect();
fixes.push(Fix::Sort);
let style_only = apply_batch(&rename_and_missing, &fixes).unwrap();
assert_eq!(style_only.output(), "PORT=\"8080\"\n");
let with_missing = apply_batch_with_policy(
&rename_and_missing,
&fixes,
BatchOptions::new().with_insert_missing(true),
)
.unwrap();
assert_eq!(with_missing.output(), "HOST=\nPORT=\"8080\"\n");
assert_eq!(with_missing.stages().len(), 4);
let already = parse_strict("A=1\n").unwrap();
let noop = apply_batch_with_policy(
&already,
&[insert_a],
BatchOptions::new().with_insert_missing(true),
)
.unwrap();
assert!(noop.is_empty());
assert_eq!(noop.output(), "A=1\n");
assert_eq!(noop.stages().len(), 0);
let tight = BatchOptions::new()
.with_insert_missing(true)
.with_edit_options(EditOptions::new().with_max_output_bytes(5));
assert!(matches!(
apply_batch_with_policy(
&doc,
&[Fix::InsertEmpty {
key: "LONG_MISSING".to_owned()
}],
tight
),
Err(LintError::Edit(EditError::Limit(limit))) if limit.kind() == LimitKind::OutputBytes
));
}