EnvVar

Derive Macro EnvVar 

Source
#[derive(EnvVar)]
{
    // Attributes available to this derive:
    #[case]
    #[var_name]
    #[default]
    #[panic_on_invalid]
    #[ignore_variant]
}
Expand description

This proc macro is applied to enums and implements the EnvVar trait, which provides a .get() method to retrieve a value of type T from an environment variable.

The macro parses the environment variable to the enum type and requires one of the following:

  • A variant called “Invalid”, which will be returned if the environment variable does not match any of the variants.
  • A variant marked with #[default], which will be returned if the environment variable does not match any of the variants.
  • The enum to be marked with #[panic_on_invalid], which will panic if the environment variable does not match any of the variants.

The macro supports the following attributes on the enum itself:

  • #[env_var = "FOO"]: Set a custom environment variable name to search for. Defaults to the name of the enum in uppercase.
  • #[panic_on_invalid]: Panics if a valid variant is not found.
  • #[case(convert = "[uppercase|lowercase|exact|any]")]: Converts all environment variable values to a specific case before comparing them to map the valid variant. This attribute is overwritten if the variant also contains this attribute.

The macro also supports the following attributes on the enum variants:

  • #[case = "[uppercase|lowercase|exact|any]"]: Specifies case conversion for the annotated enum variant. The uppercase and lowercase options convert the environment variable value to uppercase or lowercase before comparing it to the variant name. The exact option compares the environment variable value to the variant name without any case conversion. The any option converts both the environment variable value and the variant name to lowercase before comparing them.
  • #[default]: Specifies the default enum variant.
  • #[ignore_variant]: Ignores the annotated enum variant when checking for a match.

Example usage:

use env_extract::EnvVar;

#[derive(EnvVar)]
#[var_name = "DATABASE_TYPE"]
#[case(convert = "uppercase")]
enum DatabaseType {
    #[case(convert = "lowercase")]
    Postgres,
    Mysql,

    #[default]
    Sqlite,
}

fn main() {
    std::env::set_var("DATABASE_TYPE", "MYSQL");

    let database_type = DatabaseType::get();
    assert!(matches!(database_type, DatabaseType::Mysql));
}

In the example above, the EnvVar trait is implemented for the DatabaseType enum, allowing the retrieval of a value from the “DATABASE_TYPE” environment variable. The enum variants are compared to the environment variable value after applying case conversions specified by the #[case] attributes. The Mysql variant is matched since the environment variable value is converted to uppercase and the variant name to lowercase, resulting in a match.