Skip to main content

Crate adotenv

Crate adotenv 

Source
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

TaskStart with
Parse textparse, parse_strict, parse_owned, parse_values, parse_values_compact, parse_entries_compact, and their _with variants that take a Dialect
Look up valuesDocument::get, Document::get_entry, Document::get_all, Document::effective_entries, Document::lookup_index
Walk the sourceDocument::items, Document::entries, Item, Entry, EntryTokens
Report problemsDiagnostic, DiagnosticCode, Severity
Bound untrusted inputParseOptions, EditOptions, LimitExceeded, LimitKind
Choose reading rulesDialect and its presets
EditDocument::set, Document::remove, Document::rename, Document::rename_with_references, Document::rename_with_references_with_options, Document::insert, Document::comment, Document::uncomment, Document::set_export, Document::edit, or Document::edit_with_options with a batch of Edits
Set or remove one key of Portable text in one callset, remove
Quote a value for a fileencode_value, encode_value_with
Format and sortDocument::format with FormatOptions, Document::sort
Compare two filesDocument::compare
Write an example fileDocument::example
Check portability across dialectsDocument::portability
Groups and commentsDocument::groups, Document::header, Entry::leading_comments
Lines and columnsDocument::line_index, LineIndex, Position, ColumnEncoding
Find $VAR referencesEntry::references, ReferenceRules
Resolve referencesDocument::resolve with ExpandOptions
Load files from diskthe load module
Deserialize into a structDocument::deserialize
Run command substitutionsDocument::resolve_with_commands and the exec module

§Features

FeatureDefaultAdds
stdyesStandard library support. Required by load and exec.
loadnoThe load module, which reads .env cascades and file lists from disk.
serdenoDocument::deserialize and DeserializeError; with load also load::LoadedEnvironment::deserialize.
execnoThe 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.

§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§

execexec
A command callback that runs $(command) forms through the system shell.
loadload
Reads .env files from disk and merges them into one set of values.

Structs§

CommandCall
A record of one command callback call made during resolution.
CommandContext
The details of one $(command) form, passed to a command callback.
CommandError
An error that a command callback returns to stop resolution.
CompactEntries
A compact, sorted map of winning .env entries that preserves bare declarations.
CompactValues
A compact, sorted map of effective .env values.
ComparedValue
The state, value and export prefix of one side’s effective declaration.
Comparison
The keys whose effective declarations differ between two documents.
ComparisonEntry
One key whose effective declarations differ, with both sides.
DeserializeErrorserde
An error from deserializing a Document or 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 .env file and looking up its values.
Document
A parsed .env document that keeps every byte of its source.
DoubleEscapes
The set of escape sequences that double-quoted values decode.
EditOptions
Optional bounds for verified edits.
EffectiveEntry
The declaration that wins lookup for a key, with its effective value.
Entry
A declaration in a Document: a KEY=value or bare KEY item.
EntryTokens
The byte ranges of each part of a declaration’s source text.
ExpandOptions
Options for Document::resolve: eligible references, scope, lookup order and limits.
FormatOptions
The layout changes that Document::format makes.
FormatResult
The verified output of Document::format or Document::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.
LimitExceeded
A configured limit and the value that exceeded it.
LineIndex
Converts between byte offsets and zero-based line and column positions.
LookupIndex
A prebuilt key lookup table for one Document.
Masked
A wrapper whose Debug output masks values.
MaskedDeserializeErrorserde
A DeserializeError with its value-bearing message masked.
Multiline
Which quote styles may contain line breaks.
ParseOptions
Optional bounds for parsing untrusted input.
PortabilityDeclaration
A declaration as one dialect reads it, inside a PortabilityReading.
PortabilityDifference
A physical line that the compared dialects read differently.
PortabilityReading
How one dialect reads one differing physical line.
PortabilityReport
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.
ReferenceRules
Rules that decide which reference candidates could expand.
ResolveFailure
A failed Document::resolve_with_commands, with the command calls made before the failure.
ResolvedDocument
The result of resolution: every entry’s resolved value, in source order.
ResolvedEntry
One entry’s resolved value, with a record of where each part came from.
ResolvedSegment
One part of a resolved value: its text and where the text came from.
TextEdit
A replacement of one byte range of the original source.
VerifiedEdits
The verified result of an edit: the complete output text and the text edits that produce it.

