use std::collections::BTreeMap;
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};
use adotenv::{Dialect, EqualsSpacing, QuoteStyle, Severity};
use globset::{Glob, GlobSet, GlobSetBuilder};
use serde::Deserialize;
use crate::{KeyCase, LintOptions, Rule};
pub const CONFIG_FILE_NAME: &str = ".adotenv-lint.toml";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum OutputFormat {
Human,
Json,
Github,
}
impl OutputFormat {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Human => "human",
Self::Json => "json",
Self::Github => "github",
}
}
}
impl std::str::FromStr for OutputFormat {
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value {
"human" => Ok(Self::Human),
"json" => Ok(Self::Json),
"github" => Ok(Self::Github),
other => Err(format!("unknown format: {other}")),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RuleSeverity {
Off,
Warning,
Error,
}
impl RuleSeverity {
#[must_use]
pub const fn severity(self) -> Option<Severity> {
match self {
Self::Off => None,
Self::Warning => Some(Severity::Warning),
Self::Error => Some(Severity::Error),
}
}
}
impl std::str::FromStr for RuleSeverity {
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value {
"off" => Ok(Self::Off),
"warning" => Ok(Self::Warning),
"error" => Ok(Self::Error),
other => Err(format!("unknown severity: {other}")),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LintConfig {
pub dialect: Option<Dialect>,
pub format: Option<OutputFormat>,
pub recursive: Option<bool>,
pub key_order: Option<bool>,
pub key_case: Option<KeyCase>,
pub quote_style: Option<QuoteStyle>,
pub equals_spacing: Option<EqualsSpacing>,
pub trim_trailing_whitespace: Option<bool>,
pub ignore: Option<Vec<String>>,
pub rules: Option<BTreeMap<String, RuleSeverity>>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawConfig {
dialect: Option<String>,
format: Option<String>,
recursive: Option<bool>,
key_order: Option<bool>,
key_case: Option<String>,
quote_style: Option<String>,
equals_spacing: Option<String>,
trim_trailing_whitespace: Option<bool>,
ignore: Option<Vec<String>>,
rules: Option<BTreeMap<String, String>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigError {
path: Option<PathBuf>,
message: String,
}
impl ConfigError {
fn at(path: &Path, message: impl Into<String>) -> Self {
Self {
path: Some(path.to_path_buf()),
message: message.into(),
}
}
#[must_use]
pub fn path(&self) -> Option<&Path> {
self.path.as_deref()
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
}
impl fmt::Display for ConfigError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.path {
Some(path) => write!(formatter, "{}: {}", path.display(), self.message),
None => formatter.write_str(&self.message),
}
}
}
impl std::error::Error for ConfigError {}
fn unknown(name: &str, value: &str) -> String {
let mut message = String::new();
message.push_str("unknown ");
message.push_str(name);
message.push_str(": ");
message.push_str(value);
message
}
impl LintConfig {
pub fn from_toml(source: &str, path: &Path) -> Result<Self, ConfigError> {
let raw: RawConfig =
toml::from_str(source).map_err(|error| ConfigError::at(path, error.to_string()))?;
Self::from_raw(raw, path)
}
pub fn load(path: &Path) -> Result<Self, ConfigError> {
let source =
fs::read_to_string(path).map_err(|error| ConfigError::at(path, error.to_string()))?;
Self::from_toml(&source, path)
}
pub fn apply(&self, policy: &mut LintPolicy, explicit: ConfigExplicit) {
if !explicit.dialect {
if let Some(value) = self.dialect {
policy.dialect = value;
}
}
if !explicit.format {
if let Some(value) = self.format {
policy.format = value;
}
}
if !explicit.recursive {
if let Some(value) = self.recursive {
policy.recursive = value;
}
}
if !explicit.key_order {
if let Some(value) = self.key_order {
policy.lint = policy.lint.with_key_order(value);
}
}
if !explicit.key_case {
if let Some(value) = self.key_case {
policy.lint = policy.lint.with_key_case(value);
}
}
if !explicit.quote_style {
if let Some(value) = self.quote_style {
policy.lint = policy.lint.with_quote_style(value);
}
}
if !explicit.equals_spacing {
if let Some(value) = self.equals_spacing {
policy.lint = policy.lint.with_equals_spacing(value);
}
}
if !explicit.trim_trailing_whitespace {
if let Some(value) = self.trim_trailing_whitespace {
policy.lint = policy.lint.with_trim_trailing_whitespace(value);
}
}
if !explicit.ignore {
if let Some(ignore) = &self.ignore {
policy.ignore.clone_from(ignore);
}
}
if let Some(rules) = &self.rules {
apply_rules(policy, rules, explicit);
}
}
fn from_raw(raw: RawConfig, path: &Path) -> Result<Self, ConfigError> {
let dialect = raw
.dialect
.as_deref()
.map(|value| {
parse_dialect(value).map_err(|_| ConfigError::at(path, unknown("dialect", value)))
})
.transpose()?;
let format = raw
.format
.as_deref()
.map(|value| {
value
.parse()
.map_err(|_| ConfigError::at(path, unknown("format", value)))
})
.transpose()?;
let key_case = raw
.key_case
.as_deref()
.map(|value| {
parse_key_case(value).map_err(|_| ConfigError::at(path, unknown("key case", value)))
})
.transpose()?;
let quote_style = raw
.quote_style
.as_deref()
.map(|value| {
parse_quote_style(value)
.map_err(|_| ConfigError::at(path, unknown("quote style", value)))
})
.transpose()?;
let equals_spacing = raw
.equals_spacing
.as_deref()
.map(|value| {
parse_equals_spacing(value)
.map_err(|_| ConfigError::at(path, unknown("equals spacing", value)))
})
.transpose()?;
if let Some(ignore) = &raw.ignore {
IgnoredPaths::new(ignore).map_err(|error| ConfigError::at(path, error))?;
}
let mut rules = None;
if let Some(raw_rules) = raw.rules {
let mut parsed = BTreeMap::new();
for (name, value) in raw_rules {
let rule = parse_rule(&name)
.ok_or_else(|| ConfigError::at(path, format!("unknown rule: {name}")))?;
let severity = value.parse::<RuleSeverity>().map_err(|_| {
ConfigError::at(path, unknown(&format!("severity for {name}"), &value))
})?;
parsed.insert(rule.as_str().to_owned(), severity);
}
rules = Some(parsed);
}
Ok(Self {
dialect,
format,
recursive: raw.recursive,
key_order: raw.key_order,
key_case,
quote_style,
equals_spacing,
trim_trailing_whitespace: raw.trim_trailing_whitespace,
ignore: raw.ignore,
rules,
})
}
}
fn apply_rules(
policy: &mut LintPolicy,
rules: &BTreeMap<String, RuleSeverity>,
explicit: ConfigExplicit,
) {
for (name, severity) in rules {
let Some(rule) = parse_rule(name) else {
continue;
};
let enabled = severity.severity().is_some();
match rule {
Rule::DuplicateKey => {
policy.lint = policy.lint.with_duplicate_keys(enabled);
}
Rule::KeyOrder if !explicit.key_order => {
policy.lint = policy.lint.with_key_order(enabled);
}
Rule::KeyCase if !explicit.key_case && !enabled => {
policy.lint = policy.lint.with_key_case(KeyCase::Off);
}
Rule::QuoteStyle if !explicit.quote_style && !enabled => {
policy.lint = policy.lint.with_quote_style(QuoteStyle::Preserve);
}
Rule::Whitespace if !enabled => {
if !explicit.equals_spacing {
policy.lint = policy.lint.with_equals_spacing(EqualsSpacing::Preserve);
}
if !explicit.trim_trailing_whitespace {
policy.lint = policy.lint.with_trim_trailing_whitespace(false);
}
}
_ => {}
}
if let Some(severity) = severity.severity() {
policy.lint = policy.lint.with_severity(rule, severity);
}
}
}
#[derive(Debug, Clone)]
pub struct IgnoredPaths {
globs: GlobSet,
}
impl IgnoredPaths {
pub fn new(patterns: &[String]) -> Result<Self, String> {
let mut builder = GlobSetBuilder::new();
for pattern in patterns {
let glob = Glob::new(pattern).map_err(|error| format!("invalid exclude: {error}"))?;
builder.add(glob);
}
let globs = builder
.build()
.map_err(|error| format!("invalid exclude: {error}"))?;
Ok(Self { globs })
}
#[must_use]
pub fn is_ignored(&self, path: &Path) -> bool {
if self.matches_path(path) {
return true;
}
let components: Vec<_> = path.components().collect();
for start in 1..components.len() {
let suffix: PathBuf = components[start..].iter().collect();
if self.globs.is_match(&suffix) {
return true;
}
}
false
}
#[must_use]
pub fn is_ignored_with_root(&self, path: &Path, root: &Path) -> bool {
if self.matches_path(path) {
return true;
}
path.strip_prefix(root)
.is_ok_and(|relative| !relative.as_os_str().is_empty() && self.globs.is_match(relative))
}
fn matches_path(&self, path: &Path) -> bool {
self.globs.is_match(path)
|| path
.file_name()
.is_some_and(|name| self.globs.is_match(Path::new(name)))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LintPolicy {
pub dialect: Dialect,
pub format: OutputFormat,
pub recursive: bool,
pub lint: LintOptions,
pub ignore: Vec<String>,
}
impl Default for LintPolicy {
fn default() -> Self {
Self {
dialect: Dialect::PORTABLE,
format: OutputFormat::Human,
recursive: false,
lint: LintOptions::default(),
ignore: Vec::new(),
}
}
}
impl LintPolicy {
pub fn ignored_paths(&self) -> Result<IgnoredPaths, String> {
IgnoredPaths::new(&self.ignore)
}
}
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ConfigExplicit {
pub dialect: bool,
pub format: bool,
pub recursive: bool,
pub key_order: bool,
pub key_case: bool,
pub quote_style: bool,
pub equals_spacing: bool,
pub trim_trailing_whitespace: bool,
pub ignore: bool,
}
#[must_use]
pub fn discover_config(start: &Path) -> Option<PathBuf> {
let mut directory = if start.is_dir() {
start.to_path_buf()
} else {
start.parent()?.to_path_buf()
};
loop {
let candidate = directory.join(CONFIG_FILE_NAME);
if candidate.is_file() {
return Some(candidate);
}
if !directory.pop() {
return None;
}
}
}
pub fn load_effective_config(
explicit: Option<&Path>,
start: &Path,
) -> Result<Option<LintConfig>, ConfigError> {
let path = match explicit {
Some(path) => path.to_path_buf(),
None => match discover_config(start) {
Some(path) => path,
None => return Ok(None),
},
};
LintConfig::load(&path).map(Some)
}
fn parse_rule(value: &str) -> Option<Rule> {
match value {
"duplicate-key" => Some(Rule::DuplicateKey),
"key-order" => Some(Rule::KeyOrder),
"key-case" => Some(Rule::KeyCase),
"quote-style" => Some(Rule::QuoteStyle),
"whitespace" => Some(Rule::Whitespace),
_ => None,
}
}
pub fn parse_dialect(value: &str) -> Result<Dialect, String> {
match value {
"portable" => Ok(Dialect::PORTABLE),
"node" => Ok(Dialect::NODE_DOTENV),
"python" => Ok(Dialect::PYTHON_DOTENV),
"compose" => Ok(Dialect::COMPOSE),
"docker" | "docker-raw" => Ok(Dialect::DOCKER_RAW),
other => Err(format!("unknown dialect: {other}")),
}
}
pub fn parse_key_case(value: &str) -> Result<KeyCase, String> {
match value {
"lower" => Ok(KeyCase::Lower),
"upper" => Ok(KeyCase::Upper),
other => Err(format!("unknown key case: {other}")),
}
}
pub fn parse_quote_style(value: &str) -> Result<QuoteStyle, String> {
match value {
"preserve" => Ok(QuoteStyle::Preserve),
"double" => Ok(QuoteStyle::Double),
"single" => Ok(QuoteStyle::Single),
"unquoted" => Ok(QuoteStyle::Unquoted),
other => Err(format!("unknown quote style: {other}")),
}
}
pub fn parse_equals_spacing(value: &str) -> Result<EqualsSpacing, String> {
match value {
"preserve" => Ok(EqualsSpacing::Preserve),
"none" => Ok(EqualsSpacing::None),
"spaces" => Ok(EqualsSpacing::Spaces),
other => Err(format!("unknown equals spacing: {other}")),
}
}
pub fn parse_output_format(value: &str) -> Result<OutputFormat, String> {
value.parse()
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
static NEXT: AtomicUsize = AtomicUsize::new(0);
struct TempDir(PathBuf);
impl TempDir {
fn new(name: &str) -> Self {
let path = std::env::temp_dir().join(format!(
"adotenv-lint-config-{name}-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(&path).unwrap();
Self(path)
}
fn file(&self, name: &str, source: &str) -> PathBuf {
let path = self.0.join(name);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).unwrap();
}
fs::write(&path, source).unwrap();
path
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[test]
fn no_config_uses_defaults() {
let dir = TempDir::new("defaults");
let config = load_effective_config(None, dir.path()).unwrap();
assert!(config.is_none());
let policy = LintPolicy::default();
assert_eq!(policy.dialect, Dialect::PORTABLE);
assert_eq!(policy.format, OutputFormat::Human);
assert_eq!(policy.ignore.len(), 0);
}
#[test]
fn explicit_path_takes_precedence_over_discovery() {
let dir = TempDir::new("explicit");
dir.file(CONFIG_FILE_NAME, "key_order = true\n");
let explicit = dir.file("other.toml", "key_case = \"upper\"\n");
let config = load_effective_config(Some(&explicit), dir.path())
.unwrap()
.unwrap();
assert_eq!(config.key_order, None);
assert_eq!(config.key_case, Some(KeyCase::Upper));
}
#[test]
fn discovery_walks_ancestors() {
let dir = TempDir::new("discovery");
dir.file(CONFIG_FILE_NAME, "key_order = true\n");
let nested = dir.path().join("nested");
fs::create_dir_all(&nested).unwrap();
assert_eq!(
discover_config(&nested.join("app.env")),
Some(dir.path().join(CONFIG_FILE_NAME))
);
}
#[test]
fn unknown_fields_and_rules_are_rejected() {
let path = Path::new("test.toml");
assert!(LintConfig::from_toml("unknown = true\n", path).is_err());
assert!(LintConfig::from_toml("[rules]\nunknown = \"warning\"\n", path).is_err());
assert!(LintConfig::from_toml("[rules]\nkey-order = \"nope\"\n", path).is_err());
assert!(LintConfig::from_toml("ignore = [\"[\"]\n", path).is_err());
}
#[test]
fn unvalidated_public_rule_maps_do_not_panic() {
let config = LintConfig {
dialect: None,
format: None,
recursive: None,
key_order: None,
key_case: None,
quote_style: None,
equals_spacing: None,
trim_trailing_whitespace: None,
ignore: None,
rules: Some(BTreeMap::from([(
"not-a-rule".to_owned(),
RuleSeverity::Error,
)])),
};
let mut policy = LintPolicy::default();
config.apply(&mut policy, ConfigExplicit::default());
}
#[test]
fn disabled_whitespace_rule_keeps_explicit_cli_options() {
let config =
LintConfig::from_toml("[rules]\nwhitespace = \"off\"\n", Path::new("test.toml"))
.unwrap();
let mut policy = LintPolicy {
lint: LintOptions::default().with_trim_trailing_whitespace(true),
..LintPolicy::default()
};
config.apply(
&mut policy,
ConfigExplicit {
trim_trailing_whitespace: true,
..ConfigExplicit::default()
},
);
assert!(policy.lint.trim_trailing_whitespace);
}
#[test]
fn rooted_ignores_do_not_match_ancestor_components() {
let ignores = IgnoredPaths::new(&["src/**".to_owned()]).unwrap();
let absolute = Path::new("/work/src/project/.env");
assert!(!ignores.is_ignored_with_root(absolute, Path::new("/work/src/project")));
assert!(ignores.is_ignored_with_root(
Path::new("/work/src/project/src/.env"),
Path::new("/work/src/project")
));
assert!(ignores.is_ignored(absolute));
}
#[test]
fn severity_and_ignores_apply() {
let config = LintConfig::from_toml(
"ignore = [\".env.skip\"]\n[rules]\nduplicate-key = \"error\"\n",
Path::new("test.toml"),
)
.unwrap();
let mut policy = LintPolicy::default();
config.apply(&mut policy, ConfigExplicit::default());
assert_eq!(policy.ignore, [".env.skip"]);
assert_eq!(
policy.lint.severity_for_rule(Rule::DuplicateKey),
Severity::Error
);
}
#[test]
fn explicit_fields_are_not_overridden() {
let config = LintConfig::from_toml(
"format = \"json\"\nkey_order = true\nignore = [\"config\"]\n",
Path::new("test.toml"),
)
.unwrap();
let mut policy = LintPolicy {
format: OutputFormat::Human,
ignore: vec!["cli".to_owned()],
..LintPolicy::default()
};
config.apply(
&mut policy,
ConfigExplicit {
format: true,
key_order: true,
ignore: true,
..ConfigExplicit::default()
},
);
assert_eq!(policy.format, OutputFormat::Human);
assert!(!policy.lint.key_order);
assert_eq!(policy.ignore, ["cli"]);
}
#[test]
fn parses_dialects_and_spacing() {
assert_eq!(parse_dialect("portable").unwrap(), Dialect::PORTABLE);
assert_eq!(parse_dialect("node").unwrap(), Dialect::NODE_DOTENV);
assert_eq!(parse_dialect("python").unwrap(), Dialect::PYTHON_DOTENV);
assert_eq!(parse_dialect("compose").unwrap(), Dialect::COMPOSE);
assert_eq!(parse_dialect("docker").unwrap(), Dialect::DOCKER_RAW);
assert_eq!(parse_dialect("docker-raw").unwrap(), Dialect::DOCKER_RAW);
assert!(parse_dialect("nope").is_err());
assert_eq!(parse_key_case("lower").unwrap(), KeyCase::Lower);
assert_eq!(parse_key_case("upper").unwrap(), KeyCase::Upper);
assert!(parse_key_case("mixed").is_err());
assert_eq!(parse_quote_style("preserve").unwrap(), QuoteStyle::Preserve);
assert_eq!(parse_quote_style("double").unwrap(), QuoteStyle::Double);
assert_eq!(parse_quote_style("single").unwrap(), QuoteStyle::Single);
assert_eq!(parse_quote_style("unquoted").unwrap(), QuoteStyle::Unquoted);
assert!(parse_quote_style("backtick").is_err());
assert_eq!(
parse_equals_spacing("preserve").unwrap(),
EqualsSpacing::Preserve
);
assert_eq!(parse_equals_spacing("none").unwrap(), EqualsSpacing::None);
assert_eq!(
parse_equals_spacing("spaces").unwrap(),
EqualsSpacing::Spaces
);
assert!(parse_equals_spacing("tabs").is_err());
assert_eq!(OutputFormat::Human.as_str(), "human");
assert_eq!(OutputFormat::Json.as_str(), "json");
assert_eq!(OutputFormat::Github.as_str(), "github");
assert_eq!(parse_output_format("human").unwrap(), OutputFormat::Human);
assert_eq!(parse_output_format("json").unwrap(), OutputFormat::Json);
assert_eq!(parse_output_format("github").unwrap(), OutputFormat::Github);
assert!(parse_output_format("xml").is_err());
assert_eq!(
"warning".parse::<RuleSeverity>().unwrap().severity(),
Some(Severity::Warning)
);
assert_eq!(
"error".parse::<RuleSeverity>().unwrap().severity(),
Some(Severity::Error)
);
assert_eq!("off".parse::<RuleSeverity>().unwrap().severity(), None);
assert!("fatal".parse::<RuleSeverity>().is_err());
}
#[test]
fn config_apply_and_validation_cover_all_fields_and_errors() {
let full = LintConfig::from_toml(
"dialect = \"compose\"\n\
format = \"github\"\n\
recursive = true\n\
key_order = true\n\
key_case = \"lower\"\n\
quote_style = \"double\"\n\
equals_spacing = \"spaces\"\n\
trim_trailing_whitespace = true\n\
ignore = [\"vendor/**\"]\n\
[rules]\n\
key-case = \"warning\"\n\
quote-style = \"error\"\n\
whitespace = \"warning\"\n",
Path::new("full.toml"),
)
.unwrap();
let mut policy = LintPolicy::default();
full.apply(&mut policy, ConfigExplicit::default());
assert_eq!(policy.dialect, Dialect::COMPOSE);
assert_eq!(policy.format, OutputFormat::Github);
assert!(policy.recursive);
assert!(policy.lint.key_order);
assert_eq!(policy.lint.key_case, KeyCase::Lower);
assert_eq!(policy.lint.quote_style, QuoteStyle::Double);
assert_eq!(policy.lint.equals_spacing, EqualsSpacing::Spaces);
assert!(policy.lint.trim_trailing_whitespace);
assert_eq!(policy.ignore, ["vendor/**"]);
let disable = LintConfig::from_toml(
"[rules]\nkey-case = \"off\"\nquote-style = \"off\"\nwhitespace = \"off\"\n",
Path::new("off.toml"),
)
.unwrap();
disable.apply(&mut policy, ConfigExplicit::default());
assert_eq!(policy.lint.key_case, KeyCase::Off);
assert_eq!(policy.lint.quote_style, QuoteStyle::Preserve);
assert_eq!(policy.lint.equals_spacing, EqualsSpacing::Preserve);
assert!(!policy.lint.trim_trailing_whitespace);
for (snippet, expected) in [
("dialect = \"nope\"\n", "unknown dialect: nope"),
("format = \"nope\"\n", "unknown format: nope"),
("key_case = \"nope\"\n", "unknown key case: nope"),
("quote_style = \"nope\"\n", "unknown quote style: nope"),
(
"equals_spacing = \"nope\"\n",
"unknown equals spacing: nope",
),
(
"[rules]\nkey-case = \"nope\"\n",
"unknown severity for key-case: nope",
),
] {
let err = LintConfig::from_toml(snippet, Path::new("bad.toml")).unwrap_err();
assert_eq!(err.path(), Some(Path::new("bad.toml")));
assert_eq!(err.message(), expected);
assert!(err.to_string().contains("bad.toml"));
}
let no_path = ConfigError {
path: None,
message: "plain error".to_owned(),
};
assert_eq!(no_path.path(), None);
assert_eq!(no_path.to_string(), "plain error");
}
}