Crate env_config[][src]

Expand description

Adds proc macro that adds methods to parse environment variables and write documentation using doc-writer.

Examples

#![allow(dead_code)]

use doc_writer::DocumentationWriter;
use env_config::EnvConfig;
use std::str::FromStr;

#[derive(EnvConfig)]
#[env(prefix = "SERVER_")]
pub struct Config {
    /// Timeout in milliseconds.
    #[env(rename = "timeout")]
    timeout_millis: u32,

    /// The verbosity level.
    #[env(no_prefix)]
    verbosity_level: Verbosity,

    /// The address to listen on.
    #[env(skip, flatten)] // TODO implement flatten and remove skip
    address: Address,

    /// Process ID of the current process. Read automatically.
    #[env(skip)]
    process_id: u64,
}

#[derive(EnvConfig)]
pub struct Address {
    /// The domain to listen on.
    domain: String,

    /// The port to listen on.
    #[env(default = 80)]
    port: u16,
}

#[derive(EnvConfig, Debug, Eq, PartialEq)]
#[env(rename_all = "lowercase")]
pub enum Verbosity {
    /// Log informational, warning, and error messages.
    Info,
    /// Log warning and error messages.
    #[env(default)]
    Warning,
    /// Log error messages.
    #[env(rename = "Error")]
    Panic,
    /// Log nothing. Cannot be set manually only activated by `--batch-mode`.
    #[env(skip)]
    Silent,
}

fn main() {
    let mut md = Vec::<u8>::new();
    let mut doc = doc_writer::render::MarkdownWriter::new(&mut md);
    doc.start_environment().unwrap();
    Config::from_env(vec![].into_iter())
        .unwrap()
        .document_env(&mut doc)
        .unwrap();
    doc.start_enum("Verbosity").unwrap();
    Verbosity::document_enum(&mut doc).unwrap();
    println!("{}", String::from_utf8(md).unwrap().trim());

    assert_eq!(80, Address::default().port);

    assert_eq!(Verbosity::Warning, Verbosity::default());
    assert_eq!(Verbosity::Panic, Verbosity::from_str("ErRoR").unwrap());

    assert!(Verbosity::from_str("silent").is_err());
    assert!(Verbosity::from_str("panic").is_err());

Would yield the following documentation:

Environment

  • SERVER_TIMEOUT=0: Timeout in milliseconds.
  • VERBOSITY_LEVEL=warning: The verbosity level.

Verbosity

  • info: Log informational, warning, and error messages.
  • warning: Log warning and error messages.
  • error: Log error messages.

Derive Macros

Derives EnvConfig as described in the module description.