use std::collections::BTreeMap;
use std::fmt;
use std::fs;
use std::io::Read as _;
use std::path::{Path, PathBuf};
use adotenv::{Dialect, Document, EqualsSpacing, QuoteStyle, Severity};
use globset::{Glob, GlobSet, GlobSetBuilder};
use serde::Deserialize;
use crate::{KeyCase, LintOptions, Rule, Schema, ValueShape};
pub const CONFIG_FILE_NAME: &str = ".adotenv-lint.toml";
const MAX_CONFIG_BYTES: usize = 4 * 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum OutputFormat {
Human,
Json,
Github,
Sarif,
}
impl OutputFormat {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Human => "human",
Self::Json => "json",
Self::Github => "github",
Self::Sarif => "sarif",
}
}
}
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),
"sarif" => Ok(Self::Sarif),
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, Default)]
#[non_exhaustive]
pub struct KeySchemaConfig {
pub required: Option<bool>,
pub allow_empty: Option<bool>,
pub allow_bare: Option<bool>,
pub shape: Option<ValueShape>,
pub description: Option<String>,
pub deprecated: Option<bool>,
pub deprecation_note: Option<String>,
pub prefix: Option<String>,
pub suffix: Option<String>,
pub min_len: Option<usize>,
pub max_len: Option<usize>,
}
impl KeySchemaConfig {
#[must_use]
pub const fn new() -> Self {
Self {
required: None,
allow_empty: None,
allow_bare: None,
shape: None,
description: None,
deprecated: None,
deprecation_note: None,
prefix: None,
suffix: None,
min_len: None,
max_len: None,
}
}
#[must_use]
pub const fn with_required(mut self, required: bool) -> Self {
self.required = Some(required);
self
}
#[must_use]
pub const fn with_allow_empty(mut self, allow_empty: bool) -> Self {
self.allow_empty = Some(allow_empty);
self
}
#[must_use]
pub const fn with_allow_bare(mut self, allow_bare: bool) -> Self {
self.allow_bare = Some(allow_bare);
self
}
#[must_use]
pub fn with_shape(mut self, shape: ValueShape) -> Self {
self.shape = Some(shape);
self
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn with_deprecated(mut self, deprecated: bool) -> Self {
self.deprecated = Some(deprecated);
if !deprecated {
self.deprecation_note = None;
}
self
}
#[must_use]
pub fn with_deprecation_note(mut self, note: impl Into<String>) -> Self {
self.deprecated = Some(true);
self.deprecation_note = Some(note.into());
self
}
#[must_use]
pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
self.prefix = Some(prefix.into());
self
}
#[must_use]
pub fn with_suffix(mut self, suffix: impl Into<String>) -> Self {
self.suffix = Some(suffix.into());
self
}
#[must_use]
pub const fn with_min_len(mut self, min_len: usize) -> Self {
self.min_len = Some(min_len);
self
}
#[must_use]
pub const fn with_max_len(mut self, max_len: usize) -> Self {
self.max_len = Some(max_len);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SchemaConfig {
pub example: Option<PathBuf>,
pub allow_unknown: Option<bool>,
pub allow_empty: Option<bool>,
pub keys: BTreeMap<String, KeySchemaConfig>,
}
impl SchemaConfig {
#[must_use]
pub fn resolve(&self, example: Option<&Document<'_>>) -> Schema {
let mut schema = example.map_or_else(Schema::new, Schema::from_example);
if let Some(allow_unknown) = self.allow_unknown {
schema = schema.with_allow_unknown(allow_unknown);
}
if let Some(allow_empty) = self.allow_empty {
schema = schema.with_allow_empty(allow_empty);
}
for (key, override_cfg) in &self.keys {
let entry = schema.keys.entry(key.clone()).or_default();
if let Some(required) = override_cfg.required {
entry.required = required;
}
if let Some(allow_empty) = override_cfg.allow_empty {
entry.allow_empty = Some(allow_empty);
}
if let Some(allow_bare) = override_cfg.allow_bare {
entry.allow_bare = allow_bare;
}
if let Some(shape) = &override_cfg.shape {
entry.shape = shape.clone();
}
if let Some(description) = &override_cfg.description {
entry.description = Some(description.clone());
}
if let Some(deprecated) = override_cfg.deprecated {
entry.deprecated = deprecated;
if deprecated {
if let Some(note) = &override_cfg.deprecation_note {
entry.deprecation_note = Some(note.clone());
}
} else {
entry.deprecation_note = None;
}
} else if let Some(note) = &override_cfg.deprecation_note {
entry.deprecated = true;
entry.deprecation_note = Some(note.clone());
}
if let Some(prefix) = &override_cfg.prefix {
entry.prefix = Some(prefix.clone());
}
if let Some(suffix) = &override_cfg.suffix {
entry.suffix = Some(suffix.clone());
}
if let Some(min_len) = override_cfg.min_len {
entry.min_len = Some(min_len);
}
if let Some(max_len) = override_cfg.max_len {
entry.max_len = Some(max_len);
}
}
schema
}
}
#[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>>,
pub schema: Option<SchemaConfig>,
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum RawDeprecated {
Flag(bool),
Note(String),
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawKeySchemaConfig {
required: Option<bool>,
allow_empty: Option<bool>,
allow_bare: Option<bool>,
shape: Option<String>,
one_of: Option<Vec<String>>,
description: Option<String>,
deprecated: Option<RawDeprecated>,
prefix: Option<String>,
suffix: Option<String>,
min_len: Option<usize>,
max_len: Option<usize>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawSchemaConfig {
example: Option<String>,
allow_unknown: Option<bool>,
allow_empty: Option<bool>,
keys: Option<BTreeMap<String, RawKeySchemaConfig>>,
}
#[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>>,
schema: Option<RawSchemaConfig>,
}
#[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 read_config_bounded(path: &Path, max_bytes: usize) -> Result<String, ConfigError> {
if let Ok(metadata) = fs::metadata(path) {
if !metadata.is_file() {
return Err(ConfigError::at(path, "config path is not a regular file"));
}
}
let file = fs::File::open(path).map_err(|error| ConfigError::at(path, error.to_string()))?;
let metadata = file
.metadata()
.map_err(|error| ConfigError::at(path, error.to_string()))?;
if !metadata.is_file() {
return Err(ConfigError::at(path, "config path is not a regular file"));
}
let observed = usize::try_from(metadata.len()).unwrap_or(usize::MAX);
if observed > max_bytes {
return Err(ConfigError::at(
path,
format!("config exceeds maximum size ({max_bytes} bytes)"),
));
}
let mut bytes = Vec::new();
file.take(max_bytes.saturating_add(1) as u64)
.read_to_end(&mut bytes)
.map_err(|error| ConfigError::at(path, error.to_string()))?;
if bytes.len() > max_bytes {
return Err(ConfigError::at(
path,
format!("config exceeds maximum size ({max_bytes} bytes)"),
));
}
String::from_utf8(bytes).map_err(|_| ConfigError::at(path, "config file is not valid UTF-8"))
}
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 = read_config_bounded(path, MAX_CONFIG_BYTES)?;
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(schema) = &self.schema {
let target = policy.schema.get_or_insert_with(SchemaConfig::default);
merge_schema_config(target, schema, explicit);
}
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);
}
let schema = raw
.schema
.map(|raw_schema| parse_schema_config(raw_schema, path))
.transpose()?;
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,
schema,
})
}
}
fn merge_schema_config(target: &mut SchemaConfig, schema: &SchemaConfig, explicit: ConfigExplicit) {
if !explicit.schema_example {
if let Some(example) = &schema.example {
target.example = Some(example.clone());
}
}
if !explicit.schema_allow_unknown {
if let Some(allow_unknown) = schema.allow_unknown {
target.allow_unknown = Some(allow_unknown);
}
}
if !explicit.schema_allow_empty {
if let Some(allow_empty) = schema.allow_empty {
target.allow_empty = Some(allow_empty);
}
}
for (key, key_cfg) in &schema.keys {
let entry = target.keys.entry(key.clone()).or_default();
if key_cfg.required.is_some() {
entry.required = key_cfg.required;
}
if key_cfg.allow_empty.is_some() {
entry.allow_empty = key_cfg.allow_empty;
}
if key_cfg.allow_bare.is_some() {
entry.allow_bare = key_cfg.allow_bare;
}
if let Some(shape) = &key_cfg.shape {
entry.shape = Some(shape.clone());
}
if let Some(description) = &key_cfg.description {
entry.description = Some(description.clone());
}
if let Some(deprecated) = key_cfg.deprecated {
entry.deprecated = Some(deprecated);
if deprecated {
if let Some(note) = &key_cfg.deprecation_note {
entry.deprecation_note = Some(note.clone());
}
} else {
entry.deprecation_note = None;
}
} else if let Some(note) = &key_cfg.deprecation_note {
entry.deprecated = Some(true);
entry.deprecation_note = Some(note.clone());
}
if let Some(prefix) = &key_cfg.prefix {
entry.prefix = Some(prefix.clone());
}
if let Some(suffix) = &key_cfg.suffix {
entry.suffix = Some(suffix.clone());
}
if key_cfg.min_len.is_some() {
entry.min_len = key_cfg.min_len;
}
if key_cfg.max_len.is_some() {
entry.max_len = key_cfg.max_len;
}
}
}
fn parse_schema_config(raw: RawSchemaConfig, path: &Path) -> Result<SchemaConfig, ConfigError> {
let example = match raw.example {
Some(value) if value.is_empty() => {
return Err(ConfigError::at(path, "schema.example must not be empty"));
}
Some(value) => {
let candidate = PathBuf::from(&value);
if candidate.is_absolute() {
Some(candidate)
} else if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
Some(parent.join(candidate))
} else {
Some(candidate)
}
}
None => None,
};
let mut keys = BTreeMap::new();
if let Some(raw_keys) = raw.keys {
for (key, raw_key) in raw_keys {
if key.is_empty() {
return Err(ConfigError::at(path, "schema key name must not be empty"));
}
let shape = parse_key_shape(&key, raw_key.shape.as_deref(), raw_key.one_of, path)?;
let (deprecated, deprecation_note) = match raw_key.deprecated {
None => (None, None),
Some(RawDeprecated::Flag(flag)) => (Some(flag), None),
Some(RawDeprecated::Note(note)) => {
if note.trim().is_empty() {
return Err(ConfigError::at(
path,
format!(
"schema.keys.{key}.deprecated note must not be empty; use true instead"
),
));
}
(Some(true), Some(note))
}
};
if let (Some(min_len), Some(max_len)) = (raw_key.min_len, raw_key.max_len) {
if min_len > max_len {
return Err(ConfigError::at(
path,
format!(
"schema.keys.{key}.min_len ({min_len}) exceeds max_len ({max_len})"
),
));
}
}
if let Some(max_len) = raw_key.max_len {
let min_affix =
min_combined_affix_len(raw_key.prefix.as_deref(), raw_key.suffix.as_deref());
if min_affix > max_len {
return Err(ConfigError::at(
path,
format!(
"schema.keys.{key}.max_len ({max_len}) is shorter than configured prefix/suffix ({min_affix})"
),
));
}
}
keys.insert(
key,
KeySchemaConfig {
required: raw_key.required,
allow_empty: raw_key.allow_empty,
allow_bare: raw_key.allow_bare,
shape,
description: raw_key.description,
deprecated,
deprecation_note,
prefix: raw_key.prefix,
suffix: raw_key.suffix,
min_len: raw_key.min_len,
max_len: raw_key.max_len,
},
);
}
}
Ok(SchemaConfig {
example,
allow_unknown: raw.allow_unknown,
allow_empty: raw.allow_empty,
keys,
})
}
fn min_combined_affix_len(prefix: Option<&str>, suffix: Option<&str>) -> usize {
match (prefix, suffix) {
(None, None) => 0,
(Some(p), None) => p.chars().count(),
(None, Some(s)) => s.chars().count(),
(Some(p), Some(s)) => {
let p_chars: Vec<char> = p.chars().collect();
let s_chars: Vec<char> = s.chars().collect();
if s_chars.is_empty() {
return p_chars.len();
}
let mut pi = vec![0usize; s_chars.len()];
let mut matched = 0usize;
for idx in 1..s_chars.len() {
while matched > 0 && s_chars[matched] != s_chars[idx] {
matched = pi[matched - 1];
}
if s_chars[matched] == s_chars[idx] {
matched += 1;
pi[idx] = matched;
}
}
let mut overlap = 0usize;
for &ch in &p_chars {
while overlap > 0 && (overlap == s_chars.len() || s_chars[overlap] != ch) {
overlap = pi[overlap - 1];
}
if s_chars[overlap] == ch {
overlap += 1;
}
}
p_chars.len() + s_chars.len() - overlap
}
}
}
fn parse_key_shape(
key: &str,
shape: Option<&str>,
one_of: Option<Vec<String>>,
path: &Path,
) -> Result<Option<ValueShape>, ConfigError> {
if let Some(allowed) = one_of {
if allowed.is_empty() {
return Err(ConfigError::at(
path,
format!("schema.keys.{key}.one_of must not be empty"),
));
}
if let Some(shape_name) = shape {
if shape_name != "one-of" {
return Err(ConfigError::at(
path,
format!("schema.keys.{key} cannot set both shape and one_of"),
));
}
}
return Ok(Some(ValueShape::OneOf(allowed)));
}
let Some(shape_name) = shape else {
return Ok(None);
};
let parsed = match shape_name {
"any" => ValueShape::Any,
"bool" => ValueShape::Bool,
"integer" => ValueShape::Integer,
"unsigned-integer" => ValueShape::UnsignedInteger,
"port" => ValueShape::Port,
"float" => ValueShape::Float,
"url" => ValueShape::Url,
"ip-addr" => ValueShape::IpAddr,
"host" => ValueShape::Host,
"socket-addr" => ValueShape::SocketAddr,
"email" => ValueShape::Email,
"one-of" => {
return Err(ConfigError::at(
path,
format!("schema.keys.{key} with shape \"one-of\" requires one_of"),
));
}
other => return Err(ConfigError::at(path, unknown("value shape", other))),
};
Ok(Some(parsed))
}
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);
}
}
Rule::MissingKey if !explicit.schema_example || enabled => {
policy.lint = policy.lint.with_missing_keys(enabled);
}
Rule::UnknownKey if !explicit.schema_allow_unknown || enabled => {
policy.lint = policy.lint.with_unknown_keys(enabled);
}
Rule::EmptyValue if !explicit.schema_allow_empty || enabled => {
policy.lint = policy.lint.with_empty_values(enabled);
}
Rule::InvalidValue => {
policy.lint = policy.lint.with_invalid_values(enabled);
}
Rule::DeprecatedKey => {
policy.lint = policy.lint.with_deprecated_keys(enabled);
}
_ => {}
}
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>,
pub schema: Option<SchemaConfig>,
}
impl Default for LintPolicy {
fn default() -> Self {
Self {
dialect: Dialect::PORTABLE,
format: OutputFormat::Human,
recursive: false,
lint: LintOptions::default(),
ignore: Vec::new(),
schema: None,
}
}
}
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,
pub schema_example: bool,
pub schema_allow_unknown: bool,
pub schema_allow_empty: 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> {
Rule::from_name(value)
}
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,
)])),
schema: None,
};
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");
let mut explicit_policy = LintPolicy {
lint: LintOptions::new().with_key_order(true),
..LintPolicy::default()
};
let off_order =
LintConfig::from_toml("[rules]\nkey-order = \"off\"\n", Path::new("off.toml")).unwrap();
off_order.apply(
&mut explicit_policy,
ConfigExplicit {
key_order: true,
..ConfigExplicit::default()
},
);
assert!(explicit_policy.lint.key_order);
let ignores = IgnoredPaths::new(&[".env.skip".to_owned()]).unwrap();
assert!(!ignores.is_ignored(Path::new("/repo/.env.keep")));
}
#[test]
fn schema_config_parses_resolves_validates_and_honors_explicit_precedence() {
let toml = r#"
[rules]
missing-key = "error"
unknown-key = "warning"
empty-value = "off"
invalid-value = "error"
[schema]
example = ".env.example"
allow_unknown = false
allow_empty = false
[schema.keys.ANY_KEY]
shape = "any"
[schema.keys.BOOL_KEY]
shape = "bool"
[schema.keys.INT_KEY]
shape = "integer"
[schema.keys.UINT_KEY]
shape = "unsigned-integer"
[schema.keys.PORT]
required = true
allow_empty = false
allow_bare = false
shape = "port"
[schema.keys.RATE]
shape = "float"
[schema.keys.URL]
shape = "url"
[schema.keys.ENV_IMPLICIT]
one_of = ["dev", "prod"]
[schema.keys.ENV_EXPLICIT]
required = false
allow_empty = true
allow_bare = true
shape = "one-of"
one_of = ["a", "b"]
"#;
let config = LintConfig::from_toml(toml, Path::new("/repo/.adotenv-lint.toml")).unwrap();
let schema_cfg = config.schema.as_ref().unwrap();
assert_eq!(
schema_cfg.example.as_deref(),
Some(Path::new("/repo/.env.example"))
);
assert_eq!(schema_cfg.allow_unknown, Some(false));
assert_eq!(schema_cfg.allow_empty, Some(false));
assert_eq!(schema_cfg.keys["ANY_KEY"].shape, Some(ValueShape::Any));
assert_eq!(schema_cfg.keys["BOOL_KEY"].shape, Some(ValueShape::Bool));
assert_eq!(schema_cfg.keys["INT_KEY"].shape, Some(ValueShape::Integer));
assert_eq!(
schema_cfg.keys["UINT_KEY"].shape,
Some(ValueShape::UnsignedInteger)
);
assert_eq!(schema_cfg.keys["PORT"].shape, Some(ValueShape::Port));
assert_eq!(schema_cfg.keys["RATE"].shape, Some(ValueShape::Float));
assert_eq!(schema_cfg.keys["URL"].shape, Some(ValueShape::Url));
assert_eq!(
schema_cfg.keys["ENV_IMPLICIT"].shape,
Some(ValueShape::OneOf(vec!["dev".to_owned(), "prod".to_owned()]))
);
assert_eq!(schema_cfg.keys["ENV_EXPLICIT"].required, Some(false));
assert_eq!(schema_cfg.keys["ENV_EXPLICIT"].allow_empty, Some(true));
assert_eq!(schema_cfg.keys["ENV_EXPLICIT"].allow_bare, Some(true));
let example = adotenv::parse_strict("FROM_EX=1\nPORT=8080\nBARE_EX\n").unwrap();
let resolved = schema_cfg.resolve(Some(&example));
assert!(!resolved.allow_unknown);
assert!(!resolved.allow_empty);
assert!(resolved.keys["FROM_EX"].required);
assert!(resolved.keys["BARE_EX"].allow_bare);
assert_eq!(resolved.keys["PORT"].shape, ValueShape::Port);
assert!(!resolved.keys["ENV_EXPLICIT"].required);
}
#[test]
fn schema_config_paths_and_explicit_precedence_apply() {
let bare = LintConfig::from_toml(
"[schema]\nexample = \".env.example\"\n",
Path::new("test.toml"),
)
.unwrap();
assert_eq!(
bare.schema.unwrap().example.as_deref(),
Some(Path::new(".env.example"))
);
let abs = LintConfig::from_toml(
"[schema]\nexample = \"/etc/app/.env.example\"\n",
Path::new("/repo/.adotenv-lint.toml"),
)
.unwrap();
assert_eq!(
abs.schema.unwrap().example.as_deref(),
Some(Path::new("/etc/app/.env.example"))
);
let config = LintConfig::from_toml(
"[rules]\nmissing-key = \"error\"\nunknown-key = \"warning\"\nempty-value = \"off\"\ninvalid-value = \"error\"\n[schema]\nexample = \".env.example\"\nallow_unknown = false\nallow_empty = false\n",
Path::new("/repo/.adotenv-lint.toml"),
)
.unwrap();
let mut policy = LintPolicy::default();
config.apply(&mut policy, ConfigExplicit::default());
assert_eq!(
policy.lint.severity_for_rule(Rule::MissingKey),
Severity::Error
);
assert_eq!(
policy.lint.severity_for_rule(Rule::UnknownKey),
Severity::Warning
);
assert!(!policy.lint.empty_values);
assert_eq!(
policy.lint.severity_for_rule(Rule::InvalidValue),
Severity::Error
);
assert!(policy.schema.is_some());
let mut explicit_policy = LintPolicy {
schema: Some(SchemaConfig {
example: Some(PathBuf::from("cli.example")),
allow_unknown: Some(true),
allow_empty: Some(true),
keys: BTreeMap::new(),
}),
..LintPolicy::default()
};
config.apply(
&mut explicit_policy,
ConfigExplicit {
schema_example: true,
schema_allow_unknown: true,
schema_allow_empty: true,
..ConfigExplicit::default()
},
);
let merged = explicit_policy.schema.unwrap();
assert_eq!(merged.example.as_deref(), Some(Path::new("cli.example")));
assert_eq!(merged.allow_unknown, Some(true));
assert_eq!(merged.allow_empty, Some(true));
assert!(explicit_policy.lint.empty_values);
}
#[test]
fn schema_rule_toggles_honor_explicit_cli_flags() {
let off_all = LintConfig::from_toml(
"[rules]\nmissing-key = \"off\"\nunknown-key = \"off\"\ninvalid-value = \"off\"\n",
Path::new("off.toml"),
)
.unwrap();
let mut default_policy = LintPolicy::default();
off_all.apply(&mut default_policy, ConfigExplicit::default());
assert!(!default_policy.lint.missing_keys);
assert!(!default_policy.lint.unknown_keys);
assert!(!default_policy.lint.invalid_values);
let mut cli_kept = LintPolicy::default();
off_all.apply(
&mut cli_kept,
ConfigExplicit {
schema_example: true,
schema_allow_unknown: true,
..ConfigExplicit::default()
},
);
assert!(cli_kept.lint.missing_keys);
assert!(cli_kept.lint.unknown_keys);
let enable_unknown =
LintConfig::from_toml("[rules]\nunknown-key = \"error\"\n", Path::new("on.toml"))
.unwrap();
let mut reenabled = LintPolicy {
lint: LintOptions::new().with_unknown_keys(false),
..LintPolicy::default()
};
enable_unknown.apply(
&mut reenabled,
ConfigExplicit {
schema_allow_unknown: true,
..ConfigExplicit::default()
},
);
assert!(reenabled.lint.unknown_keys);
assert_eq!(
reenabled.lint.severity_for_rule(Rule::UnknownKey),
Severity::Error
);
}
#[test]
fn invalid_schema_configs_are_rejected_with_clear_errors() {
for (snippet, expected) in [
(
"[schema]\nexample = \"\"\n",
"schema.example must not be empty",
),
(
"[schema]\nunknown_field = true\n",
"unknown field `unknown_field`",
),
(
"[schema.keys.\"\"]\nrequired = true\n",
"schema key name must not be empty",
),
(
"[schema.keys.A]\nshape = \"bogus\"\n",
"unknown value shape: bogus",
),
("[schema.keys.A]\nshape = \"one-of\"\n", "requires one_of"),
("[schema.keys.A]\none_of = []\n", "one_of must not be empty"),
(
"[schema.keys.A]\nshape = \"port\"\none_of = [\"80\"]\n",
"cannot set both shape and one_of",
),
("[schema.keys.A]\nextra = 1\n", "unknown field `extra`"),
] {
let err = LintConfig::from_toml(snippet, Path::new("bad.toml")).unwrap_err();
assert!(err.message().contains(expected), "{snippet:?} -> {err}");
}
}
#[test]
fn config_load_is_bounded_and_apply_merges_per_key_schema_overrides() {
let dir = TempDir::new("bounded-cfg");
let err = LintConfig::load(dir.path()).unwrap_err();
assert!(err.message().contains("regular file"), "{err}");
assert_eq!(MAX_CONFIG_BYTES, 4_194_304);
let small = dir.file("small.toml", "key_order = true\n");
assert_eq!(
read_config_bounded(&small, 17).unwrap(),
"key_order = true\n"
);
let too_big = read_config_bounded(&small, 16).unwrap_err();
assert!(too_big.message().contains("maximum size"), "{too_big}");
let empty = dir.file("empty.toml", "");
assert_eq!(read_config_bounded(&empty, 0).unwrap(), "");
let invalid_utf8 = dir.path().join("bad-utf8.toml");
fs::write(&invalid_utf8, [0xff, 0xfe]).unwrap();
let utf8_err = LintConfig::load(&invalid_utf8).unwrap_err();
assert!(utf8_err.message().contains("UTF-8"), "{utf8_err}");
let first = LintConfig::from_toml(
"[schema.keys.PORT]\nrequired = false\nallow_empty = true\nallow_bare = true\n",
Path::new("first.toml"),
)
.unwrap();
let second = LintConfig::from_toml(
"[schema.keys.PORT]\nshape = \"port\"\n",
Path::new("second.toml"),
)
.unwrap();
let mut policy = LintPolicy::default();
first.apply(&mut policy, ConfigExplicit::default());
second.apply(&mut policy, ConfigExplicit::default());
let port = &policy.schema.unwrap().keys["PORT"];
assert_eq!(port.required, Some(false));
assert_eq!(port.allow_empty, Some(true));
assert_eq!(port.allow_bare, Some(true));
assert_eq!(port.shape, Some(ValueShape::Port));
}
#[test]
fn sarif_new_shapes_metadata_deprecation_bounds_and_merges_validate() {
assert_eq!(OutputFormat::Sarif.as_str(), "sarif");
assert_eq!(parse_output_format("sarif").unwrap(), OutputFormat::Sarif);
let cfg = LintConfig::from_toml(
r#"
format = "sarif"
[rules]
deprecated-key = "error"
[schema.keys.BIND]
shape = "socket-addr"
description = "Socket bind address"
[schema.keys.IP]
shape = "ip-addr"
[schema.keys.HOST]
shape = "host"
[schema.keys.ADMIN_EMAIL]
shape = "email"
[schema.keys.OLD_FLAG]
required = false
deprecated = true
[schema.keys.OLD_NOTE]
required = false
deprecated = "use NEW_KEY"
[schema.keys.SECRET_KEY]
prefix = "sk_"
suffix = "_v1"
min_len = 8
max_len = 32
"#,
Path::new("v04.toml"),
)
.unwrap();
assert_eq!(cfg.format, Some(OutputFormat::Sarif));
let mut policy = LintPolicy::default();
cfg.apply(&mut policy, ConfigExplicit::default());
assert_eq!(policy.format, OutputFormat::Sarif);
assert!(policy.lint.deprecated_keys);
assert_eq!(
policy.lint.severity_for_rule(Rule::DeprecatedKey),
Severity::Error
);
let resolved = policy.schema.as_ref().unwrap().resolve(None);
assert_eq!(resolved.keys["BIND"].shape, ValueShape::SocketAddr);
assert_eq!(
resolved.keys["BIND"].description.as_deref(),
Some("Socket bind address")
);
assert_eq!(resolved.keys["IP"].shape, ValueShape::IpAddr);
assert_eq!(resolved.keys["HOST"].shape, ValueShape::Host);
assert_eq!(resolved.keys["ADMIN_EMAIL"].shape, ValueShape::Email);
assert!(resolved.keys["OLD_FLAG"].deprecated);
assert_eq!(resolved.keys["OLD_FLAG"].deprecation_note, None);
assert!(resolved.keys["OLD_NOTE"].deprecated);
assert_eq!(
resolved.keys["OLD_NOTE"].deprecation_note.as_deref(),
Some("use NEW_KEY")
);
assert_eq!(resolved.keys["SECRET_KEY"].prefix.as_deref(), Some("sk_"));
assert_eq!(resolved.keys["SECRET_KEY"].suffix.as_deref(), Some("_v1"));
assert_eq!(resolved.keys["SECRET_KEY"].min_len, Some(8));
assert_eq!(resolved.keys["SECRET_KEY"].max_len, Some(32));
let off_dep =
LintConfig::from_toml("[rules]\ndeprecated-key = \"off\"\n", Path::new("off.toml"))
.unwrap();
let mut dep_policy = LintPolicy::default();
off_dep.apply(&mut dep_policy, ConfigExplicit::default());
assert!(!dep_policy.lint.deprecated_keys);
}
#[test]
fn schema_metadata_and_bounds_merge_and_reject_contradictions() {
let base = LintConfig::from_toml(
"[schema.keys.K]\ndescription = \"old\"\ndeprecated = \"old note\"\nprefix = \"a\"\nmin_len = 2\n",
Path::new("base.toml"),
)
.unwrap();
let keep_note = LintConfig::from_toml(
"[schema.keys.K]\ndeprecated = true\nsuffix = \"z\"\nmax_len = 10\n",
Path::new("keep.toml"),
)
.unwrap();
let clear_dep = LintConfig::from_toml(
"[schema.keys.K]\ndescription = \"new\"\ndeprecated = false\n",
Path::new("clear.toml"),
)
.unwrap();
let mut merged_policy = LintPolicy::default();
base.apply(&mut merged_policy, ConfigExplicit::default());
keep_note.apply(&mut merged_policy, ConfigExplicit::default());
let k_mid = &merged_policy.schema.as_ref().unwrap().keys["K"];
assert_eq!(k_mid.deprecated, Some(true));
assert_eq!(k_mid.deprecation_note.as_deref(), Some("old note"));
assert_eq!(k_mid.prefix.as_deref(), Some("a"));
assert_eq!(k_mid.suffix.as_deref(), Some("z"));
assert_eq!(k_mid.min_len, Some(2));
assert_eq!(k_mid.max_len, Some(10));
clear_dep.apply(&mut merged_policy, ConfigExplicit::default());
let k_final = &merged_policy.schema.as_ref().unwrap().keys["K"];
assert_eq!(k_final.description.as_deref(), Some("new"));
assert_eq!(k_final.deprecated, Some(false));
assert_eq!(k_final.deprecation_note, None);
let k_resolved = merged_policy.schema.as_ref().unwrap().resolve(None);
assert!(!k_resolved.keys["K"].deprecated);
assert_eq!(k_resolved.keys["K"].deprecation_note, None);
let mut note_only_keys = BTreeMap::new();
note_only_keys.insert(
"LEGACY".to_owned(),
KeySchemaConfig {
deprecation_note: Some("migrate".to_owned()),
..KeySchemaConfig::default()
},
);
let note_only_cfg = 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: None,
schema: Some(SchemaConfig {
example: None,
allow_unknown: None,
allow_empty: None,
keys: note_only_keys,
}),
};
let mut note_policy = LintPolicy::default();
note_only_cfg.apply(&mut note_policy, ConfigExplicit::default());
let leg_cfg = ¬e_policy.schema.as_ref().unwrap().keys["LEGACY"];
assert_eq!(leg_cfg.deprecated, Some(true));
assert_eq!(leg_cfg.deprecation_note.as_deref(), Some("migrate"));
let leg_res = note_only_cfg.schema.as_ref().unwrap().resolve(None);
assert!(leg_res.keys["LEGACY"].deprecated);
assert_eq!(
leg_res.keys["LEGACY"].deprecation_note.as_deref(),
Some("migrate")
);
}
#[test]
fn schema_literal_bounds_and_deprecation_notes_reject_contradictions() {
assert!(LintConfig::from_toml(
"[schema.keys.U]\nprefix = \"éé\"\nmax_len = 2\n",
Path::new("ok.toml"),
)
.is_ok());
assert!(LintConfig::from_toml(
"[schema.keys.OVERLAP]\nprefix = \"aba\"\nsuffix = \"aba\"\nmax_len = 3\n",
Path::new("overlap.toml"),
)
.is_ok());
assert!(LintConfig::from_toml(
"[schema.keys.PARTIAL]\nprefix = \"abc\"\nsuffix = \"bcd\"\nmax_len = 4\n",
Path::new("partial.toml"),
)
.is_ok());
assert!(LintConfig::from_toml(
"[schema.keys.KMP]\nprefix = \"abab\"\nsuffix = \"aba\"\nmax_len = 5\n",
Path::new("kmp.toml"),
)
.is_ok());
assert!(LintConfig::from_toml(
"[schema.keys.EXACT]\nmin_len = 4\nmax_len = 4\n",
Path::new("exact.toml"),
)
.is_ok());
assert!(LintConfig::from_toml(
"[schema.keys.KMP_BACKTRACK]\nprefix = \"aabaaab\"\nsuffix = \"aabaaac\"\nmax_len = 11\n",
Path::new("kmp_bt.toml"),
)
.is_ok());
assert!(LintConfig::from_toml(
"[schema.keys.KMP_PI_STEP]\nprefix = \"aaabaaaab\"\nsuffix = \"aaabaaaac\"\nmax_len = 14\n",
Path::new("kmp_pi.toml"),
)
.is_ok());
assert!(LintConfig::from_toml(
"[schema.keys.EMPTY_SUF]\nprefix = \"abc\"\nsuffix = \"\"\nmax_len = 3\n",
Path::new("empty_suf.toml"),
)
.is_ok());
for (snippet, expected) in [
(
"[schema.keys.A]\ndeprecated = \"\"\n",
"deprecated note must not be empty",
),
(
"[schema.keys.A]\ndeprecated = \" \"\n",
"deprecated note must not be empty",
),
(
"[schema.keys.A]\nmin_len = 5\nmax_len = 4\n",
"min_len (5) exceeds max_len (4)",
),
(
"[schema.keys.A]\nprefix = \"sk_live_\"\nmax_len = 4\n",
"shorter than configured prefix/suffix",
),
(
"[schema.keys.A]\nsuffix = \".pem\"\nmax_len = 3\n",
"shorter than configured prefix/suffix",
),
(
"[schema.keys.A]\nprefix = \"ééé\"\nmax_len = 2\n",
"shorter than configured prefix/suffix",
),
(
"[schema.keys.A]\nprefix = \"ab\"\nsuffix = \"cd\"\nmax_len = 3\n",
"shorter than configured prefix/suffix (4)",
),
(
"[schema.keys.A]\nprefix = \"abc\"\nsuffix = \"bcd\"\nmax_len = 3\n",
"shorter than configured prefix/suffix (4)",
),
(
"[schema.keys.A]\nprefix = \"abab\"\nsuffix = \"aba\"\nmax_len = 4\n",
"shorter than configured prefix/suffix (5)",
),
(
"[schema.keys.A]\nprefix = \"aabaaab\"\nsuffix = \"aabaaac\"\nmax_len = 10\n",
"shorter than configured prefix/suffix (11)",
),
(
"[schema.keys.A]\nprefix = \"aaabaaaab\"\nsuffix = \"aaabaaaac\"\nmax_len = 13\n",
"shorter than configured prefix/suffix (14)",
),
] {
let err = LintConfig::from_toml(snippet, Path::new("bad.toml")).unwrap_err();
assert!(err.message().contains(expected), "{snippet:?} -> {err}");
}
}
#[test]
fn key_schema_config_builders_populate_every_override() {
let built = KeySchemaConfig::new()
.with_required(false)
.with_allow_empty(true)
.with_allow_bare(true)
.with_shape(ValueShape::Email)
.with_description("Admin email")
.with_deprecation_note("use CONTACT_EMAIL")
.with_prefix("ops@")
.with_suffix(".com")
.with_min_len(8)
.with_max_len(64);
assert_eq!(built.required, Some(false));
assert_eq!(built.allow_empty, Some(true));
assert_eq!(built.allow_bare, Some(true));
assert_eq!(built.shape, Some(ValueShape::Email));
assert_eq!(built.description.as_deref(), Some("Admin email"));
assert_eq!(built.deprecated, Some(true));
assert_eq!(built.deprecation_note.as_deref(), Some("use CONTACT_EMAIL"));
assert_eq!(built.prefix.as_deref(), Some("ops@"));
assert_eq!(built.suffix.as_deref(), Some(".com"));
assert_eq!(built.min_len, Some(8));
assert_eq!(built.max_len, Some(64));
let un_dep = built.with_deprecated(false);
assert_eq!(un_dep.deprecated, Some(false));
assert_eq!(un_dep.deprecation_note, None);
}
}