Skip to main content

Entry

Struct Entry 

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

Source

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.

Source

pub fn item_id(self) -> usize

Returns the zero-based id of the item that holds this declaration: its position in Document::items.

Source

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.

Source

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);
Source

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.

Source

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"));
Source

pub fn quote(self) -> Quote

Returns the quote style of the value; Quote::None for a bare key.

Source

pub fn exported(self) -> bool

Returns whether the declaration starts with export.

Source

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.

Source

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.

Source

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.

Source

pub fn key_span(self) -> Range<usize> ⓘ

Returns the byte range of the key, without any key quotes.

Source

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).

Source

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.

Source

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.

Source

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
§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");
Source

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

Source

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>

Source

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"));

Trait Implementations§

Source§

impl<'doc> Clone for Entry<'doc>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'doc> Copy for Entry<'doc>

Source§

impl<'doc> Debug for Entry<'doc>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Mask for Entry<'_>

Source§

fn fmt_masked(&self, formatter: &mut Formatter<'_>) -> Result

Formats self without revealing value contents. Read more

Auto Trait Implementations§

§

impl<'doc> Forget for Entry<'doc>

§

impl<'doc> Freeze for Entry<'doc>

§

impl<'doc> Move for Entry<'doc>

§

impl<'doc> RefUnwindSafe for Entry<'doc>

§

impl<'doc> Send for Entry<'doc>

§

impl<'doc> Sync for Entry<'doc>

§

impl<'doc> Unpin for Entry<'doc>

§

impl<'doc> UnsafeUnpin for Entry<'doc>

§

impl<'doc> UnwindSafe for Entry<'doc>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.