envhead

Crates.ioenvhead
lib.rsenvhead
version1.0.0
sourcesrc
created_at2023-11-10 19:08:52.492647
updated_at2023-11-10 19:08:52.492647
descriptionA crate to build environment variable names using a static prefix. Works great with the popular clap crate.
homepagehttps://devops.tsommer.org/open-source/rust/crates/envhead
repositoryhttps://devops.tsommer.org/open-source/rust/crates/envhead
max_upload_size
id1031419
size8,519
Thorsten Sommer (SommerEngineering)

documentation

README

Envhead

Envhead is a crate that creates environment variable names using a static prefix.

Setup

First, you should define the prefix by setting the ENV_HEAD_PREFIX environment variable to the desired value. When the ENV_HEAD_PREFIX variable is not defined, ENV is used as the default prefix. In the following examples, we will use MY_APP as the prefix.

In case you are working with macOS or Linux, you might use Bash like this:

ENV_HEAD_PREFIX=MY_APP cargo build

Using an IDE from JetBrains like RustRover, you can set the environment variable in the run configuration and for your integrated terminal.

Do you use a CI/CD pipeline? You can set the environment variable in your pipeline configuration. Do you build your application in a Docker container? You can set the environment variable in your Dockerfile as well.

Please notice: This setup procedure is required just for the development environment. Your compiled program(s) will not depend on the ENV_HEAD_PREFIX environment variable.

Usage

Now, 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
Commit count: 0

cargo fmt