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, 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,
}
impl Rule {
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,
}
}
#[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",
}
}
}
#[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,
severities: [Severity; 9],
}
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,
severities: [Severity::Warning; 9],
}
}
#[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_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,
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 {
rule,
message,
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 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,
},
}
#[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)>,
format: Option<FormatOptions>,
sort: bool,
}
fn plan_fixes(fixes: &[Fix]) -> Result<PlannedFixes, LintError> {
let mut renames: Vec<(usize, String)> = Vec::new();
let mut format = None;
let mut sort = false;
for fix in fixes {
match fix {
Fix::Rename { entry, key } => {
if let Some((_, existing)) = renames.iter().find(|(id, _)| id == entry) {
if existing != key {
return Err(LintError::Conflict(
"one entry has two different replacement keys",
));
}
continue;
}
renames.push((*entry, 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,
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> {
let PlannedFixes {
renames,
format,
sort,
} = plan_fixes(fixes)?;
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 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),
}
}
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,
format,
sort,
} = plan_fixes(fixes)?;
if !renames.is_empty() && (format.is_some() || sort) {
return Err(LintError::Conflict(
"renames 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 !renames.is_empty() {
let edits: Vec<Edit<'_>> = renames
.iter()
.map(|(entry, key)| Edit::Rename { entry: *entry, key })
.collect();
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_nine_rule_indices_and_names_are_distinct() {
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);
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!(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");
}
#[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
);
}