- Rust 94.9%
- Astro 1.4%
- Python 1.3%
- JavaScript 1.2%
- TypeScript 0.6%
- Other 0.6%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
|
Some checks failed
CI / test (macos-latest) (push) Waiting to run
CI / test (windows-latest) (push) Waiting to run
CI / public API semver (push) Failing after 13s
CI / fmt, clippy, docs (push) Failing after 13s
CI / supply chain (push) Failing after 13s
CI / coverage report (push) Failing after 12s
CI / minimal versions (push) Failing after 4s
CI / MSRV (1.81) (push) Failing after 4s
CI / test (ubuntu-latest) (push) Failing after 4s
CI / MSRV adotenv-config (1.88) (push) Failing after 4s
CI / benchmark smoke (push) Failing after 5s
CI / deterministic perf (push) Failing after 4s
CI / package (push) Failing after 5s
CI / alloc-only core (push) Failing after 3s
CI / pinned upstream conformance observations (push) Failing after 5s
Docs / build site (push) Failing after 5s
Docs / deploy site (push) Waiting to run
### Summary
- **Release records (`adotenv-lsp 0.8.1`)**: records the verified
`adotenv-lsp 0.8.1` post-delivery audit patch release across
`docs/design/releases.md`, `ROADMAP.md`, and
`docs/design/companion-0.4-0.8-plan.md`.
- Commit: `
|
||
| .cargo | ||
| .github | ||
| adotenv-bench | ||
| adotenv-cli | ||
| adotenv-config | ||
| adotenv-figment | ||
| adotenv-lint | ||
| adotenv-lsp | ||
| adotenv-process | ||
| benches | ||
| conformance | ||
| docs | ||
| fuzz | ||
| proptest-regressions | ||
| scripts | ||
| site | ||
| src | ||
| tests | ||
| xtask | ||
| .gitattributes | ||
| .gitignore | ||
| AGENTS.md | ||
| Cargo.lock | ||
| Cargo.toml | ||
| CHANGELOG.md | ||
| deny.toml | ||
| LICENSE-APACHE | ||
| LICENSE-MIT | ||
| README.md | ||
| RELEASING.md | ||
| ROADMAP.md | ||
| wrangler.jsonc | ||
adotenv
A literal, lossless .env parser and editing library for Rust.
- Guide: https://zeropier.com/adotenv/
- API reference: https://docs.rs/adotenv
adotenv is built for linters, formatters, editors, scanners and codebase maintenance tools. It keeps source text exactly as written, reports precise locations and verifies every edit before returning it.
What it does
- Values stay literal.
${HOME},$USERand command-like text are never expanded or executed by the parser. - Any UTF-8 source round-trips byte for byte, including invalid statements, comments, spacing, a BOM and mixed line endings.
- Every token has a source span. Decoded values map back to the original bytes.
- Edits return source-relative text edits and a re-parsed, verified result.
- The core has no required dependencies (only the optional
serdefeature adds one), no file I/O, no environment access and no process spawning.#![forbid(unsafe_code)]is unconditional. - Filesystem loading, process mutation and command execution are separate opt-in features or crates.
Install
[dependencies]
adotenv = "1"
| Feature | Purpose |
|---|---|
default (std) |
Standard library support; required by load and exec |
load |
Read .env cascades from files |
serde |
Deserialize documents and loaded environments |
exec |
Run command substitutions with an explicit directory |
Disable default features for a no_std core that uses alloc:
adotenv = { version = "1", default-features = false }
Parse
let text = "# app\nexport PORT=8080\nURL=\"${HOST}/api\" # base\n";
let doc = adotenv::parse_strict(text).unwrap();
assert_eq!(doc.get("PORT"), Some("8080"));
assert_eq!(doc.get("URL"), Some("${HOST}/api"));
assert_eq!(doc.to_string(), text);
let url = doc.get_entry("URL").unwrap();
assert_eq!(url.line(), 3);
assert_eq!(&text[url.value_span().unwrap()], "\"${HOST}/api\"");
let edited = doc.set("URL", "https://example.invalid").unwrap();
assert_eq!(
adotenv::parse_strict(edited.as_str()).unwrap().get("URL"),
Some("https://example.invalid")
);
parse_strict returns the first error. parse always returns a document and a
list of diagnostics, so callers can inspect broken files without losing source:
let (doc, diagnostics) = adotenv::parse("BAD KEY=value\nGOOD=retained\n");
assert_eq!(doc.get("GOOD"), Some("retained"));
assert_eq!(doc.items().next().unwrap().kind(), adotenv::ItemKind::Invalid);
assert_eq!(diagnostics[0].code(), adotenv::DiagnosticCode::InvalidKey);
assert_eq!(doc.source(), "BAD KEY=value\nGOOD=retained\n");
Diagnostics have stable codes, severities, one-based lines and primary or secondary spans. Match codes and spans, not message text.
parse_owned(String) moves the source into the document. Document::into_owned
copies only when the document still borrows its input.
When only final values are needed, parse_values parses without building items
or spans. It returns the first error and discards
warnings.
let values = adotenv::parse_values("A=1\nA=2\nBARE\nC=3\n").unwrap();
assert_eq!(values.get("A").map(String::as_str), Some("2"));
assert_eq!(values.get("C").map(String::as_str), Some("3"));
assert_eq!(values.len(), 2);
For lower retained memory, parse_values_compact returns a CompactValues, and
parse_entries_compact returns a CompactEntries that also keeps winning bare
declarations:
let values = adotenv::parse_values_compact("A=1\nB=2\n").unwrap();
assert_eq!(values.get("B"), Some("2"));
let entries = adotenv::parse_entries_compact("A=1\nDEBUG\nEMPTY=\n").unwrap();
assert_eq!(entries.get("A"), Some(Some("1")));
assert_eq!(entries.get("DEBUG"), Some(None));
assert_eq!(entries.get("EMPTY"), Some(Some("")));
Dialects
The default is Dialect::PORTABLE. Other presets are NODE_DOTENV,
PYTHON_DOTENV, COMPOSE and DOCKER_RAW. Presets choose parsing and literal
lookup rules only. None expands references, reads the process environment or
loads files.
use adotenv::{parse_with, Dialect, InlineComments};
let source = "A=a#b\nB=`two words`\n";
let (node, _) = parse_with(source, Dialect::NODE_DOTENV);
assert_eq!(node.get("A"), Some("a"));
assert_eq!(node.get("B"), Some("two words"));
let (raw, _) = node.reparse(Dialect::DOCKER_RAW);
assert_eq!(raw.get("A"), Some("a#b"));
assert_eq!(raw.get("B"), Some("`two words`"));
let custom = Dialect::NODE_DOTENV.with_inline_comments(InlineComments::None);
assert_eq!(parse_with(source, custom).0.get("A"), Some("a#b"));
Each document retains its exact configuration. reparse borrows the same source
and rebuilds items, entries and source maps for another dialect. Snapshot IDs do
not carry across interpretations.
Lookups and raw tokens
Duplicate declarations are retained. get_entry selects the effective
declaration, get_all returns every occurrence and unique rejects ambiguity.
let doc = adotenv::parse_strict("A=1\nA=2\nB=3\n").unwrap();
assert_eq!(doc.get("A"), Some("2"));
assert_eq!(doc.get_all("A").count(), 2);
assert!(doc.unique("A").is_err());
let index = doc.lookup_index();
assert_eq!(index.get("A"), Some("2"));
assert_eq!(index.unique("B").unwrap().value(), Some("3"));
assert_eq!(index.len(), 2);
let winners: Vec<_> = doc
.effective_entries()
.map(|entry| (entry.key(), entry.value()))
.collect();
assert_eq!(winners, [("A", "2"), ("B", "3")]);
Raw tokens remain available:
let source = "export A=\"two words\" # note\n";
let doc = adotenv::parse_strict(source).unwrap();
let entry = doc.unique("A").unwrap();
assert!(entry.exported());
assert_eq!(&source[entry.key_span()], "A");
assert_eq!(entry.raw_value(), Some("\"two words\""));
assert_eq!(entry.value(), Some("two words"));
assert_eq!(entry.inline_comment(), Some("# note"));
assert_eq!(entry.decoded_span_to_raw(0..3).unwrap(), 10..13);
References and resolution
Entry::references reports $VAR, ${VAR:-default} and $(command) candidates
without expanding them. Each reference records spans, quote and escape context,
operators and nested forms.
use adotenv::{parse_strict, ReferenceOperator, ReferenceRules};
let source = "A=${HOST:-localhost}\n";
let doc = parse_strict(source).unwrap();
let reference = &doc.unique("A").unwrap().references()[0];
assert_eq!(&source[reference.span.clone()], "${HOST:-localhost}");
assert_eq!(
reference.operator,
Some(ReferenceOperator::DefaultIfUnsetOrEmpty)
);
assert!(reference.is_eligible(ReferenceRules::COMPOSE));
assert!(!reference.is_eligible(ReferenceRules::PORTABLE));
Resolution uses document bindings plus a caller lookup closure. It never reads the environment, files or commands on its own.
use adotenv::{parse_strict, ExpandOptions, LookupOrder};
let doc = parse_strict("BASE=base\nURL=${BASE}/api\n").unwrap();
let resolved = doc.resolve(|_| None, &ExpandOptions::portable()).unwrap();
assert_eq!(resolved.entries()[1].value.as_deref(), Some("base/api"));
let caller = doc
.resolve(
|key| (key == "BASE").then(|| "external".to_string()),
&ExpandOptions::portable().with_lookup_order(LookupOrder::CallerFirst),
)
.unwrap();
assert_eq!(caller.entries()[1].value.as_deref(), Some("external/api"));
Commands run only through an explicit callback or the opt-in exec feature:
use adotenv::{parse_strict, ExpandOptions};
let doc = parse_strict("A=$(echo hi)\n").unwrap();
let resolved = doc
.resolve_with_commands(
|_| None,
|context| Ok(format!("ran:{}", context.command)),
Some("synthetic.env"),
&ExpandOptions::dotenv_expand(),
)
.unwrap();
assert_eq!(resolved.entries()[0].value.as_deref(), Some("ran:echo hi"));
assert_eq!(resolved.commands().len(), 1);
Format and sort
Document::format changes only the requested layout and verifies the complete
result with the document dialect.
use adotenv::{parse_strict, FormatOptions};
let source = "# app \n\nA=1 \nB = 2 # note \n";
let doc = parse_strict(source).unwrap();
let formatted = doc.format(&FormatOptions::normalize()).unwrap();
assert_eq!(formatted.as_str(), "# app\n\nA = 1\nB = 2 # note\n");
assert!(parse_strict(formatted.as_str()).is_ok());
Document::sort orders declarations inside blank-line-separated groups and
keeps comments and multiline entries intact. When one key references another in
the same group, the two keep their current relative order, so resolved values
do not change. Groups with duplicate or empty keys, invalid or ignored
statements, self-references or reference cycles are left unchanged, as are
groups where a declaration shares its physical line with the next statement.
let doc = adotenv::parse_strict("# header\nC=3\nB=${A}\n# A note\nA=1\n# bottom\n").unwrap();
assert_eq!(
doc.sort().unwrap().as_str(),
"# header\nB=${A}\n# A note\nA=1\nC=3\n# bottom\n"
);
Compare and generate examples
use adotenv::{parse_strict, DifferenceKind};
let left = parse_strict("A=1\nB=\nC=3\n").unwrap();
let right = parse_strict("A=2\nB\nD=4\n").unwrap();
let comparison = left.compare(&right);
let changes: Vec<_> = comparison
.differences()
.iter()
.map(|entry| (entry.key.as_str(), entry.kind))
.collect();
assert_eq!(
changes,
[
("A", DifferenceKind::Value),
("B", DifferenceKind::State),
("C", DifferenceKind::OnlyLeft),
("D", DifferenceKind::OnlyRight),
]
);
Document::example removes assigned values while preserving layout. Invalid
statements, ignored statements and empty-key entries become comments so they
cannot leak values.
let source = "# app\nA=1\nB=\"two\" # note\nBARE\nBAD KEY=secret\n";
assert_eq!(
adotenv::parse(source).0.example(),
"# app\nA=\nB= # note\nBARE\n#\n"
);
Edit a document
Every edit method returns VerifiedEdits. Ranges refer to the original source.
The edits are sorted by start offset and do not overlap. Apply them in reverse
order of the returned slice, from the last edit to the first. Two edits can
start at the same offset, so do not re-sort them by offset.
use adotenv::{parse_strict, Edit, InsertPosition};
let doc = parse_strict("A=one\nA=two\n").unwrap();
let second = doc.get_all("A").nth(1).unwrap();
let verified = doc
.edit(&[
Edit::Set { entry: second.id(), value: "changed" },
Edit::Insert { key: "B", value: None, position: InsertPosition::End },
])
.unwrap();
let (after, _) = adotenv::parse(verified.as_str());
assert_eq!(after.get("A"), Some("changed"));
assert_eq!(after.get_entry("B").unwrap().value(), None);
let mut text = doc.source().to_string();
for edit in verified.edits().iter().rev() {
text.replace_range(edit.range.clone(), &edit.replacement);
}
assert_eq!(text, verified.as_str());
set, remove, rename, rename_with_references, insert, comment,
uncomment, set_export and edit verify the whole batch and reject changes
that alter unrelated syntax.
Pass EditOptions to edit_with_options, set_with_options,
remove_with_options, insert_with_options, rename_with_options,
rename_with_references_with_options, comment_with_options,
uncomment_with_options, set_export_with_options, format_with_options or
sort_with_options to bound output bytes, output line counts, scanned
references (max_references) and verification parsing.
Use encode_value_with(value, dialect) when you need a standalone literal token:
use adotenv::{encode_value_with, parse_strict_with, Dialect};
let value = "literal #\0\n";
let token = encode_value_with(value, Dialect::PYTHON_DOTENV).unwrap();
let source = format!("A={token}\n");
assert_eq!(
parse_strict_with(&source, Dialect::PYTHON_DOTENV).unwrap().get("A"),
Some(value)
);
assert!(encode_value_with("two\nlines", Dialect::DOCKER_RAW).is_err());
Positions
Line and column conversions are explicit and checked.
use adotenv::{parse_strict, ColumnEncoding, Position};
let doc = parse_strict("A=é\n").unwrap();
let index = doc.line_index();
let position = index.to_position(2, ColumnEncoding::Scalar).unwrap();
assert_eq!(position, Position { line: 0, column: 2 });
assert_eq!(
index.to_offset(position, ColumnEncoding::Scalar).unwrap(),
2
);
ColumnEncoding supports UTF-8 bytes, Unicode scalars and UTF-16 code units.
Out-of-range positions and split surrogates return an error instead of being
clamped. Entry and diagnostic lines are one-based; Position is zero-based.
A leading byte-order mark counts in line 1 columns by default; chain
without_bom() or with_bom_policy(policy) on the index when the consumer
hides leading marks.
Load files
Enable the load feature to read a cascade from an explicit directory. The order
is .env, .env.local, .env.{mode} and .env.{mode}.local. A later file's
effective value replaces an earlier one, key by key. Missing cascade files are
skipped. A file that cannot be read, is not valid UTF-8 or has an error-severity
diagnostic fails the whole load.
use adotenv::load::load_cascade;
let loaded = load_cascade("/srv/my-app", "production")?;
assert_eq!(loaded.get("PORT"), Some("8080"));
let origin = loaded.origin("PORT").unwrap();
println!("{}:{}", origin.path().display(), origin.line());
The default loader keeps values, their origins and the raw source text of each winning declaration. Reports are opt-in:
use adotenv::load::{load_cascade_with_options, LoadOptions};
let loaded = load_cascade_with_options(
"/srv/my-app",
"production",
LoadOptions::full(adotenv::Dialect::PORTABLE),
)?;
for entry in loaded.entries() {
println!(
"{}={} at {}:{}",
entry.key(),
entry.value(),
entry.origin().path().display(),
entry.origin().line()
);
}
LoadOptions::new(dialect) is the default profile. Builders turn the raw source
text, origins and reports on or off, and LoadOptions::full keeps the reports.
load_values, load_cascade_values and their *_values_compact* /
*_entries_compact* variants keep only the final strings or bare-preserving
compact entries.
LoadedEnvironment::resolve_contextual resolves merged values with their original
quote and escape context. resolve_decoded treats final values as unquoted text.
Process environment
adotenv-process applies a loaded environment to the current process. The API
is unsafe because the process environment is global and not thread-safe on all
platforms. Validation happens before the first mutation.
use adotenv::load::load_cascade;
use adotenv_process::apply;
let loaded = load_cascade("/srv/my-app", "production")?;
// The caller must guarantee no concurrent environment access.
unsafe { apply(&loaded)? };
validate runs the same checks without changing anything,
validate_compact / apply_compact accept CompactValues, and
validate_compact_entries / apply_compact_entries accept CompactEntries
(skipping bare None declarations). Prefer passing
LoadedEnvironment::values() to a child process or reading them directly when
mutation is not required.
Serde
With the serde feature, documents and loaded environments deserialize into
typed values:
use serde::Deserialize;
#[derive(Deserialize)]
struct Config {
host: String,
port: u16,
}
let doc = adotenv::parse_strict("host=localhost\nport=8080\n").unwrap();
let config: Config = doc.deserialize()?;
Strings, booleans, numbers, characters, options and unit or newtype shapes are
converted from literal values, and map targets also parse non-string scalar
keys (such as BTreeMap<u16, String> or BTreeMap<bool, String>) with the
same rules. Sequences, tuples, nested structs and maps, and enums are rejected.
Value-conversion errors carry the source line and key, and their messages
include the value.
CLI
cargo install adotenv-cli --locked installs the adotenv-cli binary:
adotenv-cli [--dialect <portable|node|python|compose|docker>]
[--max-input-bytes <n>] [--max-lines <n>]
[--max-items <n>] [--max-diagnostics <n>] <command> [options]
get <file> <key>
check [--format human|json|github] [--json] [--source] [-r|--recursive] [--exclude <path>] <path>...
fmt [--write|--check] [--sort] [--max-output-bytes <n>] [--max-output-lines <n>] [--max-references <n>] [-r|--recursive] [--exclude <path>] <path>...
diff [--format human|matrix|json] [--json] [--mask] <baseline> <file>...
example <file>
load <directory> [mode]
set [--max-output-bytes <n>] [--max-output-lines <n>] <file> <key> <value>
run <directory> [mode] -- <program> [args...]
check --format json and diff --format json use versioned machine schemas.
check --format github emits workflow annotations. Human output omits source
lines unless --source is passed.
run starts a child with the parent environment plus the loaded values, which
replace parent variables of the same name. Loaded files are trusted like code: a
loaded PATH changes which program runs. The parent process is not changed.
get, load and diff print values by default; diff --mask replaces
compared values with ***. fmt prints whole documents, and example keeps
comments verbatim. load prints Portable lines that parse back to the same
values.
See the command-line tool guide.
Linter
adotenv-lint is an optional companion crate for project policy. It returns
structured findings and applies fixes through the verified edit and format
APIs; lint policy stays out of the parser.
use adotenv_lint::{lint, LintOptions};
let doc = adotenv::parse_strict("B=2\nA=1\n")?;
let findings = lint(&doc, LintOptions::default().with_key_order(true));
let fixed = adotenv_lint::apply_fix(&doc, findings[0].fix().unwrap())?;
assert_eq!(fixed.as_str(), "A=1\nB=2\n");
The default rule reports duplicate keys. Key order, key case, quote style and whitespace are opt-in.
Language server
adotenv-lsp provides diagnostics (including opt-in [schema] / .env.example
checks and deprecation tags), schema-enriched completion and hover, definition,
references, document and workspace symbols, prepareRename, verified key
rename, formatting, lint-backed quick fixes and style-only source.fixAll,
dialect-accurate semanticTokens/full, foldingRange, and bounded live config
reload, both as a transport-free library and as a bounded stdio server. It
reads only the text an editor sends (plus explicitly configured or opted-in
discovered .adotenv-lint.toml and [schema] example files when --config or
--discover-lint-config is passed), does not resolve references or inspect the
process environment, and supports opt-in hover value masking.
adotenv-lsp
adotenv-lsp --mask-values
See the language server guide.
Adapters
adotenv-config exposes literal values as a config source. adotenv-figment
exposes a Figment dictionary. Both accept Document, CompactValues,
CompactEntries, explicit maps, and (with their load feature)
LoadedEnvironment.
use adotenv::parse_strict;
use adotenv_config::AdotenvSource;
let doc = parse_strict("host=localhost\nport=8080\n").unwrap();
let config = config::Config::builder()
.add_source(AdotenvSource::from_document(&doc))
.build()?;
Design limits
- Input is UTF-8. Decode bytes before parsing; invalid UTF-8 is rejected rather than replaced.
- Parsing does not read files, environment variables or commands.
- Retained documents keep token and item metadata. Use
ParseOptionsto bound input bytes, physical lines, items and diagnostics for untrusted input, andEditOptionsto bound edited output bytes, output lines, scanned references (max_references) and verification parsing; the limits are opt-in. The loader'sLoadOptions::with_limitsalso bounds the read itself. Debugoutput of documents, items, entries, edit and format results, comparisons, loaded environments and entries, resolved values, lookup indexes, effective entries, compact values, compact entries, line indexes, groups and portability reports includes values. The core document, edit, comparison, load, resolution, compact-values, compact-entries, line-index, group and portability types support a value-redactingDebugform throughadotenv::Maskedandadotenv::mask; useDeserializeError::masked()for serde errors. Adapter types still include values. Do not log normalDebugoutput when values are secret.- Windows writes use a direct replace when possible and a backup swap otherwise. The fallback is not crash-atomic.
- The
configintegration usesconfig0.15 and requires Rust 1.88.
Rust version
Rust 1.81, edition 2021 across adotenv, adotenv-process, adotenv-cli,
adotenv-lint, adotenv-lsp and adotenv-figment. adotenv-config requires
Rust 1.88 because config 0.15 does. Development and fuzz dependencies may
require a newer toolchain.
License
Licensed under either Apache License, Version 2.0 or MIT license, at your option.