### Result `unwrap_or` and `unwrap_or_else` Methods Source: https://docs.rs/dotenvy/latest/dotenvy/type.Result_search=u32+-%3E+bool Explains how to get the `Ok` value or a default using `unwrap_or` (eager) and `unwrap_or_else` (lazy). ```APIDOC ## `unwrap_or` and `unwrap_or_else` Methods ### Description `unwrap_or` returns the contained `Ok` value or a provided default (eagerly evaluated). `unwrap_or_else` returns the contained `Ok` value or computes it from a closure (lazily evaluated). ### Methods - `pub fn unwrap_or(self, default: T) -> T` - `pub fn unwrap_or_else(self, op: F) -> T` where `F: FnOnce(E) -> T` ### Parameters - **default** (T) - The default value to return if `self` is `Err` for `unwrap_or`. - **op** (FnOnce(E) -> T) - A closure that computes the default value if `self` is `Err` for `unwrap_or_else`. ### Request Example ```rust // unwrap_or example let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); // unwrap_or_else example fn count(x: &str) -> usize { x.len() } assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` ``` -------------------------------- ### Handle File Metadata Operations with and_then in Rust Source: https://docs.rs/dotenvy/latest/dotenvy/type.Result_search=u32+-%3E+bool Illustrates using `and_then` to chain fallible file system operations, specifically getting metadata and then the modified time. This example shows how to handle potential errors like file not found. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Load Default Environment Variables (Rust) Source: https://docs.rs/dotenvy/latest/src/dotenvy/lib.rs Loads environment variables from a default '.env' file. This is the most common way to use the library, typically called once at the start of an application. It searches for '.env' in the current directory and parent directories. Existing environment variables are preserved, and the first declaration in the file takes precedence. ```Rust pub fn dotenv() -> Result<()> { let path = find::locate_dotenv(None).ok_or(Error::NotFound) .map(PathBuf::from)?; let file = File::open(path).map_err(Error::Io)?; Iter::new(file).load() } ``` -------------------------------- ### Result `or` Method Source: https://docs.rs/dotenvy/latest/dotenvy/type.Result_search=u32+-%3E+bool Explains and provides examples for the `or` method, which returns the second result if the first is an `Err`. ```APIDOC ## `or` Method ### Description Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`. Arguments passed to `or` are eagerly evaluated. ### Method `pub fn or(self, res: Result) -> Result` ### Parameters - **res** (Result) - The result to return if `self` is `Err`. ### Request Example ```rust let x: Result = Ok(2); let y: Result = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("early error"); let y: Result = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("not a 2"); let y: Result = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result = Ok(2); let y: Result = Ok(100); assert_eq!(x.or(y), Ok(2)); ``` ``` -------------------------------- ### Iter Struct and Methods Source: https://docs.rs/dotenvy/latest/dotenvy/struct.Iter_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Documentation for the `Iter` struct, including its constructor and methods for loading environment variables. ```APIDOC ## Struct Iter ### Description Represents an iterator over key-value pairs read from a source. ### Constructor #### `new(reader: R) -> Iter` Creates a new `Iter` instance with the given reader. ### Methods #### `load(self) -> Result<()>` Loads all variables found in the `reader` into the environment, preserving any existing environment variables of the same name. If a variable is specified multiple times within the reader’s data, then the first occurrence is applied. #### `load_override(self) -> Result<()>` Loads all variables found in the `reader` into the environment, overriding any existing environment variables of the same name. If a variable is specified multiple times within the reader’s data, then the last occurrence is applied. ``` -------------------------------- ### Test error handling for keys starting with a dot in dotenvy Source: https://docs.rs/dotenvy/latest/src/dotenvy/parse.rs_search=u32+-%3E+bool Checks that dotenvy rejects lines where the key starts with a dot ('.'), as this is considered an invalid format. It ensures such lines are flagged as parse errors. ```rust fn should_not_allow_dot_as_first_character_of_key() { let wrong_key_value = ".Key=VALUE"; let parsed_values: Vec<_> = Iter::new(wrong_key_value.as_bytes()).collect(); assert_eq!(parsed_values.len(), 1); if let Err(LineParse(second_value, index)) = &parsed_values[0] { assert_eq!(second_value, wrong_key_value); assert_eq!(*index, 0) } else { panic!("Expected the second value not to be parsed") } } ``` -------------------------------- ### dotenvy Crate Documentation Source: https://docs.rs/dotenvy/latest/dotenvy/index This section details the functions available in the dotenvy crate for managing environment variables. ```APIDOC ## Crate dotenvy ### Summary A well-maintained fork of the `dotenv` crate. This library loads environment variables from a `.env` file. This is convenient for dev environments. ## Structs ### Iter ## Enums ### Error ## Functions ### dotenv **Description**: Loads the `.env` file from the current directory or parents. This is typically what you want. **Method**: (Implicitly a function call, not an HTTP endpoint) **Endpoint**: N/A ### dotenv_iter **Description**: Returns an iterator over environment variables. **Method**: (Implicitly a function call, not an HTTP endpoint) **Endpoint**: N/A ### dotenv_override **Description**: Loads all variables found in the `reader` into the environment, overriding any existing environment variables of the same name. **Method**: (Implicitly a function call, not an HTTP endpoint) **Endpoint**: N/A ### from_filename **Description**: Loads environment variables from the specified file. **Method**: (Implicitly a function call, not an HTTP endpoint) **Endpoint**: N/A ### from_filename_iter **Description**: Returns an iterator over environment variables from the specified file. **Method**: (Implicitly a function call, not an HTTP endpoint) **Endpoint**: N/A ### from_filename_override **Description**: Loads environment variables from the specified file, overriding existing environment variables. **Method**: (Implicitly a function call, not an HTTP endpoint) **Endpoint**: N/A ### from_path **Description**: Loads environment variables from the specified path. **Method**: (Implicitly a function call, not an HTTP endpoint) **Endpoint**: N/A ### from_path_iter **Description**: Returns an iterator over environment variables from the specified path. **Method**: (Implicitly a function call, not an HTTP endpoint) **Endpoint**: N/A ### from_path_override **Description**: Loads environment variables from the specified path, overriding existing environment variables. **Method**: (Implicitly a function call, not an HTTP endpoint) **Endpoint**: N/A ### from_read **Description**: Loads environment variables from `io::Read`. **Method**: (Implicitly a function call, not an HTTP endpoint) **Endpoint**: N/A ### from_read_iter **Description**: Returns an iterator over environment variables from `io::Read`. **Method**: (Implicitly a function call, not an HTTP endpoint) **Endpoint**: N/A ### from_read_override **Description**: Loads environment variables from `io::Read`, overriding existing environment variables. **Method**: (Implicitly a function call, not an HTTP endpoint) **Endpoint**: N/A ### var **Description**: Gets the value for an environment variable. **Method**: (Implicitly a function call, not an HTTP endpoint) **Endpoint**: N/A ### vars **Description**: Returns an iterator of `(key, value)` pairs for all environment variables of the current process. The returned iterator contains a snapshot of the process’s environment variables at the time of invocation. Modifications to environment variables afterwards will not be reflected. **Method**: (Implicitly a function call, not an HTTP endpoint) **Endpoint**: N/A ## Type Aliases ### Result ``` -------------------------------- ### Get ExitCode from Result in Rust Source: https://docs.rs/dotenvy/latest/dotenvy/type.Result_search= This implementation of the `Termination` trait allows a `Result` to be converted into an `ExitCode`. It is called to get the representation of the value as a status code, which is then returned to the operating system. This is typically used in the `main` function of a Rust program. ```rust impl Termination for Result where T: Termination, E: Debug ``` -------------------------------- ### Initialize and Use Finder for .env files in Rust Source: https://docs.rs/dotenvy/latest/src/dotenvy/find.rs This Rust code defines a `Finder` struct and associated methods for locating and opening .env files. It allows specifying a custom filename and searches recursively in parent directories until the file is found or the root is reached. The `find` function handles file metadata checks and I/O errors, returning a path and an iterator over the file's content. ```rust use std::fs::File; use std::path::{Path, PathBuf}; use std::{env, fs, io}; use crate::errors::*; use crate::iter::Iter; pub struct Finder<'a> { filename: &'a Path, } impl<'a> Finder<'a> { pub fn new() -> Self { Finder { filename: Path::new(".env"), } } pub fn filename(mut self, filename: &'a Path) -> Self { self.filename = filename; self } pub fn find(self) -> Result<(PathBuf, Iter)> { let path = find(&env::current_dir().map_err(Error::Io)?, self.filename)?; let file = File::open(&path).map_err(Error::Io)?; let iter = Iter::new(file); Ok((path, iter)) } } /// Searches for `filename` in `directory` and parent directories until found or root is reached. pub fn find(directory: &Path, filename: &Path) -> Result { let candidate = directory.join(filename); match fs::metadata(&candidate) { Ok(metadata) => { if metadata.is_file() { return Ok(candidate); } } Err(error) => { if error.kind() != io::ErrorKind::NotFound { return Err(Error::Io(error)); } } } if let Some(parent) = directory.parent() { find(parent, filename) } else { Err(Error::Io(io::Error::new( io::ErrorKind::NotFound, "path not found", ))) } } ``` -------------------------------- ### map_windows (Nightly) Source: https://docs.rs/dotenvy/latest/dotenvy/struct.Iter_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Calls a function for each contiguous window of size `N` and returns an iterator over the outputs. ```APIDOC ## fn map_windows(self, f: F) ### Description Calls the given function `f` for each contiguous window of size `N` over `self` and returns an iterator over the outputs of `f`. Like `slice::windows()`, the windows during mapping overlap as well. ### Method (Implicitly part of the Iterator trait, Nightly-only) ### Endpoint N/A (Method on Iterator trait) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Note: This is a nightly-only experimental API. // let data = vec![1, 2, 3, 4, 5]; // let result: Vec<_> = data.into_iter().map_windows::<_, _, 2>(|window| window[0] + window[1]).collect(); // Expected result (conceptually): [3, 5, 7, 9] ``` ### Response #### Success Response (200) N/A (This is a method call, not an HTTP endpoint) #### Response Example N/A ``` -------------------------------- ### Get Type ID Source: https://docs.rs/dotenvy/latest/dotenvy/struct.Iter_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the unique `TypeId` of a type. This is part of the `Any` trait implementation and is useful for dynamic type introspection. ```rust fn type_id(&self) -> TypeId where T: 'static + ?Sized, ``` -------------------------------- ### Iter Struct and Constructor Source: https://docs.rs/dotenvy/latest/dotenvy/struct.Iter Information about the Iter struct and how to create a new instance. ```APIDOC ## Iter Struct ```rust pub struct Iter { /* private fields */ } ``` ### Description A struct that iterates over environment variables read from a provided `R: Read` source. ### Constructor #### `new(reader: R) -> Iter` Creates a new `Iter` instance with the given reader. * **reader** (R) - The source to read environment variables from. Must implement the `Read` trait. ``` -------------------------------- ### Get Environment Variable Value Source: https://docs.rs/dotenvy/latest/dotenvy/fn.var_search=std%3A%3Avec Retrieves the value of an environment variable. The value must be valid Unicode. ```APIDOC ## GET /var ### Description Gets the value for an environment variable. The value is `Ok(s)` if the environment variable is present and valid unicode. Note: this function gets values from any visible environment variable key, regardless of whether a `.env` file was loaded. ### Method GET ### Endpoint /var ### Parameters #### Path Parameters - **key** (string) - Required - The environment variable key to retrieve. ### Request Example ```json { "key": "HOME" } ``` ### Response #### Success Response (200) - **value** (string) - The string value of the environment variable. #### Response Example ```json { "value": "/home/foo" } ``` ``` -------------------------------- ### take Source: https://docs.rs/dotenvy/latest/dotenvy/struct.Iter_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ```APIDOC ## fn take(self, n: usize) ### Description Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ### Method (Implicitly part of the Iterator trait) ### Endpoint N/A (Method on Iterator trait) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let numbers = vec![1, 2, 3, 4, 5]; let result: Vec<_> = numbers.into_iter().take(3).collect(); // result will be [1, 2, 3] ``` ### Response #### Success Response (200) N/A (This is a method call, not an HTTP endpoint) #### Response Example N/A ``` -------------------------------- ### dotenvy Core Functions Source: https://docs.rs/dotenvy/latest/dotenvy/all This section details the primary functions for loading environment variables using the dotenvy crate. ```APIDOC ## dotenvy API Documentation This document outlines the core functions provided by the `dotenvy` crate for managing environment variables in Rust applications. ### Functions #### `dotenv()` * **Description**: Loads environment variables from a `.env` file in the current directory or a parent directory. * **Method**: `POST` (Conceptual, as this is a function call, not a web request) * **Endpoint**: N/A (Rust function) #### `dotenv_override()` * **Description**: Loads environment variables from a `.env` file, overwriting existing variables. * **Method**: `POST` (Conceptual) * **Endpoint**: N/A #### `dotenv_iter()` * **Description**: Loads environment variables from a `.env` file and returns an iterator over the loaded variables. * **Method**: `POST` (Conceptual) * **Endpoint**: N/A #### `from_filename(filename)` * **Description**: Loads environment variables from a specific file. * **Method**: `POST` (Conceptual) * **Endpoint**: N/A * **Parameters**: * `filename` (string) - Required - The name of the file to load. #### `from_filename_override(filename)` * **Description**: Loads environment variables from a specific file, overwriting existing variables. * **Method**: `POST` (Conceptual) * **Endpoint**: N/A * **Parameters**: * `filename` (string) - Required - The name of the file to load. #### `from_filename_iter(filename)` * **Description**: Loads environment variables from a specific file and returns an iterator. * **Method**: `POST` (Conceptual) * **Endpoint**: N/A * **Parameters**: * `filename` (string) - Required - The name of the file to load. #### `from_path(path)` * **Description**: Loads environment variables from a file at a given path. * **Method**: `POST` (Conceptual) * **Endpoint**: N/A * **Parameters**: * `path` (Path) - Required - The path to the file. #### `from_path_override(path)` * **Description**: Loads environment variables from a file at a given path, overwriting existing variables. * **Method**: `POST` (Conceptual) * **Endpoint**: N/A * **Parameters**: * `path` (Path) - Required - The path to the file. #### `from_path_iter(path)` * **Description**: Loads environment variables from a file at a given path and returns an iterator. * **Method**: `POST` (Conceptual) * **Endpoint**: N/A * **Parameters**: * `path` (Path) - Required - The path to the file. #### `from_read(reader)` * **Description**: Loads environment variables from a reader. * **Method**: `POST` (Conceptual) * **Endpoint**: N/A * **Parameters**: * `reader` (Reader) - Required - The reader to load from. #### `from_read_override(reader)` * **Description**: Loads environment variables from a reader, overwriting existing variables. * **Method**: `POST` (Conceptual) * **Endpoint**: N/A * **Parameters**: * `reader` (Reader) - Required - The reader to load from. #### `from_read_iter(reader)` * **Description**: Loads environment variables from a reader and returns an iterator. * **Method**: `POST` (Conceptual) * **Endpoint**: N/A * **Parameters**: * `reader` (Reader) - Required - The reader to load from. #### `var(key)` * **Description**: Retrieves the value of an environment variable by key. * **Method**: `GET` (Conceptual) * **Endpoint**: N/A * **Parameters**: * `key` (string) - Required - The environment variable key. * **Response**: * `Ok(String)` or `Err(Error)` #### `vars()` * **Description**: Returns an iterator over all environment variables. * **Method**: `GET` (Conceptual) * **Endpoint**: N/A ### Structs #### `Iter` * **Description**: An iterator over loaded environment variables. ### Enums #### `Error` * **Description**: Represents errors that can occur during environment variable loading. ### Type Aliases #### `Result` * **Description**: A specialized `Result` type for dotenvy operations, typically `Result`. ``` -------------------------------- ### GET /var Source: https://docs.rs/dotenvy/latest/dotenvy/fn.var_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the value of a specified environment variable. This function can access any visible environment variable, not just those loaded from a .env file. ```APIDOC ## GET /var ### Description Retrieves the value of a specified environment variable. This function can access any visible environment variable, not just those loaded from a .env file. ### Method GET ### Endpoint /var ### Parameters #### Path Parameters None #### Query Parameters - **key** (string) - Required - The name of the environment variable to retrieve. #### Request Body None ### Request Example None ### Response #### Success Response (200) - **value** (string) - The string value of the environment variable if it exists and is valid unicode. #### Response Example ```json { "value": "/home/foo" } ``` ``` -------------------------------- ### dotenv() - Load .env file Source: https://docs.rs/dotenvy/latest/src/dotenvy/lib.rs_search=std%3A%3Avec Loads the .env file from the current directory or its parents, preserving existing environment variables. If multiple declarations exist for the same variable, the first one is applied. An error is returned if the file is not found. ```APIDOC ## GET /dotenv ### Description Loads the .env file from the current directory or parents, preserving existing environment variables. If multiple declarations exist for the same variable, the first one is applied. An error is returned if the file is not found. ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ``` // No request body needed for this operation ``` ### Response #### Success Response (200) - **path** (PathBuf) - The path to the loaded .env file. #### Response Example ```json { "path": "/path/to/.env" } ``` ``` -------------------------------- ### Skip Elements in an Iterator (Rust) Source: https://docs.rs/dotenvy/latest/dotenvy/struct.Iter_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates an iterator that skips a specified number of initial elements. This is useful when you want to process an iterator starting from a certain point. ```Rust fn skip(self, n: usize) -> Skip where Self: Sized ``` -------------------------------- ### var - Get Environment Variable Source: https://docs.rs/dotenvy/latest/src/dotenvy/lib.rs Retrieves the value of an environment variable. It first ensures that environment variables are loaded (if not already) and then fetches the specified variable. ```APIDOC ## GET /var ### Description Gets the value for an environment variable. The value is `Ok(s)` if the environment variable is present and valid unicode. This function gets values from any visible environment variable key, regardless of whether a *.env* file was loaded. ### Method GET ### Endpoint /var ### Parameters #### Path Parameters None #### Query Parameters - **key** (K: AsRef) - Required - The key of the environment variable to retrieve. ### Request Body None ### Request Example ```rust let value = dotenvy::var("HOME")?; println!("{}", value); // prints `/home/foo` ``` ### Response #### Success Response (200) - **String** - The value of the environment variable if found and valid. #### Response Example ```json { "value": "/home/foo" } ``` ``` -------------------------------- ### Iter Constructor and Loading Methods in Rust Source: https://docs.rs/dotenvy/latest/dotenvy/struct.Iter_search=u32+-%3E+bool Provides methods for creating an `Iter` instance and loading environment variables. `new` creates an iterator from a `Read` source, `load` applies variables without overriding existing ones, and `load_override` overwrites existing variables. ```rust pub fn new(reader: R) -> Iter Loads all variables found in the `reader` into the environment, preserving any existing environment variables of the same name. If a variable is specified multiple times within the reader’s data, then the first occurrence is applied. pub fn load(self) -> Result<()> Loads all variables found in the `reader` into the environment, overriding any existing environment variables of the same name. If a variable is specified multiple times within the reader’s data, then the last occurrence is applied. pub fn load_override(self) -> Result<()> ``` -------------------------------- ### Get Nth Environment Variable - Rust Source: https://docs.rs/dotenvy/latest/dotenvy/struct.Iter_search= The `nth` method returns the `n`th element of the iterator. Note that this consumes elements up to the `n`th one. ```rust fn nth(&mut self, n: usize) -> Option ``` -------------------------------- ### Iterating and Loading Environment Variables with dotenvy Source: https://docs.rs/dotenvy/latest/src/dotenvy/iter.rs_search=std%3A%3Avec Provides functionality to iterate over lines from a reader and load them as environment variables. Supports loading that preserves existing variables or overrides them. Handles quoted strings and comments. Requires `std::collections::HashMap`, `std::env`, `std::io`, and custom `crate::errors` and `crate::parse` modules. ```rust use std::collections::HashMap; use std::env; use std::io::prelude::*; use std::io::BufReader; use crate::errors::*; use crate::parse; pub struct Iter { lines: QuotedLines>, substitution_data: HashMap>, } impl Iter { pub fn new(reader: R) -> Iter { Iter { lines: QuotedLines { buf: BufReader::new(reader), }, substitution_data: HashMap::new(), } } /// Loads all variables found in the `reader` into the environment, /// preserving any existing environment variables of the same name. /// /// If a variable is specified multiple times within the reader's data, /// then the first occurrence is applied. pub fn load(mut self) -> Result<() > { self.remove_bom()?; for item in self { let (key, value) = item?; if env::var(&key).is_err() { env::set_var(&key, value); } } Ok(()) } /// Loads all variables found in the `reader` into the environment, /// overriding any existing environment variables of the same name. /// /// If a variable is specified multiple times within the reader's data, /// then the last occurrence is applied. pub fn load_override(mut self) -> Result<() > { self.remove_bom()?; for item in self { let (key, value) = item?; env::set_var(key, value); } Ok(()) } fn remove_bom(&mut self) -> Result<() > { let buffer = self.lines.buf.fill_buf().map_err(Error::Io)?; // https://www.compart.com/en/unicode/U+FEFF if buffer.starts_with(&[0xEF, 0xBB, 0xBF]) { // remove the BOM from the bufreader self.lines.buf.consume(3); } Ok(()) } } struct QuotedLines { buf: B, } enum ParseState { Complete, Escape, StrongOpen, StrongOpenEscape, WeakOpen, WeakOpenEscape, Comment, WhiteSpace, } fn eval_end_state(prev_state: ParseState, buf: &str) -> (usize, ParseState) { let mut cur_state = prev_state; let mut cur_pos: usize = 0; for (pos, c) in buf.char_indices() { cur_pos = pos; cur_state = match cur_state { ParseState::WhiteSpace => match c { '#' => return (cur_pos, ParseState::Comment), '\' => ParseState::Escape, '"' => ParseState::WeakOpen, ''' => ParseState::StrongOpen, _ => ParseState::Complete, }, ParseState::Escape => ParseState::Complete, ParseState::Complete => match c { c if c.is_whitespace() && c != '\n' && c != '\r' => ParseState::WhiteSpace, '\' => ParseState::Escape, '"' => ParseState::WeakOpen, ''' => ParseState::StrongOpen, _ => ParseState::Complete, }, ParseState::WeakOpen => match c { '\' => ParseState::WeakOpenEscape, '"' => ParseState::Complete, _ => ParseState::WeakOpen, }, ParseState::WeakOpenEscape => ParseState::WeakOpen, ParseState::StrongOpen => match c { '\' => ParseState::StrongOpenEscape, ''' => ParseState::Complete, _ => ParseState::StrongOpen, }, ParseState::StrongOpenEscape => ParseState::StrongOpen, // Comments last the entire line. ParseState::Comment => panic!("should have returned early"), }; } (cur_pos, cur_state) } impl Iterator for QuotedLines { type Item = Result; fn next(&mut self) -> Option> { let mut buf = String::new(); let mut cur_state = ParseState::Complete; let mut buf_pos; let mut cur_pos; loop { buf_pos = buf.len(); match self.buf.read_line(&mut buf) { Ok(0) => match cur_state { ParseState::Complete => return None, _ => { let len = buf.len(); return Some(Err(Error::LineParse(buf, len))); } }, Ok(_n) => { // Skip lines which start with a # before iteration // This optimizes parsing a bit. if buf.trim_start().starts_with('#') { return Some(Ok(String::with_capacity(0))); } } Err(e) => return Some(Err(Error::Io(e))), } } } } ``` -------------------------------- ### Get Last Environment Variable - Rust Source: https://docs.rs/dotenvy/latest/dotenvy/struct.Iter_search= The `last` method consumes the iterator and returns the last environment variable yielded. If the iterator is empty, it returns `None`. ```rust fn last(self) -> Option where Self: Sized, ``` -------------------------------- ### dotenvy Crate Functions Source: https://docs.rs/dotenvy/latest/dotenvy_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This section details the functions available in the dotenvy crate for loading environment variables. ```APIDOC ## Functions ### dotenv **Description:** Loads the `.env` file from the current directory or parents. This is typically what you want. **Usage:** `dotenvy::dotenv()` ### dotenv_iter **Description:** Returns an iterator over environment variables. **Usage:** `dotenvy::dotenv_iter()` ### dotenv_override **Description:** Loads all variables found in the `reader` into the environment, overriding any existing environment variables of the same name. **Usage:** `dotenvy::dotenv_override()` ### from_filename **Description:** Loads environment variables from the specified file. **Usage:** `dotenvy::from_filename(filename)` ### from_filename_iter **Description:** Returns an iterator over environment variables from the specified file. **Usage:** `dotenvy::from_filename_iter(filename)` ### from_filename_override **Description:** Loads environment variables from the specified file, overriding existing environment variables. **Usage:** `dotenvy::from_filename_override(filename)` ### from_path **Description:** Loads environment variables from the specified path. **Usage:** `dotenvy::from_path(path)` ### from_path_iter **Description:** Returns an iterator over environment variables from the specified path. **Usage:** `dotenvy::from_path_iter(path)` ### from_path_override **Description:** Loads environment variables from the specified path, overriding existing environment variables. **Usage:** `dotenvy::from_path_override(path)` ### from_read **Description:** Loads environment variables from `io::Read`. **Usage:** `dotenvy::from_read(reader)` ### from_read_iter **Description:** Returns an iterator over environment variables from `io::Read`. **Usage:** `dotenvy::from_read_iter(reader)` ### from_read_override **Description:** Loads environment variables from `io::Read`, overriding existing environment variables. **Usage:** `dotenvy::from_read_override(reader)` ### var **Description:** Gets the value for an environment variable. **Usage:** `dotenvy::var(key)` ### vars **Description:** Returns an iterator of `(key, value)` pairs for all environment variables of the current process. The returned iterator contains a snapshot of the process’s environment variables at the time of invocation. Modifications to environment variables afterwards will not be reflected. **Usage:** `dotenvy::vars()` ``` -------------------------------- ### dotenvy::from_path Source: https://docs.rs/dotenvy/latest/dotenvy/fn.from_path_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Loads environment variables from a specified file path. Existing environment variables are preserved, and the first declaration of a variable in the file is applied. ```APIDOC ## from_path ### Description Loads environment variables from the specified path. If variables with the same names already exist in the environment, then their values will be preserved. Where multiple declarations for the same environment variable exist in your .env file, the first one is applied. If you wish to ensure all variables are loaded from your .env file, ignoring variables already existing in the environment, then use `from_path_override` instead. ### Method `pub fn from_path>(path: P) -> Result<()>` ### Parameters #### Path Parameters - **path** (P: AsRef) - Required - The path to the .env file. ### Request Example ```rust use std::path::Path; dotenvy::from_path(Path::new("path/to/.env"))?; ``` ### Response #### Success Response (200) - **Result**<()> - Indicates successful loading of environment variables. #### Response Example ```json // No specific JSON response, function returns a Result type. // Success is indicated by the absence of an error. ``` ``` -------------------------------- ### Get Environment Variable Source: https://docs.rs/dotenvy/latest/dotenvy/fn.var Retrieves the value of an environment variable. It can access any visible environment variable, even if no .env file has been loaded. ```APIDOC ## GET /var ### Description Gets the value for an environment variable. The value is `Ok(s)` if the environment variable is present and valid unicode. This function gets values from any visible environment variable key, regardless of whether a _.env_ file was loaded. ### Method GET ### Endpoint /var ### Parameters #### Query Parameters - **key** (string) - Required - The environment variable key to retrieve. ### Request Example ```json { "key": "HOME" } ``` ### Response #### Success Response (200) - **value** (string) - The string value of the environment variable if found and valid unicode. #### Response Example ```json { "value": "/home/foo" } ``` ``` -------------------------------- ### dotenvy::from_path Source: https://docs.rs/dotenvy/latest/dotenvy/fn.from_path_search= Loads environment variables from a specified file path. Existing environment variables are preserved, and the first declaration in the file takes precedence. ```APIDOC ## from_path ### Description Loads environment variables from the specified path. If variables with the same names already exist in the environment, then their values will be preserved. Where multiple declarations for the same environment variable exist in your `.env` file, the *first one* is applied. If you wish to ensure all variables are loaded from your `.env` file, ignoring variables already existing in the environment, then use `from_path_override` instead. ### Method ```rust pub fn from_path>(path: P) -> Result<()> ``` ### Parameters #### Path Parameters - **path** (*P: AsRef*) - Required - The path to the environment file. ### Request Example ```rust use std::path::Path; dotenvy::from_path(Path::new("path/to/.env"))?; ``` ### Response #### Success Response (200) - **Success** (*()*) - Indicates the environment variables were loaded successfully. #### Error Response - **Error** (*dotenvy::Error*) - Indicates an error occurred during loading. ``` -------------------------------- ### Get mutable references from Result Source: https://docs.rs/dotenvy/latest/dotenvy/type.Result_search=u32+-%3E+bool The `as_mut` method converts a mutable reference to a Result into a Result of mutable references. This allows modifying the contained value or error in place. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### dotenvy Core Functions Source: https://docs.rs/dotenvy/latest/dotenvy/all_search=u32+-%3E+bool This section details the primary functions for loading environment variables from .env files. ```APIDOC ## dotenv ### Description Loads environment variables from a `.env` file in the current directory or in a parent directory. ### Method `fn dotenv() -> dotenvy::Result<()>` ### Endpoint N/A (local file operation) ### Parameters None ### Request Example N/A ### Response #### Success Response (200) Returns `Ok(())` on successful loading. #### Response Example ``` Ok(()) ``` ## dotenv_iter ### Description Loads environment variables from a `.env` file as an iterator. ### Method `fn dotenv_iter<'a>() -> dotenvy::Result>>` ### Endpoint N/A (local file operation) ### Parameters None ### Request Example N/A ### Response #### Success Response (200) Returns an iterator yielding `Result<(String, String)>` for each key-value pair. #### Response Example ``` // Example of iterating through results for pair in dotenv_iter()? { let (key, value) = pair?; println!("{} = {}", key, value); } ``` ## dotenv_override ### Description Loads environment variables from a `.env` file, overriding existing variables. ### Method `fn dotenv_override() -> dotenvy::Result<()>` ### Endpoint N/A (local file operation) ### Parameters None ### Request Example N/A ### Response #### Success Response (200) Returns `Ok(())` on successful loading. #### Response Example ``` Ok(()) ``` ## from_filename ### Description Loads environment variables from a specified file name. ### Method `fn from_filename(filename: impl AsRef) -> dotenvy::Result<()>` ### Endpoint N/A (local file operation) ### Parameters * **filename** (String or Path) - Required - The name of the file to load environment variables from. ### Request Example ```rust dotenvy::from_filename(".env.prod").unwrap(); ``` ### Response #### Success Response (200) Returns `Ok(())` on successful loading. #### Response Example ``` Ok(()) ``` ## from_filename_iter ### Description Loads environment variables from a specified file name as an iterator. ### Method `fn from_filename_iter<'a>(filename: impl AsRef) -> dotenvy::Result>>` ### Endpoint N/A (local file operation) ### Parameters * **filename** (String or Path) - Required - The name of the file to load environment variables from. ### Request Example N/A ### Response #### Success Response (200) Returns an iterator yielding `Result<(String, String)>` for each key-value pair. #### Response Example ```rust // Example of iterating through results from a specific file for pair in dotenvy::from_filename_iter(".env.dev")? { let (key, value) = pair?; println!("{} = {}", key, value); } ``` ## from_filename_override ### Description Loads environment variables from a specified file name, overriding existing variables. ### Method `fn from_filename_override(filename: impl AsRef) -> dotenvy::Result<()>` ### Endpoint N/A (local file operation) ### Parameters * **filename** (String or Path) - Required - The name of the file to load environment variables from. ### Request Example ```rust dotenvy::from_filename_override(".env.test").unwrap(); ``` ### Response #### Success Response (200) Returns `Ok(())` on successful loading. #### Response Example ``` Ok(()) ``` ## from_path ### Description Loads environment variables from a specified path to a file. ### Method `fn from_path(path: impl AsRef) -> dotenvy::Result<()>` ### Endpoint N/A (local file operation) ### Parameters * **path** (String or Path) - Required - The full path to the file containing environment variables. ### Request Example ```rust use std::path::Path; dotenvy::from_path(Path::new("/path/to/your/.env")).unwrap(); ``` ### Response #### Success Response (200) Returns `Ok(())` on successful loading. #### Response Example ``` Ok(()) ``` ## from_path_iter ### Description Loads environment variables from a specified path to a file as an iterator. ### Method `fn from_path_iter<'a>(path: impl AsRef) -> dotenvy::Result>>` ### Endpoint N/A (local file operation) ### Parameters * **path** (String or Path) - Required - The full path to the file containing environment variables. ### Request Example N/A ### Response #### Success Response (200) Returns an iterator yielding `Result<(String, String)>` for each key-value pair. #### Response Example ```rust use std::path::Path; for pair in dotenvy::from_path_iter(Path::new("/path/to/your/.env"))? { let (key, value) = pair?; println!("{} = {}", key, value); } ``` ## from_path_override ### Description Loads environment variables from a specified path to a file, overriding existing variables. ### Method `fn from_path_override(path: impl AsRef) -> dotenvy::Result<()>` ### Endpoint N/A (local file operation) ### Parameters * **path** (String or Path) - Required - The full path to the file containing environment variables. ### Request Example ```rust use std::path::Path; dotenvy::from_path_override(Path::new("/path/to/your/.env")).unwrap(); ``` ### Response #### Success Response (200) Returns `Ok(())` on successful loading. #### Response Example ``` Ok(()) ``` ## from_read ### Description Loads environment variables from a reader implementing `std::io::Read`. ### Method `fn from_read(reader: impl std::io::Read) -> dotenvy::Result<()>` ### Endpoint N/A (in-memory reader operation) ### Parameters * **reader** (std::io::Read) - Required - An object that implements the `Read` trait. ### Request Example ```rust use std::io::Cursor; let data = "KEY=VALUE\nANOTHER_KEY=ANOTHER_VALUE"; let reader = Cursor::new(data); dotenvy::from_read(reader).unwrap(); ``` ### Response #### Success Response (200) Returns `Ok(())` on successful loading. #### Response Example ``` Ok(()) ``` ## from_read_iter ### Description Loads environment variables from a reader implementing `std::io::Read` as an iterator. ### Method `fn from_read_iter<'a>(reader: impl std::io::Read + 'a) -> dotenvy::Result>>` ### Endpoint N/A (in-memory reader operation) ### Parameters * **reader** (std::io::Read) - Required - An object that implements the `Read` trait. ### Request Example N/A ### Response #### Success Response (200) Returns an iterator yielding `Result<(String, String)>` for each key-value pair. #### Response Example ```rust use std::io::Cursor; let data = "KEY=VALUE\nANOTHER_KEY=ANOTHER_VALUE"; let reader = Cursor::new(data); for pair in dotenvy::from_read_iter(reader)? { let (key, value) = pair?; println!("{} = {}", key, value); } ``` ## from_read_override ### Description Loads environment variables from a reader implementing `std::io::Read`, overriding existing variables. ### Method `fn from_read_override(reader: impl std::io::Read) -> dotenvy::Result<()>` ### Endpoint N/A (in-memory reader operation) ### Parameters * **reader** (std::io::Read) - Required - An object that implements the `Read` trait. ### Request Example ```rust use std::io::Cursor; let data = "KEY=VALUE\nANOTHER_KEY=ANOTHER_VALUE"; let reader = Cursor::new(data); dotenvy::from_read_override(reader).unwrap(); ``` ### Response #### Success Response (200) Returns `Ok(())` on successful loading. #### Response Example ``` Ok(()) ``` ## var ### Description Retrieves the value of an environment variable. ### Method `fn var(key: &str) -> Option` ### Endpoint N/A (environment variable access) ### Parameters * **key** (str) - Required - The name of the environment variable to retrieve. ### Request Example ```rust match dotenvy::var("MY_VARIABLE") { Some(val) => println!("MY_VARIABLE is set to: {}", val), None => println!("MY_VARIABLE is not set."), } ``` ### Response #### Success Response (200) Returns `Some(String)` containing the value if the environment variable is set, otherwise `None`. #### Response Example ``` Some("some_value") ``` ## vars ### Description Returns an iterator over the environment variables. ### Method `fn vars() -> impl Iterator` ### Endpoint N/A (environment variable access) ### Parameters None ### Request Example N/A ### Response #### Success Response (200) Returns an iterator yielding `(String, String)` tuples for each environment variable. #### Response Example ```rust for (key, value) in dotenvy::vars() { println!("{} = {}", key, value); } ``` ```