adotenv/lib.rs
1//! Literal, lossless `.env` parsing and verified editing.
2//!
3//! adotenv reads `.env` files the way tools need them. It keeps every byte of the source,
4//! leaves values literal (`${HOME}` is text, not an expansion), gives every token a byte span
5//! and checks every edit by parsing the result again before returning it. It is built for
6//! linters, formatters, editors, scanners and other tools that maintain configuration files.
7//!
8//! The core never reads files or environment variables, never expands references and never
9//! runs commands. Each of those happens only through an explicit API or an optional feature.
10//!
11//! The [user guide](https://asamarts.github.io/adotenv/) explains the behavior in more depth.
12//! This reference documents each item.
13//!
14//! # Quick start
15//!
16//! ```
17//! let source = "# app\nexport PORT=8080\nURL=\"${HOST}/api\" # base\n";
18//! let doc = adotenv::parse_strict(source)?;
19//!
20//! // Values are literal: references are not expanded.
21//! assert_eq!(doc.get("PORT"), Some("8080"));
22//! assert_eq!(doc.get("URL"), Some("${HOST}/api"));
23//!
24//! // A document prints back the exact source.
25//! assert_eq!(doc.to_string(), source);
26//!
27//! // An edit returns the new text, already parsed again and checked.
28//! let edited = doc.set("PORT", "9090")?;
29//! assert_eq!(edited.as_str(), "# app\nexport PORT=9090\nURL=\"${HOST}/api\" # base\n");
30//! # Ok::<(), Box<dyn std::error::Error>>(())
31//! ```
32//!
33//! [`parse_strict`] returns the first error instead of a document. [`parse`] never fails: it
34//! returns a document and a list of [`Diagnostic`]s, so tools can inspect and report on a broken
35//! file without losing any of it.
36//!
37//! ```
38//! use adotenv::{DiagnosticCode, ItemKind};
39//!
40//! let (doc, diagnostics) = adotenv::parse("BAD KEY=value\nGOOD=kept\n");
41//! assert_eq!(doc.get("GOOD"), Some("kept"));
42//! assert_eq!(doc.items().next().unwrap().kind(), ItemKind::Invalid);
43//! assert_eq!(diagnostics[0].code(), DiagnosticCode::InvalidKey);
44//! assert_eq!(diagnostics[0].line(), 1);
45//! ```
46//!
47//! # Where to start
48//!
49//! | Task | Start with |
50//! |---|---|
51//! | Parse text | [`parse`], [`parse_strict`], [`parse_owned`], [`parse_values`], [`parse_values_compact`], [`parse_entries_compact`], and their `_with` variants that take a [`Dialect`] |
52//! | Look up values | [`Document::get`], [`Document::get_entry`], [`Document::get_all`], [`Document::effective_entries`], [`Document::lookup_index`] |
53//! | Walk the source | [`Document::items`], [`Document::entries`], [`Item`], [`Entry`], [`EntryTokens`] |
54//! | Report problems | [`Diagnostic`], [`DiagnosticCode`], [`Severity`] |
55//! | Bound untrusted input | [`ParseOptions`], [`EditOptions`], [`LimitExceeded`], [`LimitKind`] |
56//! | Choose reading rules | [`Dialect`] and its presets |
57//! | Edit | [`Document::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 [`Edit`]s |
58//! | Set or remove one key of Portable text in one call | [`set`], [`remove`] |
59//! | Quote a value for a file | [`encode_value`], [`encode_value_with`] |
60//! | Format and sort | [`Document::format`] with [`FormatOptions`], [`Document::sort`] |
61//! | Compare two files | [`Document::compare`] |
62//! | Write an example file | [`Document::example`] |
63//! | Check portability across dialects | [`Document::portability`] |
64//! | Groups and comments | [`Document::groups`], [`Document::header`], [`Entry::leading_comments`] |
65//! | Lines and columns | [`Document::line_index`], [`LineIndex`], [`Position`], [`ColumnEncoding`] |
66//! | Find `$VAR` references | [`Entry::references`], [`ReferenceRules`] |
67//! | Resolve references | [`Document::resolve`] with [`ExpandOptions`] |
68//! | Load files from disk | the [`load`] module |
69//! | Deserialize into a struct | [`Document::deserialize`] |
70//! | Run command substitutions | [`Document::resolve_with_commands`] and the [`exec`] module |
71//!
72//! # Features
73//!
74//! | Feature | Default | Adds |
75//! |---|---|---|
76//! | `std` | yes | Standard library support. Required by `load` and `exec`. |
77//! | `load` | no | The [`load`] module, which reads `.env` cascades and file lists from disk. |
78//! | `serde` | no | [`Document::deserialize`] and [`DeserializeError`]; with `load` also [`load::LoadedEnvironment::deserialize`]. |
79//! | `exec` | no | The [`exec`] module, which runs command substitutions through the platform shell. |
80//!
81//! Without default features the crate is `no_std` and uses `alloc`:
82//!
83//! ```toml
84//! adotenv = { version = "1", default-features = false }
85//! ```
86//!
87//! The only dependency is `serde`, and only with the `serde` feature. The crate forbids unsafe
88//! code with every feature combination and supports Rust 1.81 and later.
89//!
90//! # Dialects
91//!
92//! Every parse uses a [`Dialect`]: the syntax and literal lookup rules of one `.env` reader.
93//! The functions without a suffix use [`Dialect::PORTABLE`]. The other presets follow Node
94//! dotenv, python-dotenv, Docker Compose and Docker `--env-file`, and a custom dialect starts
95//! from a preset and changes single rules. No dialect expands references, reads the process
96//! environment or loads files.
97//!
98//! ```
99//! use adotenv::{parse_with, Dialect};
100//!
101//! let (doc, _) = parse_with("A=a#b\n", Dialect::NODE_DOTENV);
102//! assert_eq!(doc.get("A"), Some("a"));
103//! assert_eq!(doc.reparse(Dialect::DOCKER_RAW).0.get("A"), Some("a#b"));
104//! ```
105//!
106//! # Source, spans and positions
107//!
108//! A [`Document`] borrows its source, or owns it after [`parse_owned`] or
109//! [`Document::into_owned`]. Its items cover the whole source without gaps, malformed
110//! statements included; only a leading byte-order mark that the dialect strips belongs to no
111//! item. Every span is a byte range into the original text, byte-order mark included.
112//!
113//! [`Entry::line`] and [`Diagnostic::line`] are one-based. [`LineIndex`] converts between byte
114//! offsets and zero-based lines and columns in UTF-8 bytes, Unicode scalar values or UTF-16
115//! code units, and [`Position::one_based`] converts a position for display. Lines and line
116//! numbers count LF, CRLF and a lone CR as line ends, whatever the dialect.
117//!
118//! # Verified edits
119//!
120//! Methods such as [`Document::set`] select the only declaration of a key. A batch of
121//! [`Edit`]s selects entries and items by id, so it can also change one of several
122//! declarations of a key. Every edit and every batch is applied to the whole source, parsed
123//! again with the same dialect and checked: the requested change happened and nothing else
124//! changed meaning. [`VerifiedEdits`] then gives the new text and the source-relative
125//! [`TextEdit`]s, for example to send to an editor. [`Document::format`] and
126//! [`Document::sort`] are verified the same way.
127//!
128//! # References and resolution
129//!
130//! Values stay literal. [`Entry::references`] lists `$VAR`, `${VAR:-default}` and
131//! `$(command)` forms with their spans without resolving anything. [`Document::resolve`]
132//! substitutes references only on request, from a lookup closure you pass, with explicit
133//! scope, precedence and size limits. Commands run only through a callback you pass to
134//! [`Document::resolve_with_commands`].
135//!
136//! # Secrets
137//!
138//! Values may be secrets. `Debug` output of documents, items, entries, edit and format results,
139//! comparisons, loaded environments and entries, resolved values, lookup indexes, effective
140//! entries, compact values, compact entries, line indexes, groups and portability reports include them, and so
141//! do the messages of serde conversion errors. The core document, edit, comparison, compact
142//! value/entry, load, resolution, line-index, group and portability types support a
143//! structure-preserving `Debug` form that replaces values with `<redacted>` through [`Masked`]
144//! and [`mask`]; use [`DeserializeError::masked`] for serde errors. Adapter types still include values. Do not
145//! log normal `Debug` output where values are secret. [`Document::example`] removes assigned
146//! values but keeps comments verbatim, including any secret written in a comment.
147//!
148//! # Related crates
149//!
150//! - [`adotenv-process`](https://docs.rs/adotenv-process) applies a loaded environment to the
151//! current process.
152//! - [`adotenv-config`](https://docs.rs/adotenv-config) and
153//! [`adotenv-figment`](https://docs.rs/adotenv-figment) provide values to `config` and
154//! Figment.
155//! - [`adotenv-cli`](https://crates.io/crates/adotenv-cli) checks, formats, compares and loads
156//! files from a shell.
157//!
158//! # Stability
159//!
160//! The public API follows semantic versioning. Enums and option structs are
161//! `#[non_exhaustive]`, so a minor release can add variants, fields and builders.
162
163#![cfg_attr(not(feature = "std"), no_std)]
164#![cfg_attr(docsrs, feature(doc_cfg))]
165// Links to items behind optional features resolve only when those features are enabled.
166// docs.rs and CI build the documentation with every feature.
167#![cfg_attr(
168 not(all(feature = "load", feature = "serde", feature = "exec")),
169 allow(rustdoc::broken_intra_doc_links)
170)]
171#![forbid(unsafe_code)]
172#![warn(missing_docs)]
173
174extern crate alloc;
175
176mod compact;
177mod compare;
178mod diagnostic;
179mod dialect;
180mod edit;
181mod encode;
182mod example;
183#[cfg(feature = "exec")]
184pub mod exec;
185mod format;
186mod limit;
187#[cfg(feature = "load")]
188pub mod load;
189mod mask;
190mod model;
191mod parser;
192mod portability;
193mod position;
194mod references;
195mod resolve;
196#[cfg(feature = "serde")]
197mod serde_support;
198mod sort;
199mod structure;
200
201pub use compact::{CompactEntries, CompactValues};
202pub use compare::{ComparedValue, Comparison, ComparisonEntry, DifferenceKind};
203pub use diagnostic::{Diagnostic, DiagnosticCode, Severity};
204pub use dialect::{
205 BareKeys, BomPolicy, ColonSeparator, Dialect, DoubleEscapes, Duplicates, InlineComments,
206 KeySyntax, LineBreaks, MalformedLines, Multiline, QuotedTail, SingleEscapes, Syntax,
207 UnknownEscapes, Whitespace,
208};
209pub use edit::{
210 remove, set, Edit, EditError, EditOptions, InsertPosition, TextEdit, VerifiedEdits,
211};
212pub use encode::{encode_value, encode_value_with, EncodeError};
213pub use format::{
214 BlankLines, EqualsSpacing, FinalNewline, FormatError, FormatOptions, FormatResult, QuoteStyle,
215};
216pub use limit::{LimitExceeded, LimitKind};
217pub use mask::{mask, Mask, Masked, REDACTED};
218pub use model::{
219 AssignmentState, Document, EffectiveEntry, Entry, EntryTokens, Item, ItemKind, LineEnding,
220 LookupIndex, Quote,
221};
222pub use parser::{
223 parse, parse_entries_compact, parse_entries_compact_with, parse_entries_compact_with_options,
224 parse_owned, parse_owned_with, parse_owned_with_options, parse_strict, parse_strict_with,
225 parse_strict_with_options, parse_values, parse_values_compact, parse_values_compact_with,
226 parse_values_compact_with_options, parse_values_with, parse_values_with_options, parse_with,
227 parse_with_options, ParseOptions,
228};
229pub use portability::{
230 PortabilityDeclaration, PortabilityDifference, PortabilityPart, PortabilityReading,
231 PortabilityReport,
232};
233pub use position::{ColumnEncoding, LineIndex, Position, PositionError};
234pub use references::{OperatorSet, Reference, ReferenceKind, ReferenceOperator, ReferenceRules};
235pub use resolve::{
236 CommandCall, CommandContext, CommandError, CommandOutcome, ExpandOptions, ExpandScope,
237 LookupOrder, ResolveError, ResolveFailure, ResolvedDocument, ResolvedEntry, ResolvedSegment,
238 ResolvedSegmentKind, Unresolved, ValueOrigin,
239};
240#[cfg(feature = "serde")]
241pub use serde_support::{DeserializeError, MaskedDeserializeError};
242pub use structure::{Group, Groups};
243
244#[cfg(test)]
245mod compact_tests;
246#[cfg(test)]
247mod compare_tests;
248#[cfg(test)]
249mod diagnostic_tests;
250#[cfg(test)]
251mod dialect_tests;
252#[cfg(test)]
253mod edit_tests;
254#[cfg(test)]
255mod encode_tests;
256#[cfg(test)]
257mod example_tests;
258#[cfg(test)]
259mod format_tests;
260#[cfg(test)]
261mod limit_tests;
262#[cfg(all(test, feature = "load"))]
263mod load_tests;
264#[cfg(test)]
265mod mask_tests;
266#[cfg(test)]
267mod portability_tests;
268#[cfg(test)]
269mod position_tests;
270#[cfg(test)]
271mod reference_tests;
272#[cfg(test)]
273mod resolve_tests;
274#[cfg(all(test, feature = "serde"))]
275mod serde_tests;
276#[cfg(test)]
277mod sort_tests;
278#[cfg(test)]
279mod structure_tests;
280#[cfg(test)]
281mod tests;
282
283/// Compile and execute the README examples with the crate's documentation.
284#[cfg(doctest)]
285#[doc = include_str!("../README.md")]
286pub struct ReadmeDoctests;
287
288/// Compile and execute the examples of the documentation site.
289///
290/// Every book page is listed, so a Rust example added to any page is tested.
291/// Pages with examples that need optional features are tested with them.
292#[cfg(doctest)]
293pub mod book_doctests {
294 #[doc = include_str!("../docs/index.md")]
295 pub struct Introduction;
296 #[cfg_attr(feature = "load", doc = include_str!("../docs/guide/getting-started.md"))]
297 pub struct GettingStarted;
298 #[doc = include_str!("../docs/guide/parsing.md")]
299 pub struct Parsing;
300 #[doc = include_str!("../docs/design/dialects.md")]
301 pub struct Dialects;
302 #[doc = include_str!("../docs/guide/editing.md")]
303 pub struct Editing;
304 #[doc = include_str!("../docs/design/formatting.md")]
305 pub struct Formatting;
306 #[doc = include_str!("../docs/design/comparison.md")]
307 pub struct Comparison;
308 #[cfg_attr(feature = "exec", doc = include_str!("../docs/design/expansion.md"))]
309 pub struct References;
310 #[cfg_attr(feature = "load", doc = include_str!("../docs/design/loading.md"))]
311 pub struct Loading;
312 #[cfg_attr(all(feature = "load", feature = "serde"), doc = include_str!("../docs/design/serde.md"))]
313 pub struct Serde;
314 #[cfg_attr(feature = "load", doc = include_str!("../docs/guide/process.md"))]
315 pub struct Process;
316 #[doc = include_str!("../docs/design/integrations.md")]
317 pub struct Integrations;
318 #[doc = include_str!("../docs/design/cli.md")]
319 pub struct Cli;
320 #[doc = include_str!("../docs/reference/diagnostics.md")]
321 pub struct Diagnostics;
322 #[doc = include_str!("../docs/reference/security.md")]
323 pub struct Security;
324 #[doc = include_str!("../docs/reference/upgrading.md")]
325 pub struct Upgrading;
326 #[doc = include_str!("../docs/design/architecture.md")]
327 pub struct Architecture;
328 #[doc = include_str!("../docs/design/feature-decisions.md")]
329 pub struct FeatureDecisions;
330 #[doc = include_str!("../docs/design/quality.md")]
331 pub struct Quality;
332 #[doc = include_str!("../docs/design/test-audit.md")]
333 pub struct TestAudit;
334 #[doc = include_str!("../docs/design/performance.md")]
335 pub struct Performance;
336 #[doc = include_str!("../docs/design/1.0-readiness.md")]
337 pub struct Readiness;
338 #[doc = include_str!("../docs/design/1.0-fix-round.md")]
339 pub struct FixRound;
340 #[doc = include_str!("../docs/design/1.1-audit.md")]
341 pub struct Audit;
342}