adotenv 0.2.0

A tooling-grade .env parser: literal values (no variable expansion), exact byte spans, and edits that leave the rest of the file untouched.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
use alloc::{borrow::Cow, string::String, vec::Vec};
use core::{fmt, ops::Range};

use crate::{Diagnostic, DiagnosticCode, EditError, LineIndex, PositionError};

/// Quoting used by a literal value in the source.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Quote {
    /// An unquoted value.
    None,
    /// Fully literal single quotes.
    Single,
    /// Double quotes with Portable escapes.
    Double,
}

/// A declaration's assignment state, independent of any environment lookup.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AssignmentState {
    /// A declaration without `=`; this is not an empty string assignment.
    Bare,
    /// An assigned empty string; quoting is recorded separately.
    Empty,
    /// An assigned non-empty literal value.
    Value,
}

/// A physical source line ending, retained exactly.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LineEnding {
    /// No terminator at EOF.
    None,
    /// A line feed.
    Lf,
    /// A carriage return followed by a line feed.
    CrLf,
    /// A lone carriage return, diagnosed by Portable parsing.
    Cr,
}
impl LineEnding {
    /// The original ending bytes as text.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::None => "",
            Self::Lf => "\n",
            Self::CrLf => "\r\n",
            Self::Cr => "\r",
        }
    }
}

/// The kind of a lossless source item.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ItemKind {
    /// A blank physical line.
    Blank,
    /// A comment physical line.
    Comment,
    /// An assignment or bare declaration, possibly spanning physical lines.
    Entry,
    /// A malformed statement retained verbatim.
    Invalid,
}

/// Raw token ranges into a document's source; absent syntax is represented by `None`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EntryTokens {
    /// Leading spaces or tabs.
    pub indent: Range<usize>,
    /// The optional `export` keyword, excluding its separator.
    pub export: Option<Range<usize>>,
    /// Whitespace after the export keyword.
    pub space_after_export: Range<usize>,
    /// The key spelling.
    pub key: Range<usize>,
    /// Whitespace between the key and equals sign (or bare declaration tail).
    pub space_before_eq: Range<usize>,
    /// The equals sign; absent for bare declarations.
    pub eq: Option<Range<usize>>,
    /// Whitespace between equals and the value.
    pub space_after_eq: Range<usize>,
    /// The raw value token, including any quotes; absent for bare declarations.
    pub value: Option<Range<usize>>,
    /// The raw value body, excluding quotes.
    pub body: Option<Range<usize>>,
    /// Whitespace after the value and before any comment.
    pub trailing_space: Range<usize>,
    /// An inline comment, including its hash.
    pub inline_comment: Option<Range<usize>>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DecodeSegment {
    pub decoded: Range<usize>,
    pub raw: Range<usize>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct EntryData {
    pub item: usize,
    pub line: usize,
    pub tokens: EntryTokens,
    pub quote: Quote,
    pub state: AssignmentState,
    pub decoded: Option<String>,
    pub map: Vec<DecodeSegment>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ItemData {
    pub kind: ItemKind,
    pub span: Range<usize>,
    pub ending: LineEnding,
    pub entry: Option<usize>,
    pub comment: Option<Range<usize>>,
    pub invalid: Option<Diagnostic>,
}

/// A lossless Portable document retaining borrowed or explicitly owned UTF-8 source.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Document<'src> {
    pub(crate) source: Cow<'src, str>,
    pub(crate) items: Vec<ItemData>,
    pub(crate) entries: Vec<EntryData>,
    pub(crate) bom: bool,
}

impl Document<'_> {
    /// The complete, unmodified input, including the BOM and malformed syntax.
    #[must_use]
    pub fn source(&self) -> &str {
        &self.source
    }
    /// All source items in order; a leading BOM is the separate prelude.
    pub fn items(&self) -> impl DoubleEndedIterator<Item = Item<'_>> + ExactSizeIterator {
        (0..self.items.len()).map(|index| Item {
            document: self,
            index,
        })
    }
    /// One source item by its zero-based snapshot-local identity.
    #[must_use]
    pub fn item(&self, index: usize) -> Option<Item<'_>> {
        (index < self.items.len()).then_some(Item {
            document: self,
            index,
        })
    }
    /// Valid declarations in source order, including duplicates and bare keys.
    pub fn entries(&self) -> impl DoubleEndedIterator<Item = Entry<'_>> + ExactSizeIterator {
        (0..self.entries.len()).map(|index| Entry {
            document: self,
            index,
        })
    }
    /// One declaration by its zero-based snapshot-local identity.
    #[must_use]
    pub fn entry(&self, index: usize) -> Option<Entry<'_>> {
        (index < self.entries.len()).then_some(Entry {
            document: self,
            index,
        })
    }
    /// Every occurrence of a key in source order.
    pub fn get_all<'doc, 'key>(
        &'doc self,
        key: &'key str,
    ) -> impl DoubleEndedIterator<Item = Entry<'doc>> + 'key
    where
        'doc: 'key,
    {
        self.entries().filter(move |entry| entry.key() == key)
    }
    /// The last declaration of a key, retaining its bare/empty/value state.
    #[must_use]
    pub fn get_entry(&self, key: &str) -> Option<Entry<'_>> {
        self.entries().rev().find(|entry| entry.key() == key)
    }
    /// The last assigned literal value. A final bare declaration returns `None`.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&str> {
        self.get_entry(key).and_then(Entry::value)
    }
    /// Select a unique declaration without guessing between duplicate occurrences.
    ///
    /// # Errors
    /// Returns [`EditError::Missing`] or [`EditError::Duplicate`].
    pub fn unique(&self, key: &str) -> Result<Entry<'_>, EditError> {
        let mut entries = self.entries().filter(|entry| entry.key() == key);
        let first = entries.next().ok_or(EditError::Missing)?;
        let remaining = entries.count();
        if remaining == 0 {
            Ok(first)
        } else {
            Err(EditError::Duplicate(remaining + 1))
        }
    }
    /// Whether the input begins with one retained UTF-8 BOM.
    #[must_use]
    pub const fn has_bom(&self) -> bool {
        self.bom
    }
    /// The BOM byte range, when present.
    #[must_use]
    pub fn bom_span(&self) -> Option<Range<usize>> {
        self.bom.then_some(0..3)
    }
    /// Whether the source ends in LF, CRLF or lone CR.
    #[must_use]
    pub fn has_final_newline(&self) -> bool {
        self.source.ends_with(['\n', '\r'])
    }
    /// Build an explicit source index without imposing an index allocation on parsing.
    #[must_use]
    pub fn line_index(&self) -> LineIndex<'_> {
        LineIndex::new(self.source())
    }
    /// Retain all metadata and consume owned source, copying borrowed source only here.
    #[must_use]
    pub fn into_owned(self) -> Document<'static> {
        Document {
            source: Cow::Owned(self.source.into_owned()),
            items: self.items,
            entries: self.entries,
            bom: self.bom,
        }
    }
    /// The dominant source line ending, or LF for a document without endings.
    pub(crate) fn preferred_ending(&self) -> &'static str {
        let mut counts = [0usize; 3];
        let bytes = self.source.as_bytes();
        let mut at = 0;
        while at < bytes.len() {
            match bytes[at] {
                b'\r' if bytes.get(at + 1) == Some(&b'\n') => {
                    counts[1] += 1;
                    at += 1;
                }
                b'\r' => counts[2] += 1,
                b'\n' => counts[0] += 1,
                _ => {}
            }
            at += 1;
        }
        if counts[1] > counts[0] && counts[1] >= counts[2] {
            "\r\n"
        } else if counts[2] > counts[0] && counts[2] > counts[1] {
            "\r"
        } else {
            "\n"
        }
    }
}

