Envhead is a crate to create environment variables with a static prefix. Works great, e.g. with the popular clap crate.
Go to file
2023-11-10 18:41:52 +01:00
.idea Initial 2023-11-10 18:41:52 +01:00
src Initial 2023-11-10 18:41:52 +01:00
.gitignore Initial 2023-11-10 18:41:52 +01:00
Cargo.toml Initial 2023-11-10 18:41:52 +01:00
LICENSE Initial 2023-11-10 18:41:52 +01:00
README.md Initial 2023-11-10 18:41:52 +01:00

Envhead

Envhead is a crate that creates environment variable names using a static prefix. The desired prefix is defined in your build script build.rs.

Usage

First, you should define the prefix in your build.rs file. In this example, we will use MY_APP as the prefix:

fn main() {
    println!("cargo:rustc-env=ENV_HEAD_PREFIX=MY_APP");
}

When the ENV_HEAD_PREFIX variable is not defined, ENV is used as the default prefix.

Then, in your code, you can use the envhead! macro to create environment variable names.

use envhead::envhead;

fn main() {
    let env_var = envhead!("server_port");

    // Prints "MY_APP_SERVER_PORT":
    println!("{}", env_var);
}

You might find it useful to use envhead together with clap to create environment variable names for your command line arguments:

use clap::Args;
use envhead::envhead;

#[derive(Debug, Args)]
pub struct ServerArgs {
    #[arg(
        short = 'p', long,
        required = false,
        value_name = "port",
        value_hint = clap::ValueHint::Other,
        help = "The server's port.",
        default_value_t = 8000,
        env = envhead!("server_port"),
    )]
    pub port: u16,

    #[arg(
        long,
        required = true,
        value_name = "SECRET_TOKEN",
        value_hint = clap::ValueHint::Other,
        help = "The secret token to authenticate the client.",
        env = envhead!("server_secret_token"),
    )]
    pub secret_token: Option<String>,
}

Changelog

Version 1.0.0

  • Initial release