Env Settings

Env Settings is a Rust library that helps you to initialize structs using environment variables

This Rust library took inspiration from pydantic's BaseSettings Python class

Installation

sh cargo add env-settings cargo add env-settings-derive

Usage

When you add the EnvSettings derive to a struct, two methods are added to it

Basic

sh export name=paolo export age=42

```rs use envsettingsderive::EnvSettings;

[derive(EnvSettings)]

struct MyStruct { name: String,

age: u8,

}

fn main() { let mystruct = MyStruct::fromenv().unwrap(); asserteq!(mystruct.name, "paolo".tostring()); asserteq!(my_struct.age, 42);

let name = "luca";
let my_struct = MyStruct::new(Some(name.to_string()), None).unwrap();
assert_eq!(my_struct.name, name);
assert_eq!(my_struct.age, 42);

} ```

Advanced

sh echo "MY_STRUCT_AGE=42\n" > .env export MY_BIRTH_DATE=01/01/1970

```rs use envsettingsderive::EnvSettings;

[derive(EnvSettings)]

[envsettings(caseinsensitive, filepath = ".env", prefix="MYSTRUCT_")]

struct MyStruct { #[env_settings(default = "paolo")] name: String,

age: u8,

#[env_settings(variable = "MY_BIRTH_DATE")]
birth_date: String,

}

fn main() { let mystruct = MyStruct::fromenv().unwrap(); asserteq!(mystruct.name, "paolo".tostring()); asserteq!(mystruct.age, 42); asserteq!(mystruct.birthdate, "01/01/1970");

let name = "luca";
let my_struct = MyStruct::new(Some(name.to_string()), None,  None).unwrap();
assert_eq!(my_struct.name, name);
assert_eq!(my_struct.age, 42);
assert_eq!(my_struct.birth_date, "01/01/1970");

} ```

Parameters

Struct

The current supported parameters for the structs are:

Field

The current supported parameters for the fields are:

Variables resolution hierarchy

  1. Arguments passed to the new method (if using new).
  2. Environment variables
  3. Variables loaded from a file (e.g. .env)
  4. Default values

Contribute

Before starting to work on a contribution please read:

Run tests

When testing run:

sh cargo test -- --test-threads=1

to prevent tests from competitively interacting with the same file

License

This project is licensed under the terms of the MIT or Apache 2.0 license.