impl fmt::Display for Document<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.source())
    }
}

/// A borrowed view of a declaration; identities belong to this document snapshot.
#[derive(Debug, Clone, Copy)]
pub struct Entry<'doc> {
    pub(crate) document: &'doc Document<'doc>,
    pub(crate) index: usize,
}
impl<'doc> Entry<'doc> {
    fn data(self) -> &'doc EntryData {
        &self.document.entries[self.index]
    }
    /// Zero-based declaration identity for explicit native edits on this snapshot.
    #[must_use]
    pub const fn id(self) -> usize {
        self.index
    }
    /// The source item containing this declaration.
    #[must_use]
    pub fn item_id(self) -> usize {
        self.data().item
    }
    /// The original key spelling, borrowed without copying.
    #[must_use]
    pub fn key(self) -> &'doc str {
        &self.document.source[self.data().tokens.key.clone()]
    }
    /// Literal decoded value; `None` is a bare declaration, not an empty string.
    #[must_use]
    pub fn value(self) -> Option<&'doc str> {
        let data = self.data();
        data.tokens.body.as_ref().map(|body| {
            data.decoded
                .as_deref()
                .unwrap_or(&self.document.source[body.clone()])
        })
    }
    /// Exact original token, including quotes, or `None` for a bare declaration.
    #[must_use]
    pub fn raw_value(self) -> Option<&'doc str> {
        self.data()
            .tokens
            .value
            .as_ref()
            .map(|span| &self.document.source[span.clone()])
    }
    /// How the assigned value is quoted.
    #[must_use]
    pub fn quote(self) -> Quote {
        self.data().quote
    }
    /// Whether this declaration has the export prefix.
    #[must_use]
    pub fn exported(self) -> bool {
        self.data().tokens.export.is_some()
    }
    /// Bare/empty/non-empty state, without implicit environment interpretation.
    #[must_use]
    pub fn state(self) -> AssignmentState {
        self.data().state
    }
    /// Explicitly one-based physical line of the key.
    #[must_use]
    pub fn line(self) -> usize {
        self.data().line
    }
    /// Whole statement, including its final line ending, excluding the BOM prelude.
    #[must_use]
    pub fn line_span(self) -> Range<usize> {
        self.document.items[self.item_id()].span.clone()
    }
    /// Original key byte range.
    #[must_use]
    pub fn key_span(self) -> Range<usize> {
        self.data().tokens.key.clone()
    }
    /// Original value token byte range, or `None` for bare declarations.
    #[must_use]
    pub fn value_span(self) -> Option<Range<usize>> {
        self.data().tokens.value.clone()
    }
    /// All raw token metadata.
    #[must_use]
    pub fn tokens(self) -> &'doc EntryTokens {
        &self.data().tokens
    }
    /// An inline comment including its marker.
    #[must_use]
    pub fn inline_comment(self) -> Option<&'doc str> {
        self.data()
            .tokens
            .inline_comment
            .as_ref()
            .map(|span| &self.document.source[span.clone()])
    }
    /// Map a decoded-value byte boundary back into original source bytes.
    ///
    /// Lookup is logarithmic in the number of decoded escape segments.
    ///
    /// # Errors
    /// Rejects absent values, out-of-range offsets and interior UTF-8 boundaries.
    pub fn decoded_offset_to_raw(self, offset: usize) -> Result<usize, PositionError> {
        let value = self.value().ok_or(PositionError::OutOfBounds)?;
        if offset > value.len() {
            return Err(PositionError::OutOfBounds);
        }
        if !value.is_char_boundary(offset) {
            return Err(PositionError::InvalidUtf8Boundary);
        }
        let data = self.data();
        let body = data
            .tokens
            .body
            .as_ref()
            .ok_or(PositionError::OutOfBounds)?;
        let count = data
            .map
            .partition_point(|segment| segment.decoded.start <= offset);
        let Some(index) = count.checked_sub(1) else {
            return Ok(body.start + offset);
        };
        let segment = &data.map[index];
        if offset == segment.decoded.start {
            return Ok(segment.raw.start);
        }
        if offset < segment.decoded.end {
            return Err(PositionError::InvalidUtf8Boundary);
        }
        Ok(segment.raw.end + offset - segment.decoded.end)
    }
    /// Map a decoded-value byte range to its exact original source region.
    ///
    /// # Errors
    /// Rejects reversed ranges and invalid decoded boundaries.
    pub fn decoded_span_to_raw(self, span: Range<usize>) -> Result<Range<usize>, PositionError> {
        if span.start > span.end {
            return Err(PositionError::OutOfBounds);
        }
        Ok(self.decoded_offset_to_raw(span.start)?..self.decoded_offset_to_raw(span.end)?)
    }
}

