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
.envcascades.
Structs§
- Command
Call - Provenance for one invoked command callback.
- Command
Context - Structured input passed to a command-substitution callback.
- Command
Error - An error returned by a command-substitution callback.
- Compared
Value - The effective value side of one compared key.
- Comparison
- Changed keys between two documents in stable key order.
- Comparison
Entry - One changed key and its effective values on both sides.
- Deserialize
Error - 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.
- Double
Escapes - Independently enabled double-quoted escape sequences.
- Effective
Entry - One effective declaration and its effective literal value.
- Entry
- A borrowed view of a declaration; identities belong to this document snapshot.
- Entry
Tokens - Raw token ranges into a document’s source; absent syntax is represented by
None. - Expand
Options - Explicit resolution policy and resource limits.
- Format
Options - Formatting policy for trivia-only changes.
- Format
Result - 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.
- Line
Index - A physical-line index borrowing its original source text.
- Lookup
Index - A borrowed lookup index over one document snapshot.
- Multiline
- Independently enabled multiline quote forms.
- Portability
Declaration - A declaration as read by one dialect on a physical line.
- Portability
Difference - One physical line whose meaning differs across the compared dialects.
- Portability
Reading - One dialect’s reading of a differing physical line.
- Portability
Report - 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.
- Reference
Container - A containing variable-operator or command form for a nested candidate.
- Reference
Rules - Caller-selected rules for deciding whether a raw candidate could expand.
- Resolve
Failure - A resolution failure that retains command calls already made.
- Resolved
Document - All resolved entries in source order.
- Resolved
Entry - One entry’s resolved value and provenance.
- Resolved
Segment - One resolved value part.
- Text
Edit - A native byte-range replacement against the original document snapshot.
- Verified
Edits - An edit batch whose complete output has already been parsed and verified.
Enums§
- Assignment
State - A declaration’s assignment state, independent of any environment lookup.
- Bare
Keys - Effective treatment of declarations with no assignment separator.
- Blank
Lines - Blank-line grouping policy.
- BomPolicy
- Treatment of an initial UTF-8 byte-order mark.
- Colon
Separator - Colon assignment separators.
- Column
Encoding - The unit used for a zero-based source column.
- Command
Outcome - Recorded outcome of one invoked command callback.
- Diagnostic
Code - Stable diagnostic identities; messages are descriptive, not API identifiers.
- Difference
Kind - 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.
- Edit
Error - Why a native edit could not be produced safely.
- Encode
Error - A value has no exact literal spelling in the selected grammar and context.
- Equals
Spacing - Preferred spacing around assignment separators.
- Expand
Scope - Whether later definitions can see earlier definitions or the final file.
- Final
Newline - Final-newline policy.
- Format
Error - A formatting request that could not be verified.
- Inline
Comments - Recognition of inline comments (whole-statement comments are always enabled).
- Insert
Position - A position for a new declaration in the original snapshot.
- Item
Kind - The kind of a lossless source item.
- KeySyntax
- Validation of unquoted key bodies.
- Line
Breaks - Physical line recognition.
- Line
Ending - A physical source line ending, retained exactly.
- Lookup
Order - Whether the caller lookup or the document’s own bindings win.
- Malformed
Lines - Handling of malformed statements, excluding explicit policy violations.
- Operator
Set - Variable-reference forms and operators eligible under one expansion policy.
- Portability
Part - One part of a physical line under one dialect.
- Position
Error - A source position that cannot be represented in the requested encoding.
- Quote
- Quoting used by a literal value in the source.
- Quote
Style - Preferred value quoting while formatting.
- Quoted
Tail - Handling of noncomment text following a closing quote.
- Reference
Kind - The kind of a raw reference candidate.
- Reference
Operator - A recognized variable-reference operator.
- Resolve
Error - A resolution failure.
- Resolved
Segment Kind - The role of one resolved segment.
- Severity
- The importance of a parsing diagnostic.
- Single
Escapes - Escapes recognized inside single quotes.
- Syntax
- The statement grammar used to recognize bindings.
- Unknown
Escapes - Handling of unrecognized double-quoted escapes.
- Unresolved
- Treatment of an eligible reference with no value from the lookup order.
- Value
Origin - 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.