Skip to main content

Crate adotenv

Crate adotenv 

Source
Expand description

Lossless, literal .env dialect parsing and verified native text edits.

Parsing borrows UTF-8 source and retains every byte, including malformed statements. It never reads files, consults the environment, or expands values.

use adotenv::{parse, parse_owned, parse_strict, Severity};

let text = "# app\nexport PORT=8080\nURL=\"${HOST}/api\" # base\n";
let (doc, diagnostics) = parse(text);
assert!(!diagnostics.iter().any(|d| d.severity() == Severity::Error));
assert_eq!(doc.get("PORT"), Some("8080"));
assert_eq!(doc.get("URL"), Some("${HOST}/api"));
let edits = doc.set("PORT", "9090")?;
assert_eq!(edits.edits()[0].replacement, "9090");
assert_eq!(parse_strict(edits.as_str())?.get("PORT"), Some("9090"));
let (owned, _) = parse_owned(String::from("KEY='value'\n"));
assert_eq!(owned.get("KEY"), Some("value"));

§Explicit dialects

parse, parse_owned and parse_strict retain Portable defaults. Their _with variants accept a Dialect; Document::reparse borrows retained source and rebuilds its interpretation. Presets never enable interpolation, inheritance, file loading or ambient environment access.

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.dialect(), Dialect::NODE_DOTENV);
assert_eq!(doc.reparse(Dialect::DOCKER_RAW).0.get("A"), Some("a#b"));

Document::portability reparses the retained source once per unique configuration, includes the document’s own reading first, and reports every physical line whose declarations, values, states, export prefixes, lookup participation or item grouping differ.

Entry::references reports raw $VAR, ${VAR:-default} and $(command) candidates with original-source spans and quote/escape context. It never resolves a lookup or executes a command; Reference::is_eligible applies explicit caller-selected rules.

Document::resolve performs opt-in variable substitution with a caller lookup closure. Sequential or whole-file scope, precedence, unresolved policy, operators, cycles and resource limits are explicit. Command forms stay literal unless Document::resolve_with_commands receives an explicit callback; callback calls are provenance-recorded and never run by default.

§Structure and formatting

Document::groups exposes blank-line-separated item runs, and Document::header exposes the structural prefix before the first entry. Entry::leading_comments attaches only contiguous whole-line comments; a blank line breaks attachment. These are views over the selected dialect’s lossless items and do not move or reinterpret source.

Document::format applies explicit trivia-only FormatOptions and reparses the complete output with the exact selected dialect. It returns source-relative TextEdit values plus verified text. BlankLines can collapse group separators and QuoteStyle can prefer a quote style when the exact decoded value survives. Raw values, multiline bodies, invalid/ignored statements, empty assigned values and ambiguous mixed line endings are left untouched. Document::sort reorders groups with attached comments and reference dependencies, then verifies the result.

Document::compare reports effective-key differences, distinguishing missing keys, bare/empty/assigned states, decoded values and exports. Document::example removes assigned values while retaining comments and layout, and comments out malformed or ignored statements so their text cannot leak a value.

§Loading

The opt-in std-only load feature provides load::load_cascade and load::load_files. They strictly read and validate every participating file before returning load::LoadedEnvironment, which carries final values, origins, overrides, repeats and skipped declarations. The full loader can use load::LoadOptions to drop raw winning tokens or reports while keeping values and origins; resolve_contextual requires raw tokens, while resolve_decoded remains available. Single-source context-aware resolution remains Document::resolve. Loading performs no expansion or process-environment mutation by itself.

The opt-in serde feature adds Document::deserialize, mapping effective literal declarations into a Serde type with line/key-aware conversion errors. With load enabled as well, LoadedEnvironment::deserialize maps the final merged cascade into the same Serde types and preserves origin lines.

§Source and positions

Ranges always address the original source, BOM included. Item ranges plus the optional BOM partition it without gaps. A LineIndex offers checked zero-based byte, scalar and UTF-16 coordinates. One-based display conversion is explicit; scalar columns are not terminal-cell widths.

§Editing and recovery

Key-only helpers require unique declarations. Edit selects explicit occurrences and comments from one source snapshot. Every complete batch is reparsed and checked before VerifiedEdits exposes its output or native edits. Unrelated malformed statements may remain, but must not change their interpretation. Verification uses the exact selected dialect; values or contexts its grammar cannot represent are rejected. External appliers check versions.

§Platform

Zero runtime dependencies. Disable default features for no_std with alloc. Unsafe code is forbidden regardless of features. Reference resolution and process-environment mutation are not part of literal parsing; filesystem loading is available only through the opt-in load feature.

Modules§

exec
Opt-in system-shell command callback for trusted files.
load
Opt-in filesystem loading of .env cascades.

Structs§

