### Runtime Macro: Full Configuration Example Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/macros.md A comprehensive example combining custom path, required flag, override flag, and usage with an async function. ```rust #[dotenvy::load(path = ".env.staging", required = true, override_ = false)] #[tokio::main] async fn main() { // Code here } ``` -------------------------------- ### Example .env File Configuration Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md A comprehensive example of a .env file demonstrating various configurations including database settings, application parameters, derived values, optional features, and multiline private keys. ```env # Database configuration DATABASE_URL=postgres://user:pass@localhost/dbname DB_HOST=localhost DB_PORT=5432 # Application settings APP_NAME=MyApp APP_ENV=development # Derived values API_BASE_URL=http://${DB_HOST}:8080 # Optional values OPTIONAL_FEATURE=disabled # Private keys (multiline) SIGNING_KEY="-----BEGIN KEY----- ...key content... -----END KEY-----" ``` -------------------------------- ### Run npm start with full .env configuration Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Applies a comprehensive configuration, specifying the file path, requirement, and override behavior. ```sh dotenvy --file .env.production --required true --override true npm start ``` -------------------------------- ### Rust Example: Basic Retrieval of HOME environment variable Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/functions.md Shows a basic example of retrieving the 'HOME' environment variable using `dotenvy::var()` and handling potential errors with the `?` operator. ```rust use dotenvy; fn main() -> Result<(), Box> { let home = dotenvy::var("HOME")?; println!("Home directory: {}", home); Ok(()) } ``` -------------------------------- ### Basic .env File Parsing Example Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/parsing-and-substitution.md Illustrates a basic .env file with configuration settings and the resulting parsed key-value pairs. ```env # Database configuration DATABASE_URL=postgres://user:pass@localhost/db DB_PORT=5432 DB_SSL=true # Application settings APP_NAME=MyApp APP_ENV=development ``` ```rust [ ("DATABASE_URL", "postgres://user:pass@localhost/db"), ("DB_PORT", "5432"), ("DB_SSL", "true"), ("APP_NAME", "MyApp"), ("APP_ENV", "development"), ] ``` -------------------------------- ### Run npm start with a custom .env file Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Specifies a custom path to the .env file to be loaded. ```sh dotenvy --file .env.production npm start ``` -------------------------------- ### Python Example with dotenvy Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/cli.md Shows how to use dotenvy to load environment variables and then access them within a Python script. This example assumes 'DATABASE_URL' is set in the .env file. ```sh dotenvy python3 -c "import os; print(os.environ['DATABASE_URL'])" ``` -------------------------------- ### Run npm start with an optional .env file Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Loads a specified .env file, but does not fail if the file is not found. ```sh dotenvy --file .env.local --required false npm start ``` -------------------------------- ### BOM Handling Example Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/parsing-and-substitution.md Illustrates the automatic removal of the UTF-8 Byte Order Mark (BOM) if it is present at the beginning of the .env file. The example shows the raw bytes before and after removal. ```text File: EF BB BF 48 45 4C 4C 4F (UTF-8 BOM + "HELLO") After BOM removal: 48 45 4C 4C 4F ("HELLO") ``` -------------------------------- ### EnvSequence Usage Examples Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/types.md Demonstrates configuring EnvLoader with different EnvSequence variants for various environments. ```rust use dotenvy::{EnvLoader, EnvSequence}; // Development: input takes precedence, but environment can override let dev_loader = EnvLoader::new() .sequence(EnvSequence::InputThenEnv); // Production: environment variables take precedence let prod_loader = EnvLoader::new() .sequence(EnvSequence::EnvThenInput); // Testing: isolated environment let test_loader = EnvLoader::new() .sequence(EnvSequence::InputOnly); ``` -------------------------------- ### Run npm start with default .env file Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Loads the default .env file and allows environment variables to override its settings. ```sh dotenvy npm start ``` -------------------------------- ### Basic Usage Example Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/cli.md Demonstrates loading environment variables from a specified file and executing a command to print one of those variables. Assumes 'env.txt' contains 'HOST=localhost' and 'PORT=5432'. ```sh dotenvy -f env.txt printenv HOST # Output: localhost ``` -------------------------------- ### Example .env file format Source: https://github.com/allan2/dotenvy/blob/main/README.md Demonstrates the basic key-value pair format for environment variables in an .env file. Variables can span multiple lines and support substitution. ```shell HOST=foo PORT=3000 ``` -------------------------------- ### Export as Key Example Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/parsing-and-substitution.md Demonstrates the special case where 'export' itself is used as a key name, followed by an equals sign and a value. This results in a key-value pair where the key is 'export'. ```env export=yes ``` -------------------------------- ### Run npm start with file-priority configuration Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Ensures that variables in the specified .env file take precedence over existing environment variables. ```sh dotenvy --override true npm start ``` -------------------------------- ### Variable Substitution Parsing Example Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/parsing-and-substitution.md Demonstrates parsing a .env file with variable substitutions, showing how environment variables are resolved or left empty if undefined. ```env HOST=localhost PORT=3000 DEBUG=true DATABASE_URL=postgres://$HOST:$PORT/myapp API_URL=http://$HOST:$PORT REPORT_PATH=/var/log/$APP_ENV/report.log ``` ```rust [ ("HOST", "localhost"), ("PORT", "3000"), ("DEBUG", "true"), ("DATABASE_URL", "postgres://localhost:3000/myapp"), ("API_URL", "http://localhost:3000"), ("REPORT_PATH", "/var/log//report.log"), // APP_ENV undefined -> "" ] ``` -------------------------------- ### EnvLoader: Complete Configuration Example Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Demonstrates file-based, reader-based, and default configurations for EnvLoader. Use file-based for typical .env file loading and reader-based for custom input streams. The default configuration loads from './.env' with InputThenEnv sequence. ```rust use dotenvy::{EnvLoader, EnvSequence}; use std::fs::File; // File-based configuration let loader = EnvLoader::with_path(".env.production") .sequence(EnvSequence::EnvThenInput); // Reader-based configuration let file = File::open(".env.staging")?; let loader = EnvLoader::with_reader(file) .path(".env.staging") .sequence(EnvSequence::InputThenEnv); // Default configuration let loader = EnvLoader::new(); // equivalent to: // EnvLoader::with_path("./.env").sequence(EnvSequence::InputThenEnv) ``` -------------------------------- ### Rust Example: Using var() to get USER environment variable Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/functions.md Demonstrates how to use the `dotenvy::var()` function to retrieve the 'USER' environment variable and handle potential errors like the variable not being set or containing invalid UTF-8. ```rust use dotenvy; fn main() { match dotenvy::var("USER") { Ok(user) => println!("Running as: {}", user), Err(dotenvy::Error::NotPresent(name)) => { eprintln!("Variable {} is not set", name); } Err(e) => eprintln!("Error: {}", e), } } ``` -------------------------------- ### dotenvy .env File Format Examples Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/INDEX.md Illustrates the various ways to define key-value pairs in a .env file, including comments, simple keys, quoted values, escaped spaces, variable substitution, and multiline values. ```env # Comments (start with #) # Simple key-value KEY=value # Quoted values SINGLE='no substitution' DOUBLE="substitution: $VAR" # Escaped spaces ESCAPED=value\ with\ spaces # Variable substitution HOST=localhost URL=http://$HOST:8080 # Multiline (double quotes) JSON="{ \"key\": \"value\" }" ``` -------------------------------- ### Correct Usage for NoInput Scenario Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/errors.md Provides examples of correct EnvLoader configuration to avoid Error::NoInput, including using new() for the default path or explicitly setting a path or reader. ```rust use dotenvy::EnvLoader; // Either use new() for default path let loader = EnvLoader::new(); // Or explicitly set a path let loader = EnvLoader::with_path(".env.local"); // Or provide a reader use std::io::Cursor; let loader = EnvLoader::with_reader(Cursor::new("KEY=value")); ``` -------------------------------- ### Valid and Invalid Keys in .env Files Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/parsing-and-substitution.md Demonstrates the naming rules for keys in .env files, showing valid and invalid examples according to character restrictions and placement. ```env # Valid keys DATABASE_URL=value DB_HOST=localhost _INTERNAL_VAR=hidden KEY.WITH.DOTS=value KEY_WITH_UNDERSCORE=value KEY123=value # Invalid keys 123KEY=value # ERROR: must start with letter or _ KEY-NAME=value # ERROR: hyphen not allowed KEY NAME=value # ERROR: space not allowed .KEY=value # ERROR: must start with letter or _ KEY/NAME=value # ERROR: slash not allowed ``` -------------------------------- ### Comments in .env file Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Shows how to add comments to .env files. Lines starting with '#' are ignored, and comments can also appear after code. ```env # This is a comment HOST=localhost # This is also a comment KEY="value" # Comment after quoted value ``` -------------------------------- ### Runtime Macro: Optional Loading Configuration Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/macros.md Example of configuring #[dotenvy::load] to ignore missing .env files by setting `required = false`. ```rust #[dotenvy::load(required = false)] fn main() { // Code here } ``` -------------------------------- ### Rust Example: Loading and Accessing DATABASE_URL Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/functions.md Illustrates loading environment variables from an .env file using `EnvLoader` and then accessing 'DATABASE_URL' via `dotenvy::var()`. This requires unsafe block for `load_and_modify`. ```rust use dotenvy::{EnvLoader, var}; fn main() -> Result<(), Box> { // Load from env file and modify process environment let loader = EnvLoader::new(); unsafe { loader.load_and_modify() }?; // Now access via dotenvy::var() let database_url = var("DATABASE_URL")?; println!("Database: {}", database_url); Ok(()) } ``` -------------------------------- ### CLI Binary Argument Parsing Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/modules.md Example of how the CLI binary parses arguments using `clap`. Supports specifying the environment file path, whether it's required, and if it should override existing variables. ```rust let matches = clap::Command::new("dotenvy") .arg(Arg::new("file") .short('f') .long("file") .default_value("./.env") .help("Path to env file")) .arg(Arg::new("required") .long("required") .action(ArgAction::SetTrue) .default_missing_value("true") .help("Fail if file not found")) .arg(Arg::new("override") .long("override") .action(ArgAction::SetTrue) .help("File overrides environment")) .get_matches(); ``` -------------------------------- ### Quoting and Escaping Parsing Example Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/parsing-and-substitution.md Shows the parsed results for various quoting and escaping scenarios, highlighting potential parse errors and literal interpretations. ```env UNQUOTED=value with spaces # ERROR: space terminates ESCAPED=value\ with\ spaces SINGLE='value with spaces' DOUBL E="value with spaces" ESCAPED_QUOTE="He said \"hello\"" BACKSLASH="C:\\Users\\Name" ``` ```rust // UNQUOTED causes parse error at "with" ("ESCAPED", "value with spaces"), ("SINGLE", "value with spaces"), ("DOUBLE", "value with spaces"), ("ESCAPED_QUOTE", "He said \"hello\""), ("BACKSLASH", "C:\\Users\\Name"), ``` -------------------------------- ### Compile-Time Macro Example Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/macros.md Shows how to use the `dotenv!` macro in `Cargo.toml` and Rust code to embed an environment variable's value as a compile-time constant. ```rust // In Cargo.toml [dependencies] dotenvy_macro = "0.15" // In code use dotenvy_macro::dotenv; const DATABASE_URL: &str = dotenv!("DATABASE_URL"); fn main() { println!("Connecting to: {}", DATABASE_URL); } ``` -------------------------------- ### Rust Example: Graceful Fallback for Configuration Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/functions.md Provides a function `get_config` that attempts to retrieve an environment variable using `dotenvy::var()`. If the variable is not found, it returns a provided default value. ```rust use dotenvy; fn get_config(key: &str, default: &str) -> String { dotenvy::var(key) .map(|v| v) .unwrap_or_else(|_| default.to_string()) } fn main() { let timeout = get_config("REQUEST_TIMEOUT", "30000"); println!("Timeout: {} ms", timeout); } ``` -------------------------------- ### Multiline JSON Configuration Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/parsing-and-substitution.md Example of defining a multiline JSON configuration within double quotes, preserving formatting and allowing for escaped quotes. ```env # Value spans multiple lines JSON_CONFIG="{ \"key\": \"value\", \"nested\": true }" ``` -------------------------------- ### Double-Quoted Values in .env Files Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/parsing-and-substitution.md Demonstrates double-quoted values, which support variable substitution and escape sequences. Covers examples of quotes, backslashes, newlines, and multi-line strings. ```env KEY="simple" # Value: "simple" KEY="with spaces" # Value: "with spaces" KEY="path to $FILE" # Value: "path to /usr/bin/python" (if FILE=/usr/bin/python) KEY="escaped \" quote" # Value: "escaped " quote" KEY="backslash \\ test" # Value: "backslash \ test" KEY="line 1\nline 2" # Value: "line 1\nline 2" (with actual newline) KEY="multi line" # Value: "multi\nline" (actual newline) ``` -------------------------------- ### Numeric and Boolean Values Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/parsing-and-substitution.md Provides examples of numeric and boolean-like values. All values, regardless of their apparent type, are stored as strings by the parser. Type conversion is left to the application. ```env PORT=5432 TIMEOUT=30000 ENABLED=true DISABLED=false RATIO=0.99 ``` -------------------------------- ### Mixed Quoting and Substitution Example Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/parsing-and-substitution.md Demonstrates how single quotes, double quotes, and unquoted strings affect variable substitution. Single quotes prevent substitution, while double quotes and unquoted strings perform it. Braced substitutions are also shown. ```env VAR=hello SINGLE='$VAR' DOUBLE="$VAR" UNQUOTED=$VAR BRACED="${VAR} world" ``` ```rust ("VAR", "hello"), ("SINGLE", "$VAR"), // No substitution in single quotes ("DOUBLE", "hello"), // Substitution in double quotes ("UNQUOTED", "hello"), // Substitution unquoted ("BRACED", "hello world") // Substitution with braces ``` -------------------------------- ### Access EnvMap as a HashMap via Deref Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/env-map.md EnvMap implements the `Deref` trait, allowing you to access its underlying `HashMap` methods directly, such as `get()`. ```rust let env_map = EnvLoader::new().load()?; if let Some(host) = env_map.get("HOST") { println!("HOST: {}", host); } ``` -------------------------------- ### Add dotenvy Dependency (With All Features) Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Enable all available features for dotenvy, including 'macros' and 'cli', for maximum functionality. ```toml [dependencies] dotenvy = { version = "0.15", features = ["macros", "cli"] } ``` -------------------------------- ### EnvLoader Methods Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/modules.md Demonstrates various methods for configuring and loading environment variables using the EnvLoader builder pattern. Use `new()` for defaults, `with_path()` for specific files, or `with_reader()` for custom input. ```rust let env_map = EnvLoader::new() .with_path("./.env.test") .sequence(EnvSequence::Wrap) .load()?; ``` ```rust let env_map = EnvLoader::new() .with_reader(std::io::Cursor::new("KEY=value")) .load()?; ``` ```rust let env_map = EnvLoader::new() .path("./.env.test") .load()?; ``` -------------------------------- ### #[dotenvy::load] Macro: Full Configuration Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Applies a full configuration to the #[dotenvy::load] macro for a production environment. It requires the '.env.production' file to exist and its variables to override the existing environment. ```rust #[dotenvy::load(path = ".env.production", required = true, override_ = true)] #[tokio::main] async fn main() { // Production settings: required file, file overrides environment } ``` -------------------------------- ### Configurable dotenvy::load macro Source: https://github.com/allan2/dotenvy/blob/main/README.md Demonstrates the default configuration for the `dotenvy::load` macro, specifying path, required status, and override behavior. ```rust #[dotenvy::load(path = "./env", required = true, override_ = false)] ``` -------------------------------- ### Runtime Macro: Custom Path Configuration Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/macros.md Shows how to specify a custom path for the .env file using the `path` parameter in #[dotenvy::load]. ```rust #[dotenvy::load(path = ".env.production")] fn main() { // Code here } ``` -------------------------------- ### Runtime Loading Configuration: From File Source: https://github.com/allan2/dotenvy/blob/main/dotenvy/README.md Configures the EnvLoader to load variables from a specific file path and specifies the order of precedence between input file and existing environment variables. ```rs let loader1 = EnvLoader::with_path("./.env").sequence(EnvSequence::InputThenEnv); let loader2 = EnvLoader::new(); // shorthand for loader1 ``` -------------------------------- ### Check for optional variable existence in EnvMap Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/env-map.md Use the `get()` method (available via `Deref`) to check if an optional environment variable exists in the `EnvMap`. This returns an `Option<&String>`. ```rust use dotenvy::EnvLoader; fn main() -> Result<(), Box> { let env_map = EnvLoader::new().load()?; if let Some(value) = env_map.get("OPTIONAL_VAR") { println!("OPTIONAL_VAR: {}", value); } Ok(()) } ``` -------------------------------- ### dotenvy CLI Usage Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/cli.md The basic syntax for using the dotenvy CLI tool. Specify options and the command to execute. ```sh dotenvy [OPTIONS] ``` -------------------------------- ### Rust Development vs Production Configuration Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/README.md Demonstrates how to configure dotenvy to prioritize environment variables over file content for development, or file content over environment variables for production. ```rust use dotenvy::{EnvLoader, EnvSequence}; // Development: environment can override file let env_map = EnvLoader::new() .sequence(EnvSequence::InputThenEnv) .load()?; // Production: file takes precedence let env_map = EnvLoader::new() .sequence(EnvSequence::EnvThenInput) .load()?; ``` -------------------------------- ### Add dotenvy Dependency (With CLI) Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Configure dotenvy with the 'cli' feature to enable command-line interface capabilities. This also includes a binary definition. ```toml [dependencies] dotenvy = { version = "0.15", features = ["cli"] } [[bin]] name = "dotenvy" path = "src/bin/dotenvy.rs" ``` -------------------------------- ### CLI Tool Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/README.md The `dotenvy` command-line interface tool loads a specified .env file and then executes a given command. It provides options to customize the .env file path, requirement, and override behavior. ```APIDOC ## CLI Tool ### Description The `dotenvy` binary is a command-line tool that loads environment variables from a specified `.env` file and then executes a given command. It simplifies the process of managing environment-specific configurations for applications. ### Usage ```sh dotenvy [OPTIONS] ``` ### Options - `-f, --file `: Specifies the path to the `.env` file. Defaults to `./.env`. - `--required `: If set to `true`, the tool will exit with an error if the specified `.env` file is not found. Defaults to `true`. - `--override `: If set to `true`, variables defined in the `.env` file will override existing environment variables. Defaults to `false`. ### Example ```sh dotenvy --file .env.production npm start ``` ``` -------------------------------- ### Single-Quoted Values in .env Files Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/parsing-and-substitution.md Shows how single-quoted values are treated literally, without variable substitution or escape sequence processing. Includes examples of escaping single quotes and handling multi-line values. ```env KEY='literal $VALUE' # Value: "literal $VALUE" KEY='path\to\file' # Value: "path\to\file" KEY='it'\''s a test' # Value: "it's a test" KEY='multi line' # Value: "multi\nline" (actual newline) ``` -------------------------------- ### Create New EnvLoader Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/env-loader.md Initializes a new EnvLoader with the default path './.env'. Use this when loading from the standard .env file in the current directory. ```rust use dotenvy::EnvLoader; let loader = EnvLoader::new(); let env_map = loader.load()?; ``` -------------------------------- ### EnvThenInput Resolution Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Demonstrates the EnvThenInput resolution sequence where process environment variables are loaded first, followed by file variables, resulting in file variables taking precedence. ```text File: A=file_a, B=file_b Env: B=env_b, C=env_c Result: A=file_a, B=file_b, C=env_c ``` -------------------------------- ### Runtime Configuration Pattern in Rust Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Demonstrates a common pattern for managing development and production environments using dotenvy in Rust. It loads environment variables based on the APP_ENV setting. ```rust use dotenvy::{EnvLoader, EnvSequence}; use std::env; use std::str::FromStr; #[derive(Debug)] enum Environment { Development, Production, } impl From for EnvSequence { fn from(env: Environment) -> Self { match env { Environment::Development => EnvSequence::InputThenEnv, Environment::Production => EnvSequence::EnvThenInput, } } } impl FromStr for Environment { type Err = String; fn from_str(s: &str) -> Result { match s { "dev" | "development" => Ok(Environment::Development), "prod" | "production" => Ok(Environment::Production), _ => Err(format!("Unknown environment: {}", s)), } } } fn main() -> Result<(), Box> { let env = env::var("APP_ENV") .ok() .and_then(|v| v.parse().ok()) .unwrap_or(Environment::Development); let env_map = EnvLoader::new() .sequence(env.into()) .load()?; let host = env_map.var("HOST")?; println!("Running in {} mode on {}", match env { Environment::Development => "development", Environment::Production => "production", }, host); Ok(()) } ``` -------------------------------- ### Runtime Loader Configuration Source: https://github.com/allan2/dotenvy/blob/main/README.md Shows different ways to configure the EnvLoader, including specifying a file path, reading from a string, and setting the loading sequence (InputThenEnv or EnvThenInput). ```rust use dotenvy::EnvLoader; use dotenvy::EnvSequence; use std::io::Cursor; // from a file let loader1 = EnvLoader::with_path("./.env").sequence(EnvSequence::InputThenEnv); let loader2 = EnvLoader::new(); // shorthand for loader1 // from a string let s = "HOST=foo\nPORT=3000"; let str_loader = EnvLoader::with_reader(Cursor::new(s)); // will load from the env file, override exiting values in the program environment let overriding_loader = EnvLoader::new().sequence(EnvSequence::EnvThenInput); ``` -------------------------------- ### Handling General IO Errors with dotenvy Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/errors.md Illustrates how to handle various file I/O errors that may occur when loading .env files. This includes specific handling for errors with associated file paths and general I/O issues. ```rust use dotenvy::{EnvLoader, Error}; use std::io; match EnvLoader::with_path(".env.local").load() { Ok(map) => { /* use map */ } Err(Error::Io(io_err, Some(path))) => { eprintln!("Cannot read {}: {}", path.display(), io_err); std::process::exit(1); } Err(Error::Io(io_err, None)) => { eprintln!("I/O error: {}", io_err); } Err(e) => { /* other errors */ } } ``` -------------------------------- ### Runtime Loading Configuration: From String Source: https://github.com/allan2/dotenvy/blob/main/dotenvy/README.md Configures the EnvLoader to read environment variables from a string buffer using a Cursor. ```rs let s = "HOST=foo\nPORT=3000"; let str_loader = EnvLoader::with_reader(Cursor::new(s)); ``` -------------------------------- ### Runtime Macro Syntax for dotenvy::load Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/macros.md Illustrates the basic syntax for the #[dotenvy::load] attribute macro, specifying optional parameters like path, required, and override_. ```rust #[dotenvy::load(path = ".env", required = true, override_ = false)] ``` -------------------------------- ### load() Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/env-loader.md Loads environment variables into a hash map without modifying the current process environment. This is the primary method recommended for most use cases. ```APIDOC ## load() ### Description Loads environment variables into a hash map without modifying the current process environment. This is the primary method recommended for most use cases. ### Method `load` ### Parameters No parameters. ### Return Type `Result` ### Errors - `Error::Io(io_err, path)`: File cannot be opened or read - `Error::LineParse(line, index)`: Invalid syntax in env file - `Error::NoInput`: No path or reader was configured ### Example ```rust use dotenvy::{EnvLoader, EnvSequence}; fn main() -> Result<(), Box> { let env_map = EnvLoader::new() .sequence(EnvSequence::InputThenEnv) .load()?; let host = env_map.var("HOST")?; println!("HOST: {}", host); Ok(()) } ``` ``` -------------------------------- ### dotenvy CLI Options Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/README.md Defines the command-line interface options for the dotenvy binary, including file path, requirement, and override settings. ```sh dotenvy [OPTIONS] -f, --file Path to env file (default: ./.env) --required Fail if file not found (default: true) --override File overrides environment (default: false) ``` -------------------------------- ### Simple and Braced Substitution Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/parsing-and-substitution.md Demonstrates basic variable substitution using $VAR and ${VAR} syntax. Use braced substitution when the variable is immediately followed by alphanumeric characters. ```env # Simple substitution HOST=localhost URL=http://$HOST:8080 # Value: "http://localhost:8080" # Braced substitution (needed when followed by alphanumeric) KEY=value1 RESULT=${KEY}2 # Value: "value12" RESULT=$KEY2 # Value: "value" (KEY2 not defined) ``` -------------------------------- ### InputThenEnv Resolution (Default) Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Illustrates the default environment variable resolution where file variables are loaded first, followed by process environment variables, resulting in environment variables taking precedence. ```text File: A=file_a, B=file_b Env: B=env_b, C=env_c Result: A=file_a, B=env_b, C=env_c ``` -------------------------------- ### Rust Error Handling for Loading .env File Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/README.md Shows how to handle potential errors when loading a .env file, including cases where the file is not found. ```rust use dotenvy::EnvLoader; match EnvLoader::with_path(".env").load() { Ok(map) => println!("Loaded {} variables", map.len()), Err(e) if e.not_found() => println!("Using defaults"), Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Add dotenvy Dependency (Standard Library) Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Use this configuration to include dotenvy with only its standard library features. ```toml [dependencies] dotenvy = "0.15" ``` -------------------------------- ### EnvLoader Builder Pattern Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/modules.md Demonstrates the usage of the builder pattern for configuring and executing the EnvLoader. ```rust EnvLoader::new() // Create with defaults .with_path(".env") // Set path .sequence(seq) // Configure sequence .load() // Execute ``` -------------------------------- ### EnvLoader Constructor Methods Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/INDEX.md These methods are used to create a new EnvLoader instance. You can use the default constructor which loads from './.env', or specify a custom path or reader. ```APIDOC ## EnvLoader Constructor Methods ### Description Methods to instantiate `EnvLoader`. ### Methods - `EnvLoader::new()` - `EnvLoader::with_path(path: &str)` - `EnvLoader::with_reader(reader: impl std::io::Read)` ``` -------------------------------- ### Optional File Loading Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/cli.md Illustrates how to configure dotenvy to not exit with an error if the specified environment file is not found. This is useful for development workflows where some variables might be optional. ```sh dotenvy --required false npm start ``` -------------------------------- ### Create EnvLoader with Specific Path Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/env-loader.md Initializes a new EnvLoader targeting a specific .env file path. I/O operations are deferred until load() or load_and_modify() is called. ```rust use dotenvy::EnvLoader; let loader = EnvLoader::with_path("./.env.production"); let env_map = loader.load()?; ``` -------------------------------- ### EnvLoader Configuration Methods Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/INDEX.md Configure the EnvLoader with additional options such as error context path or loading sequence. ```APIDOC ## EnvLoader Configuration Methods ### Description Methods to configure `EnvLoader` behavior. ### Methods - `.path(path: &str)`: Sets the path for error context. - `.sequence(seq: &[&str])`: Specifies the loading strategy sequence. ``` -------------------------------- ### EnvLoader::with_path() Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/env-loader.md Creates a new EnvLoader with an explicit file path. I/O is deferred until load() or load_and_modify() is called. ```APIDOC ## EnvLoader::with_path() ### Description Creates a new `EnvLoader` with an explicit file path. This operation is infallible; I/O is deferred until `load()` or `load_and_modify()` is called. ### Method `with_path>(path: P)` ### Parameters #### Path Parameters - **path** (`P: AsRef`) - Required - Path to the `.env` file to load ### Return Type `EnvLoader<'a>` ### Example ```rust use dotenvy::EnvLoader; let loader = EnvLoader::with_path("./.env.production"); let env_map = loader.load()?; ``` ``` -------------------------------- ### Runtime Macro: Override Existing Environment Configuration Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/macros.md Demonstrates how to enable overriding existing environment variables with values from the .env file by setting `override_ = true`. ```rust #[dotenvy::load(override_ = true)] fn main() { // Code here } ``` -------------------------------- ### Load Environment Variables with Macro (Async) Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/INDEX.md This snippet demonstrates how to use the `#[dotenvy::load]` attribute macro with an async function, typically used in Tokio applications. ```rust #[dotenvy::load] #[tokio::main] async fn main() { } ``` -------------------------------- ### dotenvy Crate Dependency Graph Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/modules.md Visualizes the dependency structure of the dotenvy crate and its associated macro crate. ```text dotenvy (crate) ├── std (core library) ├── clap (feature: cli) → command-line parsing └── dotenvy-macros (feature: macros) → runtime attribute macro dotenvy-macros (crate) ├── proc-macro2 → token manipulation ├── quote → code generation ├── syn → AST parsing └── dotenvy → EnvLoader usage dotenv_codegen (crate) ├── proc-macro2 → token manipulation ├── quote → code generation ├── syn → AST parsing └── dotenvy → EnvLoader usage ``` -------------------------------- ### Basic EnvMap loading and variable access Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/env-map.md Load environment variables using `EnvLoader::new().load()?` and access specific variables like 'HOST' and 'PORT' using the `var()` method. ```rust use dotenvy::EnvLoader; fn main() -> Result<(), Box> { let env_map = EnvLoader::new().load()?; let host = env_map.var("HOST")?; let port = env_map.var("PORT")?; println!("Connecting to {}:{}", host, port); Ok(()) } ``` -------------------------------- ### Correct Usage for EnvOnly Sequence Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/errors.md Shows the correct way to load environment variables with EnvSequence::EnvOnly using load(). For modification, other sequences like InputThenEnv should be used. ```rust use dotenvy::{EnvLoader, EnvSequence}; // For EnvOnly, use load() instead let map = EnvLoader::new() .sequence(EnvSequence::EnvOnly) .load()?; // For modification, use InputThenEnv or another sequence let map = EnvLoader::new() .sequence(EnvSequence::InputThenEnv); unsafe { loader.load_and_modify() }?; ``` -------------------------------- ### #[dotenvy::load] Macro: Default Configuration Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Applies the default #[dotenvy::load] macro configuration, which loads from './.env' and requires the file to exist. This is equivalent to specifying path = "./.env", required = true, and override_ = false. ```rust #[dotenvy::load] fn main() { // Expands to: // #[dotenvy::load(path = "./.env", required = true, override_ = false)] } ``` -------------------------------- ### EnvMap::new() Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/env-map.md Creates a new, empty EnvMap. This is the constructor for the EnvMap type. ```APIDOC ## EnvMap::new() ### Description Creates a new empty `EnvMap`. ### Method `new()` ### Parameters No parameters. ### Return Type `EnvMap` ### Example ```rust use dotenvy::EnvMap; let mut map = EnvMap::new(); map.insert("HOST".to_string(), "localhost".to_string()); println!("HOST={}", map.var("HOST")?); ``` ``` -------------------------------- ### Simple Variable Substitution in .env file Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Demonstrates how to use environment variables within other variable definitions in a .env file. Substitution is enabled in double-quoted and unquoted values. ```env # Simple substitution HOST=localhost URL=http://$HOST:8080 # Braced substitution URL=http://${HOST}:8080 # Undefined variables substitute to empty MISSING_VAR=value_before_$UNDEFINED_VAR_value_after # Result: value_before__value_after ``` -------------------------------- ### dotenvy Macros Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/INDEX.md dotenvy provides macros for loading environment variables. `#[dotenvy::load]` is a runtime attribute macro, and `dotenv!()` is a compile-time macro. ```APIDOC ## Macros ### Description Macros provided by the `dotenvy` crate for loading environment variables. ### Macros - `#[dotenvy::load]`: An attribute macro that loads environment variables at runtime. - `dotenv!()`: A compile-time macro for loading environment variables. ``` -------------------------------- ### Add dotenvy Dependency (With Macros) Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Include dotenvy with the 'macros' feature enabled for additional macro support. ```toml [dependencies] dotenvy = { version = "0.15", features = ["macros"] } ``` -------------------------------- ### EnvLoader Methods Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/README.md Methods for creating and configuring an EnvLoader instance to load environment variables from files or other sources. ```APIDOC ## EnvLoader Methods ### `new()` - **Purpose**: Create an `EnvLoader` instance with the default path (`./.env`). - **Returns**: `Self` (a new `EnvLoader` instance). ### `with_path(path: &str)` - **Purpose**: Create an `EnvLoader` instance with a custom file path. - **Parameters**: - `path` (string slice): The custom path to the environment file. - **Returns**: `Self` (a new `EnvLoader` instance). ### `with_reader(reader)` - **Purpose**: Create an `EnvLoader` instance from a reader. - **Parameters**: - `reader`: A type that implements `std::io::Read`. - **Returns**: `Self` (a new `EnvLoader` instance). ### `path(path: &str)` - **Purpose**: Set the error context path for the `EnvLoader`. - **Parameters**: - `path` (string slice): The path to set for error context. - **Returns**: `Self` (the modified `EnvLoader` instance). ### `sequence(seq: EnvSequence)` - **Purpose**: Set the loading strategy for environment variables (e.g., file then environment, or environment then file). - **Parameters**: - `seq` (`EnvSequence`): The desired loading sequence. - **Returns**: `Self` (the modified `EnvLoader` instance). ### `load()` - **Purpose**: Load environment variables from the configured source without modifying the actual environment. - **Returns**: `Result`: An `EnvMap` containing the loaded variables on success, or an `Error` on failure. ### `load_and_modify()` - **Purpose**: Load environment variables and modify the process's environment (unsafe). - **Returns**: `Result`: An `EnvMap` containing the loaded variables on success, or an `Error` on failure. - **Note**: This operation is `unsafe`. ``` -------------------------------- ### Handling LineParse Errors Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/errors.md Demonstrates how to catch and report errors related to invalid syntax in .env files. This is useful when parsing configuration files to provide specific feedback on syntax issues. ```rust use dotenvy::EnvLoader; match EnvLoader::new().load() { Err(dotenvy::Error::LineParse(line, idx)) => { eprintln!("Parse error at char {}: {}", idx, line); } _ => {} } ``` -------------------------------- ### EnvLoader::with_reader() Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/env-loader.md Creates a new EnvLoader that reads from an arbitrary reader implementing io::Read. I/O is deferred until load() or load_and_modify() is called. ```APIDOC ## EnvLoader::with_reader() ### Description Creates a new `EnvLoader` that reads from an arbitrary reader implementing `io::Read`. This operation is infallible; I/O is deferred until `load()` or `load_and_modify()` is called. ### Method `with_reader(rdr: R)` ### Parameters #### Path Parameters - **rdr** (`R: Read + 'a`) - Required - Any type implementing `std::io::Read` ### Return Type `EnvLoader<'a>` ### Example ```rust use dotenvy::EnvLoader; use std::io::Cursor; let content = "HOST=localhost\nPORT=5432"; let reader = Cursor::new(content); let loader = EnvLoader::with_reader(reader); let env_map = loader.load()?; println!("HOST={}", env_map.var("HOST")?); ``` ``` -------------------------------- ### Changelog Entry Format Source: https://github.com/allan2/dotenvy/blob/main/CONTRIBUTING.md Use this format to describe changes in the CHANGELOG.md file. Include PR number and author for tracking. ```markdown ### Changed - Short description of what has been changed ([PR #123](pull.request.url)) by [username](github.profile.url) - [**BREAKING**] Please prefix any breaking changes ``` -------------------------------- ### Optional Loading with Error Matching Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/errors.md Shows how to implement optional loading by matching on specific errors, like `not_found()`. If the file is not found, it defaults to an empty map; otherwise, it prints the error and exits. ```rust use dotenvy::EnvLoader; fn main() { let map = match EnvLoader::with_path(".env.local").load() { Ok(m) => m, Err(e) if e.not_found() => { println!("No local config, using defaults"); dotenvy::EnvMap::new() } Err(e) => { eprintln!("Error: {}", e); std::process::exit(1); } }; } ``` -------------------------------- ### Handle dotenvy Loading Errors Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/types.md Demonstrates how to match against various dotenvy::Error variants to provide user-friendly messages for different loading failures, such as IO errors, parsing errors, or missing variables. ```rust use dotenvy::{EnvLoader, Error}; fn main() -> Result<(), Box> { match EnvLoader::with_path(".env").load() { Ok(map) => println!("Loaded {} variables", map.len()), Err(Error::Io(io_err, Some(path))) => { eprintln!("Cannot read {}: {}", path.display(), io_err); } Err(Error::LineParse(line, idx)) => { eprintln!("Parse error at position {}: {}", idx, line); } Err(Error::NotPresent(name)) => { eprintln!("Variable {} is required", name); } Err(e) => eprintln!("Error: {}", e), } Ok(()) } ``` -------------------------------- ### Escaped Spaces in Value Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/README.md Demonstrates how to include spaces within a value in .env files by escaping them. ```env KEY=val\ ue ``` -------------------------------- ### #[dotenvy::load] Macro: Custom Path Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/configuration.md Configures the #[dotenvy::load] macro to load environment variables from a specific file, '.env.development', instead of the default './.env'. ```rust #[dotenvy::load(path = ".env.development")] fn main() { // Load from .env.development instead of .env } ``` -------------------------------- ### Create a new empty EnvMap Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/env-map.md Use `EnvMap::new()` to create an empty map. You can then insert key-value pairs into it. ```rust use dotenvy::EnvMap; let mut map = EnvMap::new(); map.insert("HOST".to_string(), "localhost".to_string()); println!("HOST={}", map.var("HOST")?); ``` -------------------------------- ### Graceful Fallback for Missing Variables Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/errors.md Shows how to provide a default value for an environment variable if it's not found using `unwrap_or_else`. This is useful for optional configuration settings. ```rust use dotenvy::EnvLoader; let map = EnvLoader::new().load()?; let timeout = map.var("REQUEST_TIMEOUT") .unwrap_or_else(|_| "30000".to_string()); ``` -------------------------------- ### Configure EnvLoader Loading Sequence Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/env-loader.md Sets the strategy for merging environment variables from the input source with the existing process environment. Use InputThenEnv for development and EnvThenInput for production. ```rust use dotenvy::{EnvLoader, EnvSequence}; // Development: env file takes precedence let dev_loader = EnvLoader::new() .sequence(EnvSequence::InputThenEnv); // Production: process environment takes precedence let prod_loader = EnvLoader::new() .sequence(EnvSequence::EnvThenInput); let env_map = dev_loader.load()?; ``` -------------------------------- ### Handling NotPresent Errors for Required Variables Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/errors.md Demonstrates how to detect and handle cases where a required environment variable is missing after loading the .env file. This is crucial for ensuring essential configuration is present. ```rust use dotenvy::EnvLoader; let map = EnvLoader::new().load()?; match map.var("DATABASE_URL") { Ok(url) => println!("Database: {}", url), Err(dotenvy::Error::NotPresent(name)) => { eprintln!("Required variable missing: {}", name); std::process::exit(1); } Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Detecting File Not Found Errors with dotenvy Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/errors.md Shows how to specifically check if a .env file was not found using the `not_found()` method. This is useful for implementing fallback logic or providing user-friendly messages when configuration files are missing. ```rust use dotenvy::EnvLoader; match EnvLoader::with_path(".env").load() { Err(e) if e.not_found() => { println!("No .env file, using defaults"); } Err(e) => { eprintln!("I/O error: {}", e); } Ok(map) => { // Process map } } ``` -------------------------------- ### var() Function Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/README.md Fetches a specific environment variable by key, returning a Result with improved error reporting. ```rust pub fn var(key: &str) -> Result ``` -------------------------------- ### var() Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/functions.md Fetches an environment variable from the current process, returning a `dotenvy::Error` for improved error messages, especially when a variable is not found. ```APIDOC ## var() ### Description Fetches an environment variable from the current process, with improved error reporting via `dotenvy::Error`. This function is similar to `std::env::var()` but returns `dotenvy::Error` instead of `std::env::VarError`. The main advantage is that `dotenvy::Error::NotPresent` includes the variable name for better error messages. ### Method Rust Function ### Signature ```rust pub fn var(key: &str) -> Result ``` ### Parameters #### Path Parameters - **key** (`&str`) - Required - Name of the environment variable to retrieve ### Response #### Success Response - **String** - The value of the environment variable if found. #### Error Response - **`Error::NotPresent(key)`** - The environment variable is not set. - **`Error::NotUnicode(os_str, key)`** - The variable value contains invalid UTF-8. - Other errors may occur if the variable name contains the equal sign (`=`) or the NUL character. ### Notes - Only call this on environment variables already in the current process (set via `load_and_modify()` or externally). ### Example ```rust use dotenvy; fn main() { match dotenvy::var("USER") { Ok(user) => println!("Running as: {}", user), Err(dotenvy::Error::NotPresent(name)) => { eprintln!("Variable {} is not set", name); } Err(e) => eprintln!("Error: {}", e), } } ``` ``` -------------------------------- ### dotenvy Rust Implementation Details Source: https://github.com/allan2/dotenvy/blob/main/_autodocs/api-reference/cli.md Shows the Rust code snippet that constructs an EnvLoader with a specified file path and loading sequence (EnvThenInput or InputThenEnv). The `load_and_modify()` function is called unsafely to modify the current process environment. ```rust let seq = if cli.override_ { EnvSequence::EnvThenInput } else { EnvSequence::InputThenEnv }; let loader = EnvLoader::with_reader(file) .path(&cli.file) .sequence(seq); unsafe { loader.load_and_modify() }?; ```