/// A borrowed view of a raw source item.
#[derive(Debug, Clone, Copy)]
pub struct Item<'doc> {
    pub(crate) document: &'doc Document<'doc>,
    pub(crate) index: usize,
}
impl<'doc> Item<'doc> {
    fn data(self) -> &'doc ItemData {
        &self.document.items[self.index]
    }
    /// Zero-based identity, valid only for this document snapshot.
    #[must_use]
    pub const fn id(self) -> usize {
        self.index
    }
    /// The item's syntax classification.
    #[must_use]
    pub fn kind(self) -> ItemKind {
        self.data().kind
    }
    /// Complete raw byte range, including its final line ending.
    #[must_use]
    pub fn span(self) -> Range<usize> {
        self.data().span.clone()
    }
    /// Original source text, without normalization.
    #[must_use]
    pub fn raw(self) -> &'doc str {
        &self.document.source[self.span()]
    }
    /// The final physical line ending of the item.
    #[must_use]
    pub fn line_ending(self) -> LineEnding {
        self.data().ending
    }
    /// Item bytes excluding the final line ending.
    #[must_use]
    pub fn content_span(self) -> Range<usize> {
        let span = self.span();
        span.start..span.end - self.line_ending().as_str().len()
    }
    /// Declaration view when this is an entry item.
    #[must_use]
    pub fn entry(self) -> Option<Entry<'doc>> {
        self.data().entry.map(|index| Entry {
            document: self.document,
            index,
        })
    }
    /// Comment body after `#`, preserving its spaces.
    #[must_use]
    pub fn comment_text(self) -> Option<&'doc str> {
        self.data()
            .comment
            .as_ref()
            .map(|span| &self.document.source[span.clone()])
    }
    /// The error explaining an invalid statement, if this item is invalid.
    #[must_use]
    pub fn diagnostic(self) -> Option<&'doc Diagnostic> {
        self.data().invalid.as_ref()
    }
    /// Stable invalid-statement identity, convenient for source-preserving checks.
    #[must_use]
    pub fn invalid_code(self) -> Option<DiagnosticCode> {
        self.diagnostic().map(Diagnostic::code)
    }
}