CommandCall
Provenance for one invoked command callback.
CommandContext
Structured input passed to a command-substitution callback.
CommandError
An error returned by a command-substitution callback.
ComparedValue
The effective value side of one compared key.
Comparison
Changed keys between two documents in stable key order.
ComparisonEntry
One changed key and its effective values on both sides.
DeserializeError
A serde error tied to the literal document line where possible.
Diagnostic
A source-relative diagnostic. Its primary span always addresses original bytes.
Dialect
Complete, explicit literal parsing and lookup configuration.
Document
A lossless document interpreted under one explicit literal syntax configuration.
DoubleEscapes
Independently enabled double-quoted escape sequences.
EffectiveEntry
One effective declaration and its effective literal value.
Entry
A borrowed view of a declaration; identities belong to this document snapshot.
EntryTokens
Raw token ranges into a document’s source; absent syntax is represented by None.
ExpandOptions
Explicit resolution policy and resource limits.
FormatOptions
Formatting policy for trivia-only changes.
FormatResult
A verified trivia-only formatting result.
Group
A contiguous run of nonblank items, separated by blank lines.
Groups
Blank-line-separated groups in source order.
Item
A borrowed view of a raw source item.
LineIndex
A physical-line index borrowing its original source text.
LookupIndex
A borrowed lookup index over one document snapshot.
Multiline
Independently enabled multiline quote forms.
PortabilityDeclaration
A declaration as read by one dialect on a physical line.
PortabilityDifference
One physical line whose meaning differs across the compared dialects.
PortabilityReading
One dialect’s reading of a differing physical line.
PortabilityReport
Differences between a document’s interpretation and selected dialects.
Position
A zero-based physical source line and column.
Reference
A raw reference candidate in an entry’s literal value.
ReferenceContainer
A containing variable-operator or command form for a nested candidate.
ReferenceRules
Caller-selected rules for deciding whether a raw candidate could expand.
ResolveFailure
A resolution failure that retains command calls already made.
ResolvedDocument
All resolved entries in source order.
ResolvedEntry
One entry’s resolved value and provenance.
ResolvedSegment
One resolved value part.
TextEdit
A native byte-range replacement against the original document snapshot.
VerifiedEdits
An edit batch whose complete output has already been parsed and verified.

Enums§

AssignmentState
A declaration’s assignment state, independent of any environment lookup.
BareKeys
Effective treatment of declarations with no assignment separator.
BlankLines
Blank-line grouping policy.
BomPolicy
Treatment of an initial UTF-8 byte-order mark.
ColonSeparator
Colon assignment separators.
ColumnEncoding
The unit used for a zero-based source column.
CommandOutcome
Recorded outcome of one invoked command callback.
DiagnosticCode
Stable diagnostic identities; messages are descriptive, not API identifiers.
DifferenceKind
Why a key appears in a Comparison.
Duplicates
Which participating duplicate declaration wins lookup.
Edit
An operation whose identities refer to the original document snapshot.
EditError
Why a native edit could not be produced safely.
EncodeError
A value has no exact literal spelling in the selected grammar and context.
EqualsSpacing
Preferred spacing around assignment separators.
ExpandScope
Whether later definitions can see earlier definitions or the final file.
FinalNewline
Final-newline policy.
FormatError
A formatting request that could not be verified.
InlineComments
Recognition of inline comments (whole-statement comments are always enabled).
InsertPosition
A position for a new declaration in the original snapshot.
ItemKind
The kind of a lossless source item.
KeySyntax
Validation of unquoted key bodies.
LineBreaks
Physical line recognition.
LineEnding
A physical source line ending, retained exactly.
LookupOrder
Whether the caller lookup or the document’s own bindings win.
MalformedLines
Handling of malformed statements, excluding explicit policy violations.
OperatorSet
Variable-reference forms and operators eligible under one expansion policy.
PortabilityPart
One part of a physical line under one dialect.
PositionError
A source position that cannot be represented in the requested encoding.
Quote
Quoting used by a literal value in the source.
QuoteStyle
Preferred value quoting while formatting.
QuotedTail
Handling of noncomment text following a closing quote.
ReferenceKind
The kind of a raw reference candidate.
ReferenceOperator
A recognized variable-reference operator.
ResolveError
A resolution failure.
ResolvedSegmentKind
The role of one resolved segment.
Severity
The importance of a parsing diagnostic.
SingleEscapes
Escapes recognized inside single quotes.
Syntax
The statement grammar used to recognize bindings.
UnknownEscapes
Handling of unrecognized double-quoted escapes.
Unresolved
Treatment of an eligible reference with no value from the lookup order.
ValueOrigin
Where one resolved variable value came from.
Whitespace
Whitespace classification used by syntax policies.

Functions§

encode_value
Encode a standalone Portable value, retaining the original control policy.
encode_value_with
Encode an exact standalone value under an explicit literal dialect.
parse
Parse Portable syntax, retaining the complete source and ordered diagnostics.
parse_owned
Consume owned UTF-8 source without copying the source bytes.
parse_owned_with
Consume owned source using the selected literal configuration.
parse_strict
Parse Portable syntax, returning the first error in source order.
parse_strict_with
Parse with an explicit configuration, returning the first error in source order.
parse_with
Parse literal bindings under an explicit configuration, without expansion or I/O.
remove
Remove a unique key in recovering input, without deleting adjacent comments.
set
Set a unique key in recovering input, verifying that unrelated items survive.