### LookupError Handling in Rust Source: https://context7.com/ijackson/rust-shellexpand/llms.txt The `LookupError` type is returned when an environment variable lookup fails. It contains the variable name and the underlying cause, facilitating debugging and error handling. This example demonstrates accessing error details, implementing `Display` and the `Error` trait, and handling custom error types. ```rust use shellexpand::LookupError; use std::env::{self, VarError}; env::remove_var("NONEXISTENT"); let result = shellexpand::env("$NONEXISTENT"); match result { Err(LookupError { var_name, cause }) => { // Access error details assert_eq!(var_name, "NONEXISTENT"); assert_eq!(cause, VarError::NotPresent); // LookupError implements Display println!("Error: {}", shellexpand::env("$NONEXISTENT").unwrap_err()); // Output: "error looking key 'NONEXISTENT' up: environment variable not found" // LookupError implements Error trait use std::error::Error; let lookup_err = shellexpand::env("$NONEXISTENT").unwrap_err(); if let Some(source) = lookup_err.source() { println!("Caused by: {}", source); } } Ok(_) => panic!("should have failed") } // Custom error types work too #[derive(Debug, Clone, PartialEq)] struct MyError(String); fn failing_lookup(_: &str) -> Result, MyError> { Err(MyError("custom error".into())) } let err = shellexpand::env_with_context("$VAR", failing_lookup); assert_eq!(err, Err(LookupError { var_name: "VAR".into(), cause: MyError("custom error".into()) })); ``` -------------------------------- ### Perform Tilde Expansion with System Defaults Source: https://context7.com/ijackson/rust-shellexpand/llms.txt Demonstrates how to use the tilde function to expand the tilde character to the user's home directory. It handles various path formats and respects platform-specific separators. ```rust use shellexpand; // Basic tilde expansion to home directory let expanded = shellexpand::tilde("~/documents/file.txt"); // Tilde alone expands to home directory let home = shellexpand::tilde("~"); // No expansion if tilde is not at start or not followed by separator let unchanged = shellexpand::tilde("some/~/path"); // Windows backslash paths are also supported let windows_path = shellexpand::tilde("~\\Documents"); ``` -------------------------------- ### full_with_context Source: https://context7.com/ijackson/rust-shellexpand/llms.txt Performs tilde and environment expansion using custom context functions for maximum flexibility. ```APIDOC ## full_with_context ### Description Performs both tilde and environment expansion using custom context functions. Provides maximum flexibility for controlling expansion behavior. ### Method N/A (Function Call) ### Endpoint N/A (Function Call) ### Parameters N/A ### Request Example ```rust use shellexpand::{self, LookupError}; use std::borrow::Cow; // Custom contexts fn home_dir() -> Option { Some("/home/testuser".to_string()) } fn get_env(name: &str) -> Result, &'static str> { match name { "APP" => Ok(Some("myapp")), "ENV" => Ok(Some("production")), "TILDE" => Ok(Some("~")), // Value starts with tilde "FORBIDDEN" => Err("access denied"), _ => Ok(None) } } // Full expansion with custom contexts let path = shellexpand::full_with_context( "~/$APP/$ENV", home_dir, get_env ).unwrap(); assert_eq!(path, "/home/testuser/myapp/production"); // Tilde in variable value is correctly NOT expanded let result = shellexpand::full_with_context( "$TILDE/data", home_dir, get_env ).unwrap(); assert_eq!(result, "~/data"); // Tilde preserved // Error propagation let err = shellexpand::full_with_context( "~/$FORBIDDEN", home_dir, get_env ); assert!(err.is_err()); // No allocation when no expansion needed let unchanged = shellexpand::full_with_context( "plain/path", home_dir, get_env ).unwrap(); match unchanged { Cow::Borrowed(s) => assert_eq!(s, "plain/path"), _ => panic!("should not allocate") } ``` ### Response N/A (Function Return) ### Response Example N/A (Function Return) ``` -------------------------------- ### full_with_context_no_errors Source: https://context7.com/ijackson/rust-shellexpand/llms.txt Performs tilde and environment expansion with an infallible context function, combining behaviors. ```APIDOC ## full_with_context_no_errors ### Description Performs both tilde and environment expansion with an infallible context function. Combines `tilde_with_context` and `env_with_context_no_errors` behavior. ### Method N/A (Function Call) ### Endpoint N/A (Function Call) ### Parameters N/A ### Request Example ```rust use shellexpand; use std::borrow::Cow; fn home() -> Option { Some("/users/demo".to_string()) } fn vars(name: &str) -> Option<&'static str> { match name { "DIR" => Some("documents"), "FILE" => Some("readme.txt"), _ => None } } // Simple combined expansion let path: Cow = shellexpand::full_with_context_no_errors( "~/$DIR/$FILE", home, vars ); assert_eq!(path, "/users/demo/documents/readme.txt"); // Unknown variables preserved, tilde expanded let partial = shellexpand::full_with_context_no_errors( "~/$UNKNOWN/path", home, vars ); assert_eq!(partial, "/users/demo/$UNKNOWN/path"); ``` ### Response N/A (Function Return) ### Response Example N/A (Function Return) ``` -------------------------------- ### Perform Tilde Expansion with Custom Context Source: https://context7.com/ijackson/rust-shellexpand/llms.txt Shows how to use tilde_with_context to provide a custom home directory or dynamic behavior. This is useful for testing or non-standard environment configurations. ```rust use shellexpand; use std::borrow::Cow; // Custom home directory provider fn custom_home() -> Option { Some("/custom/home".to_string()) } let expanded = shellexpand::tilde_with_context("~/projects", custom_home); assert_eq!(expanded, "/custom/home/projects"); // Using closures for dynamic behavior let user = "alice"; let expanded = shellexpand::tilde_with_context( "~/data", || Some(format!("/home/{}", user)) ); assert_eq!(expanded, "/home/alice/data"); ``` -------------------------------- ### Perform Environment Variable Expansion Source: https://context7.com/ijackson/rust-shellexpand/llms.txt Illustrates how to expand environment variables in strings using the env function. Supports standard $VAR syntax, braced ${VAR} syntax, and default values using ${VAR:-default}. ```rust use shellexpand; use std::env; // Set up environment variables env::set_var("PROJECT", "myapp"); env::set_var("VERSION", "1.0"); // Basic variable expansion let config = shellexpand::env("$PROJECT/config").unwrap(); assert_eq!(config, "myapp/config"); // Braced syntax for clarity let path = shellexpand::env("${PROJECT}/${VERSION}/data").unwrap(); assert_eq!(path, "myapp/1.0/data"); // Default values for unset variables env::remove_var("UNSET_VAR"); let with_default = shellexpand::env("${UNSET_VAR:-fallback}").unwrap(); assert_eq!(with_default, "fallback"); ``` -------------------------------- ### Tilde Expansion Source: https://context7.com/ijackson/rust-shellexpand/llms.txt Performs tilde expansion using the default system home directory. Expands '~' at the beginning of a string into the user's home directory path. ```APIDOC ## Tilde Expansion ### Description Performs tilde expansion using the default system home directory from `dirs::home_dir()`. Expands `~` at the beginning of a string (when followed by `/`, `\` on Windows, or end of string) into the user's home directory path. ### Method `shellexpand::tilde` ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use shellexpand; // Basic tilde expansion to home directory let expanded = shellexpand::tilde("~/documents/file.txt"); // Result: "/home/username/documents/file.txt" (on Unix) // Tilde alone expands to home directory let home = shellexpand::tilde("~"); // Result: "/home/username" // No expansion if tilde is not at start or not followed by separator let unchanged = shellexpand::tilde("some/~/path"); // Result: "some/~/path" (unchanged) // Windows backslash paths are also supported let windows_path = shellexpand::tilde("~\\Documents"); // Result: "C:\\Users\\username\\Documents" (on Windows) ``` ### Response #### Success Response (200) `Cow`: The expanded string. Returns `Cow::Borrowed` if no expansion occurred, `Cow::Owned` if expansion resulted in a new string. #### Response Example ```json { "example": "/home/username/documents/file.txt" } ``` ``` -------------------------------- ### Tilde Expansion with Custom Context Source: https://context7.com/ijackson/rust-shellexpand/llms.txt Performs tilde expansion using a custom context function that provides the home directory. Useful for specifying a different home directory or mocking for testing. ```APIDOC ## Tilde Expansion with Custom Context ### Description Performs tilde expansion using a custom context function that provides the home directory. Useful when you need to specify a different home directory or mock the home directory for testing. ### Method `shellexpand::tilde_with_context` ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use shellexpand; use std::borrow::Cow; // Custom home directory provider fn custom_home() -> Option { Some("/custom/home".to_string()) } let expanded = shellexpand::tilde_with_context("~/projects", custom_home); assert_eq!(expanded, "/custom/home/projects"); // Context can return None to skip expansion fn no_home() -> Option { None } let unchanged = shellexpand::tilde_with_context("~/path", no_home); assert_eq!(unchanged, "~/path"); // Using closures for dynamic behavior let user = "alice"; let expanded = shellexpand::tilde_with_context( "~/data", || Some(format!("/home/{}", user)) ); assert_eq!(expanded, "/home/alice/data"); ``` ### Response #### Success Response (200) `Cow`: The expanded string. Returns `Cow::Borrowed` if no expansion occurred, `Cow::Owned` if expansion resulted in a new string. #### Response Example ```json { "example": "/custom/home/projects" } ``` ``` -------------------------------- ### Perform full tilde and environment expansion Source: https://context7.com/ijackson/rust-shellexpand/llms.txt Performs both tilde and environment variable expansion using system defaults. It correctly handles edge cases such as variables containing tildes and provides error handling for missing variables. ```rust use shellexpand; use std::env; env::set_var("PROJECT", "myproject"); env::set_var("SUBDIR", "src"); let path = shellexpand::full("~/$PROJECT/$SUBDIR").unwrap(); let config = shellexpand::full("~/${CONFIG_DIR:-config}/app.toml").unwrap(); env::set_var("TILDE_VAR", "~/should/not/expand"); let result = shellexpand::full("$TILDE_VAR/file").unwrap(); assert_eq!(result, "~/should/not/expand/file"); env::remove_var("MISSING"); let err = shellexpand::full("~/$MISSING/path"); assert!(err.is_err()); ``` -------------------------------- ### Full Expansion with Custom Contexts in Rust Source: https://context7.com/ijackson/rust-shellexpand/llms.txt Performs both tilde and environment expansion using custom context functions. This method offers maximum flexibility for controlling expansion behavior. It handles cases where variables are not found or access is denied, and efficiently avoids allocation when no expansion is necessary. ```rust use shellexpand::{self, LookupError}; use std::borrow::Cow; // Custom contexts fn home_dir() -> Option { Some("/home/testuser".to_string()) } fn get_env(name: &str) -> Result, &'static str> { match name { "APP" => Ok(Some("myapp")), "ENV" => Ok(Some("production")), "TILDE" => Ok(Some("~")), // Value starts with tilde "FORBIDDEN" => Err("access denied"), _ => Ok(None) } } // Full expansion with custom contexts let path = shellexpand::full_with_context( "~/$APP/$ENV", home_dir, get_env ).unwrap(); assert_eq!(path, "/home/testuser/myapp/production"); // Tilde in variable value is correctly NOT expanded let result = shellexpand::full_with_context( "$TILDE/data", home_dir, get_env ).unwrap(); assert_eq!(result, "~/data"); // Tilde preserved // Error propagation let err = shellexpand::full_with_context( "~/$FORBIDDEN", home_dir, get_env ); assert!(err.is_err()); // No allocation when no expansion needed let unchanged = shellexpand::full_with_context( "plain/path", home_dir, get_env ).unwrap(); match unchanged { Cow::Borrowed(s) => assert_eq!(s, "plain/path"), _ => panic!("should not allocate") } ``` -------------------------------- ### Environment Variable Expansion Source: https://context7.com/ijackson/rust-shellexpand/llms.txt Performs environment variable expansion using system environment variables. Supports `$VAR`, `${VAR}`, and `${VAR:-default}` syntax. ```APIDOC ## Environment Variable Expansion ### Description Performs environment variable expansion using system environment variables via `std::env::var()`. Supports both `$VAR` and `${VAR}` syntax, plus default values with `${VAR:-default}`. ### Method `shellexpand::env` ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use shellexpand; use std::env; // Set up environment variables env::set_var("PROJECT", "myapp"); env::set_var("VERSION", "1.0"); // Basic variable expansion let config = shellexpand::env("$PROJECT/config").unwrap(); assert_eq!(config, "myapp/config"); // Braced syntax for clarity let path = shellexpand::env("${PROJECT}/${VERSION}/data").unwrap(); assert_eq!(path, "myapp/1.0/data"); // Default values for unset variables env::remove_var("UNSET_VAR"); let with_default = shellexpand::env("${UNSET_VAR:-fallback}").unwrap(); assert_eq!(with_default, "fallback"); // Error handling for unknown variables let result = shellexpand::env("$UNKNOWN_VAR"); match result { Err(shellexpand::LookupError { var_name, cause }) => { println!("Variable '{}' not found: {:?}", var_name, cause); } Ok(_) => unreachable!() } ``` ### Response #### Success Response (200) `Result, LookupError>`: Returns `Ok(Cow)` with the expanded string on success, or `Err(LookupError)` if an environment variable is not found and no default is provided. #### Response Example ```json { "example": "myapp/config" } ``` ``` -------------------------------- ### path Module Source: https://context7.com/ijackson/rust-shellexpand/llms.txt Extension module for working directly with `Path` types, mirroring the main API but for paths. ```APIDOC ## path Module ### Description Extension module for working directly with `Path` types instead of strings. Requires the `path` cargo feature. Functions mirror the main API but accept and return `Path`/`Cow`. ### Method N/A (Function Calls) ### Endpoint N/A (Function Calls) ### Parameters N/A ### Request Example ```rust // Enable with: shellexpand = { version = "3.0", features = ["path"] } use shellexpand::path; use std::path::{Path, PathBuf}; use std::borrow::Cow; use std::env; env::set_var("SUBDIR", "data"); // Tilde expansion returning Path let home_path: Cow = path::tilde(Path::new("~/documents")); // Result: Path("/home/username/documents") // Environment expansion on paths let expanded: Cow = path::env(Path::new("/app/$SUBDIR/file.txt")).unwrap(); // Result: Path("/app/data/file.txt") // Full expansion on paths let full_path: Cow = path::full(Path::new("~/$SUBDIR")).unwrap(); // Result: Path("/home/username/data") // Context-based path expansion fn custom_home() -> Option { Some(PathBuf::from("/custom/home")) } let custom: Cow = path::tilde_with_context( Path::new("~/files"), custom_home ); assert_eq!(custom.as_ref(), Path::new("/custom/home/files")); ``` ### Response N/A (Function Return Types) ### Response Example N/A (Function Return Types) ``` -------------------------------- ### Path Module for Path Expansion in Rust Source: https://context7.com/ijackson/rust-shellexpand/llms.txt The `path` module extends shellexpand to work directly with `Path` types, requiring the `path` cargo feature. It mirrors the main API but accepts and returns `Path` or `Cow`. This includes tilde expansion, environment expansion on paths, and context-based path expansion. ```rust // Enable with: shellexpand = { version = "3.0", features = ["path"] } use shellexpand::path; use std::path::{Path, PathBuf}; use std::borrow::Cow; use std::env; env::set_var("SUBDIR", "data"); // Tilde expansion returning Path let home_path: Cow = path::tilde(Path::new("~/documents")); // Result: Path("/home/username/documents") // Environment expansion on paths let expanded: Cow = path::env(Path::new("/app/$SUBDIR/file.txt")).unwrap(); // Result: Path("/app/data/file.txt") // Full expansion on paths let full_path: Cow = path::full(Path::new("~/$SUBDIR")).unwrap(); // Result: Path("/home/username/data") // Context-based path expansion fn custom_home() -> Option { Some(PathBuf::from("/custom/home")) } let custom: Cow = path::tilde_with_context( Path::new("~/files"), custom_home ); assert_eq!(custom.as_ref(), Path::new("/custom/home/files")); ``` -------------------------------- ### Infallible Full Expansion with Custom Contexts in Rust Source: https://context7.com/ijackson/rust-shellexpand/llms.txt Performs both tilde and environment expansion using an infallible context function. This combines the behavior of `tilde_with_context` and `env_with_context_no_errors`. Unknown variables are preserved, and tildes are expanded. ```rust use shellexpand; use std::borrow::Cow; fn home() -> Option { Some("/users/demo".to_string()) } fn vars(name: &str) -> Option<&'static str> { match name { "DIR" => Some("documents"), "FILE" => Some("readme.txt"), _ => None } } // Simple combined expansion let path: Cow = shellexpand::full_with_context_no_errors( "~/$DIR/$FILE", home, vars ); assert_eq!(path, "/users/demo/documents/readme.txt"); // Unknown variables preserved, tilde expanded let partial = shellexpand::full_with_context_no_errors( "~/$UNKNOWN/path", home, vars ); assert_eq!(partial, "/users/demo/$UNKNOWN/path"); ``` -------------------------------- ### Expand environment variables with custom context Source: https://context7.com/ijackson/rust-shellexpand/llms.txt Performs environment variable expansion using a custom context function. This allows for fine-grained control over variable lookup and supports error propagation if a lookup fails. ```rust use shellexpand::{self, LookupError}; use std::borrow::Cow; use std::collections::HashMap; fn get_config(name: &str) -> Result, &'static str> { match name { "DB_HOST" => Ok(Some("localhost")), "DB_PORT" => Ok(Some("5432")), "SECRET" => Err("access denied to secret variables"), _ => Ok(None) } } let conn = shellexpand::env_with_context( "postgresql://$DB_HOST:$DB_PORT/mydb", get_config ).unwrap(); assert_eq!(conn, "postgresql://localhost:5432/mydb"); let partial = shellexpand::env_with_context( "$DB_HOST:$UNKNOWN", get_config ).unwrap(); assert_eq!(partial, "localhost:$UNKNOWN"); let result = shellexpand::env_with_context("key=$SECRET", get_config); assert_eq!(result, Err(LookupError { var_name: "SECRET".into(), cause: "access denied to secret variables" })); let mut vars: HashMap<&str, &str> = HashMap::new(); vars.insert("NAME", "world"); let greeting = shellexpand::env_with_context( "Hello, $NAME!", |key| Ok::<_, ()>(vars.get(key).copied()) ).unwrap(); assert_eq!(greeting, "Hello, world!"); ``` -------------------------------- ### Add shellexpand Dependency to Cargo.toml Source: https://gitlab.com/ijackson/rust-shellexpand/-/blob/main/README.md This snippet shows how to add the shellexpand library as a dependency in your Rust project's Cargo.toml file. It specifies the version to be used. ```toml [dependencies] shellexpand = "3.0" ``` -------------------------------- ### Expand environment variables with infallible context Source: https://context7.com/ijackson/rust-shellexpand/llms.txt Performs environment variable expansion using a context function that cannot fail. This simplifies the API when lookups are guaranteed to succeed or return None. ```rust use shellexpand; use std::borrow::Cow; fn simple_context(name: &str) -> Option<&'static str> { match name { "USER" => Some("alice"), "ROLE" => Some("admin"), _ => None } } let message: Cow = shellexpand::env_with_context_no_errors( "User: $USER, Role: $ROLE", simple_context ); assert_eq!(message, "User: alice, Role: admin"); let partial = shellexpand::env_with_context_no_errors( "$USER ($UNKNOWN)", simple_context ); assert_eq!(partial, "alice ($UNKNOWN)"); let unchanged = shellexpand::env_with_context_no_errors( "no variables here", simple_context ); match unchanged { Cow::Borrowed(s) => assert_eq!(s, "no variables here"), Cow::Owned(_) => panic!("should not allocate") } ``` -------------------------------- ### LookupError Source: https://context7.com/ijackson/rust-shellexpand/llms.txt The error type returned when environment variable lookup fails, providing details for debugging. ```APIDOC ## LookupError ### Description Error type returned when environment variable lookup fails. Contains the variable name and the underlying cause for debugging and error handling. ### Method N/A (Function Call / Error Handling) ### Endpoint N/A (Function Call / Error Handling) ### Parameters N/A ### Request Example ```rust use shellexpand::LookupError; use std::env::{self, VarError}; env::remove_var("NONEXISTENT"); let result = shellexpand::env("$NONEXISTENT"); match result { Err(LookupError { var_name, cause }) => { // Access error details assert_eq!(var_name, "NONEXISTENT"); assert_eq!(cause, VarError::NotPresent); // LookupError implements Display println!("Error: {}", shellexpand::env("$NONEXISTENT").unwrap_err()); // Output: "error looking key 'NONEXISTENT' up: environment variable not found" // LookupError implements Error trait use std::error::Error; let lookup_err = shellexpand::env("$NONEXISTENT").unwrap_err(); if let Some(source) = lookup_err.source() { println!("Caused by: {}", source); } } Ok(_) => panic!("should have failed") } // Custom error types work too #[derive(Debug, Clone, PartialEq)] struct MyError(String); fn failing_lookup(_: &str) -> Result, MyError> { Err(MyError("custom error".into())) } let err = shellexpand::env_with_context("$VAR", failing_lookup); assert_eq!(err, Err(LookupError { var_name: "VAR".into(), cause: MyError("custom error".into()) })); ``` ### Response N/A (Error Type) ### Response Example N/A (Error Type) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.