adotenv-lint 0.4.0

Opt-in lint rules, schema checks and verified fixes for adotenv documents.
Documentation

adotenv-lint

Optional lint rules, schema checks and verified fixes for adotenv documents.

The linter is a companion crate: lint and schema policies do not belong in the parser core. Findings are structured and never contain values. A finding may carry a fix that is applied through adotenv's verified edit or format APIs.

use adotenv_lint::{
    apply_batch_with_policy, lint, lint_with_schema, BatchOptions, KeySchema, LintOptions, Rule,
    Schema, ValueShape,
};

let doc = adotenv::parse_strict("B=2\nA=1\n")?;
let findings = lint(&doc, LintOptions::default().with_key_order(true));
assert_eq!(findings[0].rule(), Rule::KeyOrder);

let fixed = adotenv_lint::apply_fix(&doc, findings[0].fix().unwrap())?;
assert_eq!(fixed.as_str(), "A=1\nB=2\n");

let example = adotenv::parse_strict("HOST=localhost\nPORT=8080\n")?;
let schema = Schema::from_example(&example)
    .with_allow_unknown(false)
    .with_key("HOST", KeySchema::new().with_shape(ValueShape::Host))
    .with_key("PORT", KeySchema::new().with_shape(ValueShape::Port));
let app = adotenv::parse_strict("PORT=8080\n")?;
let schema_findings = lint_with_schema(&app, LintOptions::default(), &schema);
assert_eq!(schema_findings[0].rule(), Rule::MissingKey);

let fixes: Vec<_> = schema_findings
    .iter()
    .filter_map(|f| f.fix().cloned())
    .collect();
let scaffolded = apply_batch_with_policy(
    &app,
    &fixes,
    BatchOptions::new().with_insert_missing(true),
)?;
assert_eq!(scaffolded.output(), "PORT=8080\nHOST=\n");
# Ok::<(), Box<dyn std::error::Error>>(())

CLI

adotenv-lint [options] <file-or-directory>...

Examples:

adotenv-lint --key-order --key-case upper .env
adotenv-lint --example .env.example --no-unknown-keys --no-empty-values .env
adotenv-lint --format=json --recursive .
adotenv-lint --format=github --key-order .
adotenv-lint --format=sarif --recursive .
adotenv-lint --list-rules
adotenv-lint --explain missing-key
adotenv-lint --recursive --exclude='target/**' .
adotenv-lint --max-input-bytes 1048576 --max-lines 10000 --max-items 50000 .env
adotenv-lint --fix --quote-style=unquoted --equals-spacing=none --max-output-bytes 1048576 .env
adotenv-lint --example .env.example --fix --fix-missing --key-order .env

Without --fix the CLI is report-only. With --fix it applies compatible verified style fixes in batches (including two-pass QuoteStyle::Unquoted when combined with trivia formatting) and rewrites changed files through a temporary file in the same directory. Adding --fix-missing alongside --fix also inserts empty KEY= placeholders for missing required keys without copying values from .env.example. --list-rules and --explain <rule> print offline rule documentation and exit with 0. With no path it searches the current directory recursively, even when the configuration sets recursive = false. It discovers .env and .env.* files with --recursive, skips .git, target, node_modules, and the configured --example / [schema] example file during directory discovery (explicit positional file arguments are still linted), and exits with 0 for no findings (or all findings fixed), 1 for remaining findings and 2 for usage, read, parse, limit or write errors. Human output reports the configured severity as severity[rule]; JSON includes severity (and optional detail), GitHub annotations use the matching error, warning or notice level, and --format=sarif emits SARIF 2.1.0 JSON for GitHub Code Scanning and IDE problem matchers. The Windows replace fallback is best-effort and not crash-atomic, matching the CLI write contract.

Configuration

By default the command discovers .adotenv-lint.toml from the current directory upward. Use --config <path> to select another file. Command-line options override configuration values.

dialect = "portable"
format = "json"
recursive = true
key_order = true
key_case = "upper"
quote_style = "double"
equals_spacing = "none"
trim_trailing_whitespace = true
ignore = ["target/**", "vendor/**"]

[rules]
duplicate-key = "error"
key-order = "warning"
key-case = "off"
missing-key = "error"
unknown-key = "error"
empty-value = "warning"
invalid-value = "error"
deprecated-key = "warning"

[schema]
example = ".env.example"
allow_unknown = false
allow_empty = false

[schema.keys.PORT]
shape = "port"
description = "HTTP listen port"

[schema.keys.APP_ENV]
one_of = ["development", "staging", "production"]

[schema.keys.BIND_ADDR]
shape = "socket-addr"

[schema.keys.API_TOKEN]
prefix = "sk_"
min_len = 16
max_len = 128

[schema.keys.LEGACY_HOST]
required = false
deprecated = "use HOST instead"

[schema.keys.DEBUG]
required = false
allow_empty = true
shape = "bool"

