pub struct Entry<'doc> { /* private fields */ }Expand description
A declaration in a Document: a KEY=value or bare KEY item.
An entry is a small Copy view that borrows its document. Get one from
Document::entries, Document::get_entry, Document::unique or
Item::entry.
Entry::value is the decoded value: quotes removed and escapes decoded
as the dialect defines, without the inline comment or the whitespace around
it. It stays literal, so $HOME is not expanded. Entry::raw_value,
Entry::tokens and the span methods give the source text behind it. A
bare key has no value (None), which is different from an empty
assignment such as KEY= (Some("")); see AssignmentState.
Every declaration is an entry, including duplicates and declarations that
do not take part in lookup. The effective value of a key, after the
dialect’s duplicate-key and bare-key rules, comes from Document::get.
§Examples
use adotenv::{AssignmentState, Quote};
let source = "export GREETING=\"hello\\nworld\" # shown at login\n";
let doc = adotenv::parse_strict(source)?;
let entry = doc.unique("GREETING")?;
assert_eq!(entry.value(), Some("hello\nworld"));
assert_eq!(entry.raw_value(), Some("\"hello\\nworld\""));
assert_eq!(entry.quote(), Quote::Double);
assert_eq!(entry.state(), AssignmentState::Value);
assert!(entry.exported());
assert_eq!(entry.inline_comment(), Some("# shown at login"));
assert_eq!(&source[entry.key_span()], "GREETING");
assert_eq!(entry.line(), 1);Implementations§
Source§impl<'doc> Entry<'doc>
impl<'doc> Entry<'doc>
Sourcepub const fn id(self) -> usize
pub const fn id(self) -> usize
Returns the zero-based id of this declaration: its position in
Document::entries.
Ids belong to this document only. Edit operations
select declarations by this id.
Sourcepub fn item_id(self) -> usize
pub fn item_id(self) -> usize
Returns the zero-based id of the item that holds this declaration: its
position in Document::items.
Sourcepub fn key(self) -> &'doc str
pub fn key(self) -> &'doc str
Returns the key, without any key quotes.
The key is borrowed from the source. Dialects that allow quoted keys
(Dialect::quoted_keys) drop the quotes here; EntryTokens::key
keeps them.
Sourcepub fn value(self) -> Option<&'doc str>
pub fn value(self) -> Option<&'doc str>
Returns the decoded value, or None for a bare key.
Decoding removes the quotes and decodes escapes as the dialect defines;
the inline comment and the whitespace around the value are not part of
it. The value stays literal: $HOME and ${HOME} are not expanded. An
empty assignment such as KEY= returns Some(""), not None. The
value is borrowed from the source when no decoding was needed.
This is the declaration’s own value. The effective value of a key,
after duplicate-key and bare-key rules, comes from Document::get.
§Examples
let doc = adotenv::parse_strict("A=\"tab\\there\"\nB='$HOME'\nC=\nD\n")?;
assert_eq!(doc.unique("A")?.value(), Some("tab\there"));
assert_eq!(doc.unique("B")?.value(), Some("$HOME"));
assert_eq!(doc.unique("C")?.value(), Some(""));
assert_eq!(doc.unique("D")?.value(), None);Sourcepub fn raw_value(self) -> Option<&'doc str>
pub fn raw_value(self) -> Option<&'doc str>
Returns the value exactly as written, including its quotes, or None
for a bare key.
Text after the closing quote is included only when the dialect appends
it to the value (QuotedTail::Append). This is the text of
Entry::value_span.
Sourcepub fn participates_in_lookup(self) -> bool
pub fn participates_in_lookup(self) -> bool
Returns whether this declaration takes part in lookup.
Every declaration takes part in Portable. A dialect can leave some out:
a bare key under BareKeys::Ignore (used by the Node dotenv, Compose
and Docker presets), and the key __proto__ in Node dotenv
(Dialect::node_object_keys). Such declarations still appear in
Document::entries, Document::get_all and Document::unique
and can be edited, but Document::get skips them.
§Examples
use adotenv::Dialect;
let (doc, _) = adotenv::parse_with("PORT=8080\nPORT\n", Dialect::NODE_DOTENV);
let bare = doc.get_all("PORT").last().unwrap();
assert!(!bare.participates_in_lookup());
assert_eq!(doc.get("PORT"), Some("8080"));Sourcepub fn quote(self) -> Quote
pub fn quote(self) -> Quote
Returns the quote style of the value; Quote::None for a bare key.
Sourcepub fn state(self) -> AssignmentState
pub fn state(self) -> AssignmentState
Returns whether the declaration is bare, empty or has a value.
See AssignmentState. The state depends on the source only, not on
lookup rules.
Sourcepub fn line(self) -> usize
pub fn line(self) -> usize
Returns the one-based line of the key.
Lines are counted as LineIndex counts them: LF, CRLF and a lone CR
each end a line, in every dialect. So in Compose and Docker, where a
lone CR does not end a statement, it still starts a new line number.
Sourcepub fn line_span(self) -> Range<usize> ⓘ
pub fn line_span(self) -> Range<usize> ⓘ
Returns the byte range of the whole statement, including its line ending.
This is the span of the item that holds the declaration
(Item::span). It covers every line of a multiline value. In
dialects that read several statements on one line, such as Compose, it
can be part of a line.
Sourcepub fn key_span(self) -> Range<usize> ⓘ
pub fn key_span(self) -> Range<usize> ⓘ
Returns the byte range of the key, without any key quotes.
Sourcepub fn value_span(self) -> Option<Range<usize>>
pub fn value_span(self) -> Option<Range<usize>>
Returns the byte range of the value as written, including its quotes,
or None for a bare key.
Text after the closing quote is included only when the dialect appends
it to the value (QuotedTail::Append).
Sourcepub fn tokens(self) -> &'doc EntryTokens
pub fn tokens(self) -> &'doc EntryTokens
Returns the byte ranges of every part of the declaration, such as the key, separator, value and inline comment.
Sourcepub fn inline_comment(self) -> Option<&'doc str>
pub fn inline_comment(self) -> Option<&'doc str>
Returns the inline comment, including its #, or None if there is
none.
Whole-line comments above the declaration are available through
Entry::leading_comments.
Sourcepub fn decoded_offset_to_raw(
self,
offset: usize,
) -> Result<usize, PositionError>
pub fn decoded_offset_to_raw( self, offset: usize, ) -> Result<usize, PositionError>
Maps a byte offset in the decoded value to a byte offset in the source.
Escapes make the decoded value shorter than its source text, so offsets
differ: in A="a\nb" the decoded b is at offset 2 of the value but at
byte 6 of the source. An offset at the start of a decoded escape maps
to the start of the escape in the source. The offset equal to the value
length is valid too. The time taken grows with the logarithm of the
number of escapes.
§Errors
PositionError::OutOfBoundswhen the declaration is a bare key oroffsetis greater than the length of the decoded value.PositionError::InvalidUtf8Boundarywhenoffsetis inside a UTF-8 character of the decoded value.
§Examples
let source = "A=\"a\\nb\"\n";
let doc = adotenv::parse_strict(source)?;
let entry = doc.unique("A")?;
assert_eq!(entry.value(), Some("a\nb"));
assert_eq!(entry.decoded_offset_to_raw(1)?, 4);
assert_eq!(entry.decoded_offset_to_raw(2)?, 6);
assert_eq!(&source[4..6], "\\n");Sourcepub fn decoded_span_to_raw(
self,
span: Range<usize>,
) -> Result<Range<usize>, PositionError>
pub fn decoded_span_to_raw( self, span: Range<usize>, ) -> Result<Range<usize>, PositionError>
Maps a byte range in the decoded value to a byte range in the source.
Both ends are mapped with Entry::decoded_offset_to_raw, so a range
that covers a decoded escape covers the whole escape in the source.
§Errors
PositionError::OutOfBoundswhen the range is reversed, the declaration is a bare key, or an end is past the decoded value.PositionError::InvalidUtf8Boundarywhen an end is inside a UTF-8 character of the decoded value.
§Examples
let source = "export A=\"two words\" # note\n";
let doc = adotenv::parse_strict(source)?;
let entry = doc.unique("A")?;
let raw = entry.decoded_span_to_raw(0..3)?;
assert_eq!(raw, 10..13);
assert_eq!(&source[raw], "two");Source§impl Entry<'_>
impl Entry<'_>
Sourcepub fn references(self) -> Vec<Reference>
pub fn references(self) -> Vec<Reference>
Returns the $ reference candidates in this entry’s value, in source order.
The value is scanned as written in the source, with its quote style:
$VAR, ${VAR}, the operator forms such as ${VAR:-default}, and
$(command), including candidates nested in operator arguments and
commands. Escaped, single-quoted and malformed candidates are returned
too. Nothing is looked up, expanded or run: use
Reference::is_eligible to apply ReferenceRules, or
Document::resolve to expand. A bare key
or a value without $ has no candidates.
Inside ${...}, the operand ends at the first } outside a nested
form. Quotes and backslashes are ordinary text there, as in Compose
and dotenv-expand. Inside $(...), shell quoting applies.
Candidates are sorted by span start. A nested candidate’s
Reference::parent is the index of its innermost containing form,
which comes earlier in the list. The candidates nested in a form, at
any depth, are exactly the candidates after it whose spans start before
its span ends, so they directly follow it.
The list holds at most one candidate per $ in the value, and scanning
takes time linear in the value length, up to a logarithmic factor.
Each candidate occupies roughly
size_of::<Reference>(), so a value with many
candidates can allocate much more memory than its own length. Bound the
value before calling this on untrusted input;
Document::resolve does so with
ExpandOptions::max_references.
§Examples
use adotenv::{parse_strict, ReferenceKind};
let source = "REVISION=${TAG:-$(git describe)}\n";
let doc = parse_strict(source)?;
let references = doc.unique("REVISION")?.references();
let spans: Vec<_> = references.iter().map(|r| &source[r.span.clone()]).collect();
assert_eq!(spans, ["${TAG:-$(git describe)}", "$(git describe)"]);
assert_eq!(references[1].kind, ReferenceKind::Command);
assert_eq!(references[1].parent, Some(0));
assert_eq!(references[1].depth, 1);Source§impl<'doc> Entry<'doc>
impl<'doc> Entry<'doc>
Sourcepub fn leading_comments(
self,
) -> impl DoubleEndedIterator<Item = Item<'doc>> + ExactSizeIterator + 'doc
pub fn leading_comments( self, ) -> impl DoubleEndedIterator<Item = Item<'doc>> + ExactSizeIterator + 'doc
Returns an iterator over the whole-line comments directly above this declaration, in source order.
The run of comments ends at the first item above that is not a
comment: a blank line, an entry or an invalid statement. So a comment
separated from the declaration by a blank line is not attached to it.
The inline comment on the declaration’s own line is available through
Entry::inline_comment.
§Panics
Panics only if an internal invariant is broken; the comments always come from the declaration’s own document.
§Examples
let source = "# detached\n\n# HTTP port\nPORT=8080 # default\n";
let (doc, _) = adotenv::parse(source);
let entry = doc.get_entry("PORT").unwrap();
let comments: Vec<_> = entry.leading_comments().map(|item| item.raw()).collect();
assert_eq!(comments, ["# HTTP port\n"]);
assert_eq!(entry.inline_comment(), Some("# default"));