Enums§

AssignmentState
Whether a declaration is bare, empty or has a value.
BareKeys
How lookup treats a bare key: a declaration such as DEBUG with no =.
BlankLines
What Document::format does with runs of blank lines.
BomPolicy
What happens to a UTF-8 byte-order mark (U+FEFF) at the start of the source.
ColonSeparator
Whether a colon can separate a key from its value, as in KEY: value.
ColumnEncoding
The unit that a Position column counts.
CommandOutcome
What one command callback call returned.
DiagnosticCode
The kind of a Diagnostic, as a stable identifier.
DifferenceKind
The kind of difference that Document::compare found for one key.
Duplicates
Which declaration wins when a key is declared more than once.
Edit
One operation of a Document::edit batch.
EditError
The reason an edit was refused.
EncodeError
The error returned when a value has no exact spelling in a dialect.
EqualsSpacing
The spacing that Document::format puts around assignment separators.
ExpandScope
Which declarations in the file a reference can see during resolution.
FinalNewline
What Document::format does with the line ending at the end of the file.
FormatError
The reason Document::format or Document::sort refused to return a result.
InlineComments
Where a # inside a line starts a comment.
InsertPosition
Where Edit::Insert and Document::insert place a new declaration.
ItemKind
What kind of source text an Item holds.
KeySyntax
Which characters an unquoted key may contain.
LimitKind
Which configured parse, load or edit limit was exceeded.
LineBreaks
Which characters end a physical line.
LineEnding
A line ending as written in the source.
LookupOrder
Whether the file or the lookup closure supplies a variable’s value first.
MalformedLines
What happens to a statement that cannot be read.
OperatorSet
Which variable forms ReferenceRules accept.
PortabilityPart
One item, or the part of one, on a physical line as one dialect reads it.
PositionError
Why a byte offset or position cannot be converted.
Quote
The quote style of a value as written in the source.
QuoteStyle
The quoting that Document::format prefers for values.
QuotedTail
What happens to text after a closing quote, as in A="x"y.
ReferenceKind
Whether a reference candidate is a variable or a command.
ReferenceOperator
The operator of a braced variable, such as :- in ${VAR:-default}.
ResolveError
An error from Document::resolve or Document::resolve_with_commands.
ResolvedSegmentKind
Where the text of one ResolvedSegment came from.
Severity
How serious a Diagnostic is.
SingleEscapes
The escape sequences that single-quoted values decode.
Syntax
The statement grammar: how a line splits into key, separator and value.
UnknownEscapes
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.
ValueOrigin
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§

Mask
A value with a structure-preserving, value-masking Debug form.

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 value in dialect.
mask
Wraps value so its Debug output masks values.
parse
Parses .env text with the Portable dialect, recovering from errors.
parse_entries_compact
Parses .env text with the Portable dialect into compact winning entries, preserving bare declarations.
parse_entries_compact_with
Parses .env text with the given dialect into compact winning entries, preserving bare declarations when the dialect keeps them in lookup.
parse_entries_compact_with_options
Parses .env text into compact winning entries with opt-in limits.
parse_owned
Parses an owned String with the Portable dialect, recovering from errors.
parse_owned_with
Parses an owned String with the given dialect, recovering from errors.
parse_owned_with_options
Parses an owned String with opt-in limits.
parse_strict
Parses .env text with the Portable dialect, failing on the first error.
parse_strict_with
Parses .env text with the given dialect, failing on the first error.
parse_strict_with_options
Parses .env text with the given dialect and opt-in limits, failing on the first error or limit.
parse_values
Parses .env text with the Portable dialect into a map of effective values.
parse_values_compact
Parses .env text with the Portable dialect into compact effective values.
parse_values_compact_with
Parses .env text with the given dialect into compact effective values.
parse_values_compact_with_options
Parses .env text into compact effective values with opt-in limits.
parse_values_with
Parses .env text with the given dialect into a map of effective values.
parse_values_with_options
Parses .env text into a map of effective values with opt-in limits.
parse_with
Parses .env text with the given dialect, recovering from errors.
parse_with_options
Parses .env text with the given dialect and opt-in limits, recovering from errors.
remove
Removes the only declaration of key from text, keeping the comments around it.
set
Sets the literal value of the only declaration of key in text.