All fields are optional. Unknown fields, unknown rules, unknown value shapes, empty deprecated = "" notes, and contradictory bounds (min_len > max_len or max_len shorter than prefix/suffix) are rejected so typos are visible. format accepts human, json, github, or sarif. rules values are off, warning or error; off disables the rule. key-order is enabled by its rule severity. warning and error for key-case, quote-style, whitespace, missing-key, unknown-key, empty-value, invalid-value and deprecated-key set the reported severity (and schema rules still require --example, --no-empty-values, or [schema]). Relative schema.example paths resolve against the directory containing .adotenv-lint.toml. Supported shape values are any, bool, integer, unsigned-integer, port, float, url, ip-addr, host, socket-addr, email and one-of (with one_of = [...], which also implies one-of). Each key may also declare description, deprecated = true | false | "reason", prefix, suffix, min_len, and max_len (measured in Unicode scalar characters). CLI options override the corresponding configuration values, and --exclude replaces configured ignore patterns. Ignore globs match a full path, a basename, a path relative to the discovery root, or a path suffix for LSP document URIs, so patterns such as target/** also apply to absolute editor URIs.

Library policy API

The same configuration model is available without the CLI:

use adotenv_lint::{ConfigExplicit, LintPolicy, load_effective_config};

let start = std::env::current_dir()?;
let config = load_effective_config(None, &start)?;
let mut policy = LintPolicy::default();
if let Some(config) = config {
    config.apply(&mut policy, ConfigExplicit::default());
}
assert_eq!(policy.dialect, adotenv::Dialect::PORTABLE);
# Ok::<(), Box<dyn std::error::Error>>(())

load_effective_config handles explicit paths and ancestor discovery. LintConfig::from_toml is available for callers that already have the source. LintPolicy carries the resolved dialect, format, recursive mode, lint rules, ignored glob patterns and optional [schema] configuration, so the language server can share the CLI policy without a second parser or discovery implementation.

Rules

The default policy reports duplicate keys only when no Schema is supplied. Enable the other rules or supply a Schema explicitly:

Rule Default Rationale
duplicate-key on Repeated declarations are usually accidental and make lookup depend on dialect policy.
key-order off Sorting is a style choice; some files group related keys deliberately.
key-case off Upper- and lowercase keys are both common in the wild.
quote-style preserve Quote policy depends on the project and on values that contain references.
whitespace preserve Whitespace policy is project-specific; formatting is opt-in.
missing-key schema opt-in Reports required keys declared in a Schema or .env.example that are missing.
unknown-key schema opt-in Reports undeclared keys when allow_unknown = false (--no-unknown-keys).
empty-value schema opt-in Reports empty (KEY=) or disallowed bare (KEY) values under a Schema or --no-empty-values.
invalid-value schema opt-in Reports literal values that do not match their configured ValueShape or literal bounds.
deprecated-key schema opt-in Reports declared keys marked deprecated in the active Schema.

Findings include the rule, configured severity, one-based line, source span, key, optional value-free detail (such as a deprecation note or bound expectation), and an optional verified fix. Schema checks operate on decoded literal values (Entry::value), never expand references or inspect the process environment, and never include document values in findings. missing-key findings attach Fix::InsertEmpty (which inserts KEY= with an empty value and never copies .env.example values); all other schema findings have no automatic fix. Key-order findings cover a whole group and have no key; groups that Document::sort_with_options refuses to reorder (for example due to a cycle or exceeded EditOptions::max_references) are still reported without a fix because no verified sort edit exists. apply_fix / apply_fix_with_options apply one fix and apply_fixes / apply_fixes_with_options apply one compatible single-pass batch; apply_batch / apply_batch_with_options apply independent style renames together followed by sorting and formatting (skipping Fix::InsertEmpty by default, and splitting QuoteStyle::Unquoted into its own verified stage when combined with trivia rewrites, which single-pass Document::format_with_options intentionally leaves unquoted-neutral) while honoring EditOptions output, reference and parse bounds. Use apply_batch_with_policy with BatchOptions::new().with_insert_missing(true) (or CLI --fix --fix-missing) to include verified empty-placeholder insertions ahead of sorting and formatting. Parse diagnostics remain available from adotenv::parse.

This crate requires Rust 1.81 and does not change the core crate's no_std or dependency-free guarantees.

Version 0.1.0 was the first published release of the companion crate. Version 0.2.0 added the shared configuration loader and ignored-path API used by the CLI and language server. Version 0.2.1 fixes rooted ignore matching, severity output and explicit whitespace-option precedence, and reports unsortable key-order groups without a fix. Version 0.2.2 adopts adotenv 1.6.0 and adds --max-input-bytes and --max-lines parse-limit flags across lint and --fix runs. Version 0.2.3 adopts adotenv 1.7.0 and hardens multi-file error reporting, bounded file reads, stdout error handling, explicit symlinked root rejection and canonical path deduplication. Version 0.3.0 adopts adotenv 1.8.0, adds opt-in schema and .env.example presence-and-shape rules (Schema, KeySchema, ValueShape, [schema], --example, --no-unknown-keys, --no-empty-values), adds bounded lint_with_schema, lint_with_options, apply_fix_with_options, apply_fixes_with_options and apply_batch_with_options (with two-pass QuoteStyle::Unquoted convergence), and adds --max-items, --max-diagnostics, --max-output-bytes, --max-output-lines and --max-references CLI flags. Version 0.3.1 adopts adotenv 1.8.1, hardens LintConfig::load with a regular-file check and 4 MiB read cap (enforcing --max-input-bytes on CLI config reads), merges per-key [schema.keys.*] overrides in LintConfig::apply, rejects empty closed [schema] allow_unknown = false configs consistently with --no-unknown-keys, and escapes control, line-separator and Bidi characters in human-output keys. Version 0.3.2 extends key escaping to --format=github annotations and keeps CLI .adotenv-lint.toml config reads capped at min(--max-input-bytes, 4 MiB). Version 0.4.0 adds schema key metadata (description, deprecated, deprecation_note), Rule::DeprecatedKey, zero-new-dependency std shapes (ValueShape::{IpAddr, Host, SocketAddr, Email}), literal bounds (prefix, suffix, min_len, max_len), Finding::detail, opt-in value-free Fix::InsertEmpty scaffolding (BatchOptions, apply_batch_with_policy, CLI --fix --fix-missing), SARIF 2.1.0 output (OutputFormat::Sarif, --format=sarif), and offline rule docs (Rule::ALL, Rule::from_name, Rule::explain, RuleExplanation, CLI --list-rules and --explain <rule>).