cnfg 0.1.0

Configuration + validation for Rust: load from files, env, CLI, then validate with schema annotations.
Documentation

cnfg 🧩

Configuration + Validation for Rust

cnfg makes it easy to build robust Rust applications with configuration that can be loaded from files, environment variables, and CLI arguments, and validated against a schema using simple annotations.

  • ✅ Load from JSON / YAML / TOML files
  • ✅ Merge with environment variables (with optional prefixes)
  • ✅ Override via CLI arguments (powered by clap)
  • ✅ Enforce constraints with #[derive(Validate)]
  • ✅ Strongly typed configuration structs with serde

✨ Example

use cnfg::{Config, Validate};
use serde::Deserialize;
use clap::Parser;

#[derive(Debug, Deserialize, Validate)]
struct AppConfig {
    #[validate(range(min = 1024, max = 65535))]
    port: u16,

    #[validate(length(min = 10))]
    database_url: String,
}

#[derive(Parser, Debug)]
struct Args {
    #[arg(long)]
    port: Option<String>,

    #[arg(long)]
    database_url: Option<String>,
}

fn main() {
    let cfg: AppConfig = Config::new()
        .from_file("config.yaml")
        .add_env_prefixed("MYAPP_")
        .add_cli::<Args>()
        .build()
        .unwrap();

    println!("✅ Loaded config: {:?}", cfg);
}

config.yaml:

port: 8080
database_url: postgres://localhost:5432/app

Run with overrides:

MYAPP_PORT=9000 cargo run -- --database-url sqlite://test.db

Output:

✅ Loaded config: AppConfig { port: 9000, database_url: "sqlite://test.db" }

🚀 Installation

Add to your Cargo.toml:

[dependencies]

cnfg = "0.1"


📦 Features

  • FileSource → Load from JSON, YAML, TOML

  • EnvSource → Flatten or prefix environment variables into config

  • CliSource → Auto-merge CLI arguments via clap

  • Validation → Built-in annotations:

    • #[validate(range(min, max))]
    • #[validate(length(min, max))]
    • more coming soon!
  • Deep merging of multiple sources


🛠 Roadmap

  • Pretty error messages with miette
  • More validators: regex, enum, required
  • Remote sources (HTTP, Consul, Vault, etc.)
  • Config hot-reloading

📚 Documentation


⚖️ License

Licensed under:


💡 Contributing

Contributions are welcome! Please open issues or pull requests on GitHub.