### Implement Full Application Configuration with Clapfig Source: https://context7.com/arthur-debert/clapfig/llms.txt A comprehensive example showing how to define nested configuration structures, integrate with clap for CLI arguments, and set up multiple search paths and persistence scopes. ```rust use clap::{Parser, Subcommand}; use confique::Config; use serde::{Deserialize, Serialize}; use clapfig::{Clapfig, ConfigArgs, SearchPath, Boundary}; #[derive(Config, Serialize, Deserialize, Debug)] pub struct AppConfig { #[config(default = "myapp")] pub name: String, #[config(default = false)] pub verbose: bool, #[config(nested)] pub server: ServerConfig, } #[derive(Config, Serialize, Deserialize, Debug)] pub struct ServerConfig { #[config(default = "127.0.0.1")] pub host: String, #[config(default = 8080)] pub port: u16, } #[derive(Parser)] struct Cli { #[arg(long, global = true)] verbose: bool, #[arg(long)] port: Option, #[command(subcommand)] command: Commands, } #[derive(Subcommand)] enum Commands { Run, Config(ConfigArgs), } #[derive(Serialize)] struct CliOverrides { verbose: bool, } fn main() -> anyhow::Result<()> { let cli = Cli::parse(); let builder = Clapfig::builder::() .app_name("myapp") .search_paths(vec![ SearchPath::Platform, SearchPath::Home(".myapp"), SearchPath::Ancestors(Boundary::Marker(".git")), ]) .persist_scope("local", SearchPath::Cwd) .persist_scope("global", SearchPath::Platform) .cli_overrides_from(&CliOverrides { verbose: cli.verbose }) .cli_override("server.port", cli.port.map(i64::from)); match cli.command { Commands::Run => { let config = builder.load()?; if config.verbose { println!("[verbose] Starting {}...", config.name); } println!("Server at {}:{}", config.server.host, config.server.port); } Commands::Config(args) => { builder.handle_and_print(&args.into_action())?; } } Ok(()) } ``` -------------------------------- ### List and Get Configuration Values with Clapfig Source: https://context7.com/arthur-debert/clapfig/llms.txt Demonstrates how to list configuration values across different scopes or retrieve a specific key's value. It utilizes the ConfigAction enum to perform operations on the builder. ```rust use clapfig::{Clapfig, SearchPath, ConfigAction, ConfigResult}; let builder = Clapfig::builder::() .app_name("myapp") .persist_scope("local", SearchPath::Cwd); // List all resolved values (merged from all sources) let result = builder.clone().handle(&ConfigAction::List { scope: None })?; match result { ConfigResult::Listing { entries } => { for (key, value) in entries { println!("{key} = {value}"); } } _ => {} } // List values from specific scope file only let result = builder.clone().handle(&ConfigAction::List { scope: Some("local".into()), })?; // Get a single key's value let result = builder.clone().handle(&ConfigAction::Get { key: "database.url".into(), scope: None, })?; match result { ConfigResult::KeyValue { key, value } => println!("{key} = {value}"), _ => {} } ``` -------------------------------- ### Integrate Clapfig with Clap CLI Source: https://context7.com/arthur-debert/clapfig/llms.txt Integrates ConfigArgs into a Clap-based CLI application to automatically provide configuration management subcommands like gen, list, get, set, and unset. ```rust use clap::{Parser, Subcommand}; use clapfig::{Clapfig, ConfigArgs, SearchPath}; #[derive(Parser)] struct Cli { #[arg(long)] port: Option, #[command(subcommand)] command: Commands, } #[derive(Subcommand)] enum Commands { /// Run the server Run, /// Manage configuration Config(ConfigArgs), } fn main() -> anyhow::Result<()> { let cli = Cli::parse(); let builder = Clapfig::builder::() .app_name("myapp") .persist_scope("local", SearchPath::Cwd) .cli_override("port", cli.port.map(i64::from)); match cli.command { Commands::Run => { let config = builder.load()?; println!("Running on port {}", config.port); } Commands::Config(args) => { let action = args.into_action(); builder.handle_and_print(&action)?; } } Ok(()) } ``` -------------------------------- ### Basic Configuration Loading with Clapfig Builder Source: https://context7.com/arthur-debert/clapfig/llms.txt Shows the basic usage of Clapfig to load application configuration. It utilizes the `Clapfig::builder()` entry point and `app_name()` to derive default file names, search paths, and environment variable prefixes. The `load()` method merges configurations and fills in default values. ```rust use clapfig::Clapfig; fn main() -> anyhow::Result<()> { // Minimal setup: app_name derives all defaults let config: AppConfig = Clapfig::builder() .app_name("myapp") .load()?; // Searches for myapp.toml in platform config dir // Merges MYAPP__* env vars // Fills in #[config(default)] values println!("Listening on {}:{}", config.host, config.port); Ok(()) } ``` -------------------------------- ### Load Configuration with Clapfig Builder Source: https://github.com/arthur-debert/clapfig/blob/main/README.md Initialize and load your configuration using the Clapfig builder. This automatically searches for config files and merges environment variables based on the app name. ```rust use clapfig::Clapfig; fn main() -> anyhow::Result<()> { let config: AppConfig = Clapfig::builder() .app_name("myapp") .load()?; println!("Listening on {}:{}", config.host, config.port); Ok(()) } ``` -------------------------------- ### Customizing Configuration Search Paths in Rust Source: https://context7.com/arthur-debert/clapfig/llms.txt Illustrates how to define custom search paths for configuration files using `clapfig::SearchPath`. This allows specifying directories like platform-specific locations, home directories, explicit paths, and the current working directory in a prioritized order. It also shows how to use `SearchPath::Ancestors` for searching up to a project boundary. ```rust use clapfig::{Clapfig, SearchPath, Boundary}; let config: AppConfig = Clapfig::builder() .app_name("myapp") .file_name("config.toml") .search_paths(vec![ SearchPath::Platform, // XDG on Linux, ~/Library/Application Support on macOS SearchPath::Home(".myapp"), // ~/.myapp/ SearchPath::Path("/etc/myapp".into()), // Explicit path for system-wide defaults SearchPath::Cwd, // Current working directory (highest priority) ]) .load()?; // Or use ancestor walk to find project configs (like .editorconfig) let config: AppConfig = Clapfig::builder() .app_name("myapp") .search_paths(vec![ SearchPath::Platform, SearchPath::Ancestors(Boundary::Marker(".git")), // Walk up to repo root ]) .load()?; ``` -------------------------------- ### Loading Configuration from URL Query Parameters in Rust Source: https://context7.com/arthur-debert/clapfig/llms.txt Shows how to load configuration from URL query parameters using Clapfig, which requires the `url` feature to be enabled. This provides a per-request configuration layer, useful for WASM or server-side applications. The query parameters are parsed and applied to the configuration. ```rust // Cargo.toml: clapfig = { version = "...", features = ["url"] } use clapfig::Clapfig; // Query: ?port=9090&database.url=pg%3A%2F%2Fprod&debug=true let query = "port=9090&database.url=pg%3A%2F%2Fprod&debug=true"; let config: AppConfig = Clapfig::builder() .app_name("myapp") .url_query(query) .load()?; // port = 9090 (integer) // database.url = "pg://prod" (percent-decoded) // debug = true (bool) ``` -------------------------------- ### Generate Configuration Templates Source: https://context7.com/arthur-debert/clapfig/llms.txt Shows how to generate a TOML template based on the configuration struct's documentation and default values. The output can be directed to standard output or a specific file. ```rust use clapfig::{Clapfig, ConfigAction, ConfigResult}; use std::path::PathBuf; // Generate template to stdout let result = Clapfig::builder::() .app_name("myapp") .handle(&ConfigAction::Gen { output: None })?; match result { ConfigResult::Template(content) => println!("{}", content), _ => {} } // Write template directly to file Clapfig::builder::() .app_name("myapp") .handle(&ConfigAction::Gen { output: Some(PathBuf::from("config.template.toml")), })?; ``` -------------------------------- ### Loading Config with Environment Variables in Rust Source: https://context7.com/arthur-debert/clapfig/llms.txt Demonstrates how to load configuration from environment variables using Clapfig. Environment variables are mapped to config keys using double-underscore separators and parsed heuristically. It shows how to set the application name for the environment prefix and how to disable environment variable loading. ```rust use clapfig::Clapfig; // With app_name("myapp"), env prefix is MYAPP // MYAPP__HOST=0.0.0.0 -> host = "0.0.0.0" // MYAPP__PORT=9000 -> port = 9000 // MYAPP__DATABASE__URL=pg://x -> database.url = "pg://x" // MYAPP__DEBUG=true -> debug = true let config: AppConfig = Clapfig::builder() .app_name("myapp") .load()?; // Custom env prefix let config: AppConfig = Clapfig::builder() .app_name("myapp") .env_prefix("CUSTOM_PREFIX") .load()?; // Disable env var loading entirely (useful for tests) let config: AppConfig = Clapfig::builder() .app_name("myapp") .no_env() .load()?; ``` -------------------------------- ### Persisting Configuration Scopes and Actions in Rust with Clapfig Source: https://context7.com/arthur-debert/clapfig/llms.txt Demonstrates how to manage configuration persistence scopes and actions in Clapfig. Named scopes like 'local' and 'global' can be defined with associated search paths. The `handle()` method with `ConfigAction` allows setting, unsetting, or modifying configuration values within specified scopes. ```rust use clapfig::{Clapfig, SearchPath, ConfigAction}; let builder = Clapfig::builder::() .app_name("myapp") .persist_scope("local", SearchPath::Cwd) .persist_scope("global", SearchPath::Platform); // Set a value (writes to default "local" scope) builder.clone().handle(&ConfigAction::Set { key: "port".into(), value: "9000".into(), scope: None, })?; // Set a value in specific scope builder.clone().handle(&ConfigAction::Set { key: "host".into(), value: "0.0.0.0".into(), scope: Some("global".into()), })?; // Unset a value builder.clone().handle(&ConfigAction::Unset { key: "port".into(), scope: None, })?; ``` -------------------------------- ### Clapfig Configuration Builder Source: https://context7.com/arthur-debert/clapfig/llms.txt The primary interface for building and loading application configurations using the Clapfig builder pattern. ```APIDOC ## BUILDER CONFIGURATION ### Description Initializes the application configuration builder, defines search paths, and sets up persistence scopes. ### Method Rust Builder Pattern ### Parameters #### Builder Methods - **app_name** (String) - Required - Sets the application name for config file discovery. - **search_paths** (Vec) - Optional - Defines where to look for configuration files. - **persist_scope** (String, SearchPath) - Optional - Configures scopes for saving configuration changes. - **cli_override** (String, Option) - Optional - Manually overrides specific configuration keys with CLI values. ### Request Example let builder = Clapfig::builder::() .app_name("myapp") .search_paths(vec![SearchPath::Platform, SearchPath::Home(".myapp")]) .persist_scope("local", SearchPath::Cwd); ``` -------------------------------- ### Programmatic Configuration Overrides with Clapfig in Rust Source: https://context7.com/arthur-debert/clapfig/llms.txt Illustrates how to override configuration values programmatically or via CLI arguments using Clapfig. It covers manual overrides for specific keys using `cli_override()` and automatic matching from a struct (or any `Serialize` type) using `cli_overrides_from()`. Note that `None` values are skipped and non-matching keys are ignored. ```rust use clapfig::Clapfig; use serde::Serialize; // Manual override for specific keys let config: AppConfig = Clapfig::builder() .app_name("myapp") .cli_override("port", Some(9999i64)) .cli_override("database.url", Some("pg://prod")) .cli_override("debug", Some(true)) .load()?; // Auto-match from a clap struct (or any Serialize type) #[derive(Serialize)] struct CliArgs { host: Option, port: Option, verbose: bool, // Non-matching keys are silently ignored } let args = CliArgs { host: Some("0.0.0.0".into()), port: None, // None values are skipped verbose: true, }; let config: AppConfig = Clapfig::builder() .app_name("myapp") .cli_overrides_from(&args) // Auto-matches host .cli_override("database.url", Some("pg://cli")) // Nested keys need manual mapping .load()?; ``` -------------------------------- ### Define Configuration Structs with Confique Source: https://github.com/arthur-debert/clapfig/blob/main/README.md Use the Config derive macro to define application settings with default values and nested structures. This serves as the source of truth for your application configuration. ```rust use confique::Config; use serde::{Serialize, Deserialize}; #[derive(Config, Serialize, Deserialize, Debug)] pub struct AppConfig { /// The host address to bind to. #[config(default = "127.0.0.1")] pub host: String, /// The port number. #[config(default = 8080)] pub port: u16, /// Database settings. #[config(nested)] pub database: DbConfig, } #[derive(Config, Serialize, Deserialize, Debug)] pub struct DbConfig { /// Connection string URL. pub url: Option, /// Connection pool size. #[config(default = 10)] pub pool_size: usize, } ``` -------------------------------- ### Error Handling Source: https://context7.com/arthur-debert/clapfig/llms.txt Handling configuration loading errors using the ClapfigError enum. ```APIDOC ## ERROR HANDLING ### Description Detailed error handling for configuration loading, providing specific feedback on missing keys, invalid values, or misconfigured scopes. ### Response #### Error Types - **UnknownKey** - The provided configuration file contains an unrecognized key. - **KeyNotFound** - A required configuration key is missing. - **InvalidValue** - The value provided for a key failed validation. - **UnknownScope** - The requested persistence scope is not defined. ### Response Example match result { Err(ClapfigError::UnknownKey { key, path, line }) => { eprintln!("Unknown key '{}' in {} (line {})", key, path.display(), line); } _ => eprintln!("Error loading configuration") } ``` -------------------------------- ### Customizing Layer Order in Clapfig (Rust) Source: https://context7.com/arthur-debert/clapfig/llms.txt Explains how to customize the precedence of configuration layers in Clapfig using the `layer_order()` method. The default order is Files < Env < URL < Cli. This allows users to define a custom override behavior, such as having files override environment variables, or excluding a layer entirely. ```rust use clapfig::{Clapfig, Layer}; // Default: CLI overrides everything let config: AppConfig = Clapfig::builder() .app_name("myapp") .load()?; // Custom: Files override env vars (CLI still wins) let config: AppConfig = Clapfig::builder() .app_name("myapp") .layer_order(vec![Layer::Env, Layer::Files, Layer::Cli]) .load()?; // Exclude a layer entirely (no env vars in merge) let config: AppConfig = Clapfig::builder() .app_name("myapp") .layer_order(vec![Layer::Files, Layer::Cli]) .load()?; ``` -------------------------------- ### Handle Clapfig Errors in Rust Source: https://context7.com/arthur-debert/clapfig/llms.txt Demonstrates how to match against the ClapfigError enum to provide user-friendly feedback. It covers common failure scenarios such as unknown keys, missing values, and configuration builder misconfigurations. ```rust use clapfig::{Clapfig, ClapfigError, SearchPath, ConfigAction}; let result: Result = Clapfig::builder() .app_name("myapp") .load(); match result { Ok(config) => println!("Loaded: {:?}", config), Err(ClapfigError::UnknownKey { key, path, line }) => { eprintln!("Unknown key '{}' in {} (line {})", key, path.display(), line); } Err(ClapfigError::KeyNotFound(key)) => { eprintln!("Key not found: {}", key); } Err(ClapfigError::InvalidValue { key, reason }) => { eprintln!("Invalid value for '{}': {}", key, reason); } Err(ClapfigError::UnknownScope { scope, available }) => { eprintln!("Unknown scope '{}'. Available: {}", scope, available.join(", ")); } Err(ClapfigError::NoPersistPath) => { eprintln!("No persist scope configured. Call .persist_scope() on the builder."); } Err(ClapfigError::AppNameRequired) => { eprintln!("App name is required. Call .app_name() on the builder."); } Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Configuring Search Modes for Configuration Loading in Rust Source: https://context7.com/arthur-debert/clapfig/llms.txt Explains the two search modes for resolving multiple configuration files: `SearchMode::Merge` (default) and `SearchMode::FirstMatch`. `Merge` deep-merges all found files, while `FirstMatch` uses only the highest-priority file encountered. This allows control over how configurations from different sources are combined. ```rust use clapfig::{Clapfig, SearchPath, SearchMode}; // Merge mode (default): deep-merge all found files let config: AppConfig = Clapfig::builder() .app_name("myapp") .search_paths(vec![SearchPath::Platform, SearchPath::Cwd]) .search_mode(SearchMode::Merge) .load()?; // Global config provides defaults, project config overrides specific keys // FirstMatch mode: use only the highest-priority file found let config: AppConfig = Clapfig::builder() .app_name("myapp") .search_paths(vec![SearchPath::Platform, SearchPath::Cwd]) .search_mode(SearchMode::FirstMatch) .load()?; // Config in cwd used as-is; platform config ignored if cwd has one ``` -------------------------------- ### Strict vs. Lenient Mode Configuration Loading in Rust Source: https://context7.com/arthur-debert/clapfig/llms.txt Explains the strict and lenient modes for configuration loading in Clapfig. Strict mode (enabled by default) errors on unknown keys in configuration files to catch typos and stale entries. Lenient mode ignores unknown keys, which can be useful in certain scenarios. ```rust use clapfig::Clapfig; // Strict mode (default): unknown keys error let result: Result = Clapfig::builder() .app_name("myapp") .strict(true) .load(); // Error: Unknown key 'typo_key' in /path/to/config.toml (line 5) // Lenient mode: ignore unknown keys let config: AppConfig = Clapfig::builder() .app_name("myapp") .strict(false) .load()?; ``` -------------------------------- ### Define Rust Config Struct with Confique Derive Source: https://context7.com/arthur-debert/clapfig/llms.txt Demonstrates how to define a configuration structure using `confique::Config` derive macro. This struct serves as the single source of truth for defaults, documentation, and validation. It includes nested configurations and default values for fields. ```rust use confique::Config; use serde::{Serialize, Deserialize}; #[derive(Config, Serialize, Deserialize, Debug)] pub struct AppConfig { /// The host address to bind to. #[config(default = "127.0.0.1")] pub host: String, /// The port number. #[config(default = 8080)] pub port: u16, /// Enable debug mode. #[config(default = false)] pub debug: bool, /// Database settings. #[config(nested)] pub database: DbConfig, } #[derive(Config, Serialize, Deserialize, Debug)] pub struct DbConfig { /// Connection string URL. pub url: Option, /// Connection pool size. #[config(default = 10)] pub pool_size: usize, } ``` -------------------------------- ### Customize Clapfig Subcommands and Flags Source: https://context7.com/arthur-debert/clapfig/llms.txt Utilizes ConfigCommand to rename subcommands and flags to avoid conflicts with existing CLI structures, allowing for a custom interface for configuration management. ```rust use clap::Command; use clapfig::{Clapfig, ConfigCommand, SearchPath}; let config_cmd = ConfigCommand::new() .scope_long("target") // Rename --scope to --target .gen_name("template") // Rename "gen" to "template" .set_name("write") // Rename "set" to "write" .get_name("read"); // Rename "get" to "read" let app = Command::new("myapp") .subcommand(config_cmd.as_command("settings")); let matches = app.get_matches(); if let Some(("settings", sub)) = matches.subcommand() { let action = config_cmd.parse(sub)?; let builder = Clapfig::builder::() .app_name("myapp") .persist_scope("local", SearchPath::Cwd); builder.handle_and_print(&action)?; } ``` -------------------------------- ### Customize Layer Precedence Source: https://github.com/arthur-debert/clapfig/blob/main/README.md Adjust the order in which configuration layers are merged. Layers listed later in the vector override those listed earlier. ```rust use clapfig::{Clapfig, Layer}; let config: AppConfig = Clapfig::builder() .app_name("myapp") .layer_order(vec![Layer::Env, Layer::Files, Layer::Cli]) .load()?; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.