Expand description
Literal, lossless .env parsing and verified editing.
adotenv reads .env files the way tools need them. It keeps every byte of the source,
leaves values literal (${HOME} is text, not an expansion), gives every token a byte span
and checks every edit by parsing the result again before returning it. It is built for
linters, formatters, editors, scanners and other tools that maintain configuration files.
The core never reads files or environment variables, never expands references and never runs commands. Each of those happens only through an explicit API or an optional feature.
The user guide explains the behavior in more depth. This reference documents each item.
§Quick start
let source = "# app\nexport PORT=8080\nURL=\"${HOST}/api\" # base\n";
let doc = adotenv::parse_strict(source)?;
// Values are literal: references are not expanded.
assert_eq!(doc.get("PORT"), Some("8080"));
assert_eq!(doc.get("URL"), Some("${HOST}/api"));
// A document prints back the exact source.
assert_eq!(doc.to_string(), source);
// An edit returns the new text, already parsed again and checked.
let edited = doc.set("PORT", "9090")?;
assert_eq!(edited.as_str(), "# app\nexport PORT=9090\nURL=\"${HOST}/api\" # base\n");parse_strict returns the first error instead of a document. parse never fails: it
returns a document and a list of Diagnostics, so tools can inspect and report on a broken
file without losing any of it.
use adotenv::{DiagnosticCode, ItemKind};
let (doc, diagnostics) = adotenv::parse("BAD KEY=value\nGOOD=kept\n");
assert_eq!(doc.get("GOOD"), Some("kept"));
assert_eq!(doc.items().next().unwrap().kind(), ItemKind::Invalid);
assert_eq!(diagnostics[0].code(), DiagnosticCode::InvalidKey);
assert_eq!(diagnostics[0].line(), 1);§Where to start
§Features
| Feature | Default | Adds |
|---|---|---|
std | yes | Standard library support. Required by load and exec. |
load | no | The load module, which reads .env cascades and file lists from disk. |
serde | no | Document::deserialize and DeserializeError; with load also load::LoadedEnvironment::deserialize. |
exec | no | The exec module, which runs command substitutions through the platform shell. |
Without default features the crate is no_std and uses alloc:
adotenv = { version = "1", default-features = false }The only dependency is serde, and only with the serde feature. The crate forbids unsafe
code with every feature combination and supports Rust 1.81 and later.
§Dialects
Every parse uses a Dialect: the syntax and literal lookup rules of one .env reader.
The functions without a suffix use Dialect::PORTABLE. The other presets follow Node
dotenv, python-dotenv, Docker Compose and Docker --env-file, and a custom dialect starts
from a preset and changes single rules. No dialect expands references, reads the process
environment or loads files.
use adotenv::{parse_with, Dialect};
let (doc, _) = parse_with("A=a#b\n", Dialect::NODE_DOTENV);
assert_eq!(doc.get("A"), Some("a"));
assert_eq!(doc.reparse(Dialect::DOCKER_RAW).0.get("A"), Some("a#b"));§Source, spans and positions
A Document borrows its source, or owns it after parse_owned or
Document::into_owned. Its items cover the whole source without gaps, malformed
statements included; only a leading byte-order mark that the dialect strips belongs to no
item. Every span is a byte range into the original text, byte-order mark included.
Entry::line and Diagnostic::line are one-based. LineIndex converts between byte
offsets and zero-based lines and columns in UTF-8 bytes, Unicode scalar values or UTF-16
code units, and Position::one_based converts a position for display. Lines and line
numbers count LF, CRLF and a lone CR as line ends, whatever the dialect.
§Verified edits
Methods such as Document::set select the only declaration of a key. A batch of
Edits selects entries and items by id, so it can also change one of several
declarations of a key. Every edit and every batch is applied to the whole source, parsed
again with the same dialect and checked: the requested change happened and nothing else
changed meaning. VerifiedEdits then gives the new text and the source-relative
TextEdits, for example to send to an editor. Document::format and
Document::sort are verified the same way.
§References and resolution
Values stay literal. Entry::references lists $VAR, ${VAR:-default} and
$(command) forms with their spans without resolving anything. Document::resolve
substitutes references only on request, from a lookup closure you pass, with explicit
scope, precedence and size limits. Commands run only through a callback you pass to
Document::resolve_with_commands.
§Secrets
Values may be secrets. Debug output 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 include them, and so
do the messages of serde conversion errors. The core document, edit, comparison, compact
value/entry, load, resolution, line-index, group and portability types support a
structure-preserving Debug form that replaces values with <redacted> through Masked
and mask; use DeserializeError::masked for serde errors. Adapter types still include values. Do not
log normal Debug output where values are secret. Document::example removes assigned
values but keeps comments verbatim, including any secret written in a comment.
§Related crates
adotenv-processapplies a loaded environment to the current process.adotenv-configandadotenv-figmentprovide values toconfigand Figment.adotenv-clichecks, formats, compares and loads files from a shell.
§Stability
The public API follows semantic versioning. Enums and option structs are
#[non_exhaustive], so a minor release can add variants, fields and builders.
Modules§
- exec
exec - A command callback that runs
$(command)forms through the system shell. - load
load - Reads
.envfiles from disk and merges them into one set of values.
Structs§
- Command
Call - A record of one command callback call made during resolution.
- Command
Context - The details of one
$(command)form, passed to a command callback. - Command
Error - An error that a command callback returns to stop resolution.
- Compact
Entries - A compact, sorted map of winning
.enventries that preserves bare declarations. - Compact
Values - A compact, sorted map of effective
.envvalues. - Compared
Value - The state, value and
exportprefix of one side’s effective declaration. - Comparison
- The keys whose effective declarations differ between two documents.
- Comparison
Entry - One key whose effective declarations differ, with both sides.
- Deserialize
Error serde - An error from deserializing a
Documentor loaded environment with Serde. - Diagnostic
- A problem or note that parsing reports about the source, with its location.
- Dialect
- The complete set of rules for reading a
.envfile and looking up its values. - Document
- A parsed
.envdocument that keeps every byte of its source. - Double
Escapes - The set of escape sequences that double-quoted values decode.
- Edit
Options - Optional bounds for verified edits.
- Effective
Entry - The declaration that wins lookup for a key, with its effective value.
- Entry
- A declaration in a
Document: aKEY=valueor bareKEYitem. - Entry
Tokens - The byte ranges of each part of a declaration’s source text.
- Expand
Options - Options for
Document::resolve: eligible references, scope, lookup order and limits. - Format
Options - The layout changes that
Document::formatmakes. - Format
Result - The verified output of
Document::formatorDocument::sort, with the text edits that produce it. - Group
- A run of items between blank lines.
- Groups
- An iterator over the
Groups of a document, in source order. - Item
- One piece of a
Document’s source: an entry, comment, blank line, or invalid or ignored statement. - Limit
Exceeded - A configured limit and the value that exceeded it.
- Line
Index - Converts between byte offsets and zero-based line and column positions.
- Lookup
Index - A prebuilt key lookup table for one
Document. - Masked
- A wrapper whose
Debugoutput masks values. - Masked
Deserialize Error serde - A
DeserializeErrorwith its value-bearing message masked. - Multiline
- Which quote styles may contain line breaks.
- Parse
Options - Optional bounds for parsing untrusted input.
- Portability
Declaration - A declaration as one dialect reads it, inside a
PortabilityReading. - Portability
Difference - A physical line that the compared dialects read differently.
- Portability
Reading - How one dialect reads one differing physical line.
- Portability
Report - The lines of a document that several dialects read differently.
- Position
- A zero-based line and column in the source.
- Reference
- A
$reference candidate found in an entry’s value. - Reference
Rules - Rules that decide which reference candidates could expand.
- Resolve
Failure - A failed
Document::resolve_with_commands, with the command calls made before the failure. - Resolved
Document - The result of resolution: every entry’s resolved value, in source order.
- Resolved
Entry - One entry’s resolved value, with a record of where each part came from.
- Resolved
Segment - One part of a resolved value: its text and where the text came from.
- Text
Edit - A replacement of one byte range of the original source.
- Verified
Edits - The verified result of an edit: the complete output text and the text edits that produce it.
Enums§
- Assignment
State - Whether a declaration is bare, empty or has a value.
- Bare
Keys - How lookup treats a bare key: a declaration such as
DEBUGwith no=. - Blank
Lines - What
Document::formatdoes with runs of blank lines. - BomPolicy
- What happens to a UTF-8 byte-order mark (U+FEFF) at the start of the source.
- Colon
Separator - Whether a colon can separate a key from its value, as in
KEY: value. - Column
Encoding - The unit that a
Positioncolumn counts. - Command
Outcome - What one command callback call returned.
- Diagnostic
Code - The kind of a
Diagnostic, as a stable identifier. - Difference
Kind - The kind of difference that
Document::comparefound for one key. - Duplicates
- Which declaration wins when a key is declared more than once.
- Edit
- One operation of a
Document::editbatch. - Edit
Error - The reason an edit was refused.
- Encode
Error - The error returned when a value has no exact spelling in a dialect.
- Equals
Spacing - The spacing that
Document::formatputs around assignment separators. - Expand
Scope - Which declarations in the file a reference can see during resolution.
- Final
Newline - What
Document::formatdoes with the line ending at the end of the file. - Format
Error - The reason
Document::formatorDocument::sortrefused to return a result. - Inline
Comments - Where a
#inside a line starts a comment. - Insert
Position - Where
Edit::InsertandDocument::insertplace a new declaration. - Item
Kind - What kind of source text an
Itemholds. - KeySyntax
- Which characters an unquoted key may contain.
- Limit
Kind - Which configured parse, load or edit limit was exceeded.
- Line
Breaks - Which characters end a physical line.
- Line
Ending - A line ending as written in the source.
- Lookup
Order - Whether the file or the lookup closure supplies a variable’s value first.
- Malformed
Lines - What happens to a statement that cannot be read.
- Operator
Set - Which variable forms
ReferenceRulesaccept. - Portability
Part - One item, or the part of one, on a physical line as one dialect reads it.
- Position
Error - Why a byte offset or position cannot be converted.
- Quote
- The quote style of a value as written in the source.
- Quote
Style - The quoting that
Document::formatprefers for values. - Quoted
Tail - What happens to text after a closing quote, as in
A="x"y. - Reference
Kind - Whether a reference candidate is a variable or a command.
- Reference
Operator - The operator of a braced variable, such as
:-in${VAR:-default}. - Resolve
Error - An error from
Document::resolveorDocument::resolve_with_commands. - Resolved
Segment Kind - Where the text of one
ResolvedSegmentcame from. - Severity
- How serious a
Diagnosticis. - Single
Escapes - The escape sequences that single-quoted values decode.
- Syntax
- The statement grammar: how a line splits into key, separator and value.
- Unknown
Escapes - What a double-quoted value does with a backslash pair it does not decode.
- Unresolved
- What happens to a plain reference whose variable has no value.
- Value
Origin - Where a substituted variable value came from.
- Whitespace
- Which characters count as whitespace around keys, separators, values and comments.
Constants§
- REDACTED
- The replacement text used for a masked value.
Traits§
Functions§
- encode_
value - Returns a Portable token that reads back as
value, quoting conservatively. - encode_
value_ with - Returns a token that reads back as exactly
valueindialect. - mask
- Wraps
valueso itsDebugoutput masks values. - parse
- Parses
.envtext with the Portable dialect, recovering from errors. - parse_
entries_ compact - Parses
.envtext with the Portable dialect into compact winning entries, preserving bare declarations. - parse_
entries_ compact_ with - Parses
.envtext with the given dialect into compact winning entries, preserving bare declarations when the dialect keeps them in lookup. - parse_
entries_ compact_ with_ options - Parses
.envtext into compact winning entries with opt-in limits. - parse_
owned - Parses an owned
Stringwith the Portable dialect, recovering from errors. - parse_
owned_ with - Parses an owned
Stringwith the given dialect, recovering from errors. - parse_
owned_ with_ options - Parses an owned
Stringwith opt-in limits. - parse_
strict - Parses
.envtext with the Portable dialect, failing on the first error. - parse_
strict_ with - Parses
.envtext with the given dialect, failing on the first error. - parse_
strict_ with_ options - Parses
.envtext with the given dialect and opt-in limits, failing on the first error or limit. - parse_
values - Parses
.envtext with the Portable dialect into a map of effective values. - parse_
values_ compact - Parses
.envtext with the Portable dialect into compact effective values. - parse_
values_ compact_ with - Parses
.envtext with the given dialect into compact effective values. - parse_
values_ compact_ with_ options - Parses
.envtext into compact effective values with opt-in limits. - parse_
values_ with - Parses
.envtext with the given dialect into a map of effective values. - parse_
values_ with_ options - Parses
.envtext into a map of effective values with opt-in limits. - parse_
with - Parses
.envtext with the given dialect, recovering from errors. - parse_
with_ options - Parses
.envtext with the given dialect and opt-in limits, recovering from errors. - remove
- Removes the only declaration of
keyfromtext, keeping the comments around it. - set
- Sets the literal value of the only declaration of
keyintext.