Loads environment variables into your structs in one shot.

Overview

econf

Loads environment variables into your structs in one shot.

Latest version Documentation License Actions Status

econf allows to override struct fields with environment variables easily. This is useful to build up applications that optionally overrides some configuration with environment variables. Here is the basic usage:

use econf::LoadEnv;

#[derive(Debug, LoadEnv)]
struct A {
    x: bool,
    y: u64,
}

fn main() {
    let a = A {
        x: true,
        y: 42,
    };
    println!("Before: {:?}", a);

    let a = econf::load(a, "PREFIX");
    println!("After:  {:?}", a);
}
$ ./app
Before: A { x: true, y: 42 }
After:  A { x: true, y: 42 }

$ PREFIX_X=false ./app
Before: A { x: true, y: 42 }
After:  A { x: false, y: 42 }

In this example,

  • PREFIX_X is loaded to x
  • PREFIX_Y is loaded to y

The environment variables are all upper-case with _ separated.

Why econf?

There are some existing crates that provide similar features but econf is unique in the following ways:

  • Supports nesting: Supports nested structs in an intutive manner with a little constraint.
  • Supports containers: Supports Vec, HashMap and various types.
  • Supplemental: Loads into existing variables in the code without changing the original logic.
  • Contributor friendly: Simple code base. Comprehensible with a little study on basic macro usage.

Supported types

  • Boolean: bool
  • Integer: isize, usize, i8, i16,i32,i64,i128, u8,u16,u32,u64,u128
  • String: char, String
  • Float: f32, f64
  • Network: IpAddr,Ipv4Addr,Ipv6Addr,SocketAddr,SocketAddrV4,SocketAddrV6
  • Non-zero types: NonZeroI128,NonZeroI16,NonZeroI32,NonZeroI64,NonZeroI8,NonZeroIsize,NonZeroU128, NonZeroU16,NonZeroU32,NonZeroU64,NonZeroU8, NonZeroUsize
  • File system: PathBuf
  • Containers: Vec, HashSet, HashMap, Option, BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque, tuple
    • Containers are parsed as YAML format. See the tests.

Nesting

Nested structs are supported.

#[derive(LoadEnv)]
struct A {
    v1: usize,
    v2: B,
}

#[derive(LoadEnv)]
struct B {
    v1: usize,
    v2: usize,
}

fn main() {
    let a = A {
        v1: 1,
        v2: B {
            v1: 2,
            v2: 3,
        },
    };

    let a = econf::load(a, "PREFIX");
}

In this example,

  • PREFIX_V1 is loaded to a.v1
  • PREFIX_V2_V1 is loaded to a.v2.v1
  • PREFIX_V2_V2 is loaded to a.v2.v2

Fields in child structs can be specified by chaining the field names with _ as a separator. However, there're cases that names conflict. For example,

#[derive(LoadEnv)]
struct A {
    v2_v1: usize,
    v2: B,
}

#[derive(LoadEnv)]
struct B {
    v1: usize,
    v2: usize,
}

fn main() {
    let a = A {
        v2_v1: 1,
        v2: B {
            v1: 2,
            v2: 3,
        },
    };

    let a = econf::load(a, "PREFIX");
}

Here PREFIX_V2_V1 corresponds to both a.v2_v1 and a.v2.v1. In this case, econf prints warning through log facade and the value is loaded to both a.v2_v1 and a.v2.v1.

Skipping fields

Fields that do not implement LoadEnv or simply should not be loaded by econf can be skipped by adding the #[econf(skip)] helper attribute:

#[derive(LoadEnv)]
struct A {
    x: bool,
    #[econf(skip)]
    y: u64, // will not be loaded by econf
}

License: MIT

You might also like...
Set Shell Environment Variables across multiple shells with a single configuration file.

Xshe – Cross-Shell Environment Vars xshe allows for setting Shell Environment Variables across multiple shells with a single TOML configuration file.

Rust Lambda Extension for any Runtime to preload SSM Parameters as  πŸ” Secure Environment Variables!
Rust Lambda Extension for any Runtime to preload SSM Parameters as πŸ” Secure Environment Variables!

πŸ›‘ Crypteia Rust Lambda Extension for any Runtime to preload SSM Parameters as Secure Environment Variables! Super fast and only performaned once duri

A Modern And Secure CLI Tool For Managing Environment Variables
A Modern And Secure CLI Tool For Managing Environment Variables

Envio is a command-line tool that simplifies the management of environment variables across multiple profiles. It allows users to easily switch between different configurations and apply them to their current environment

This is a webpack loader that loads Rust code as a WebAssembly module

rust-native-wasm-loader This is a webpack loader that loads Rust code as a WebAssembly module. It uses the native Rust support for compiling to wasm32

A tool and library to losslessly join multiple .mp4 files shot with same camera and settings

mp4-merge A tool and library to losslessly join multiple .mp4 files shot with same camera and settings. This is useful to merge multiple files that ar

πŸ™ Loads config and hosts for gh CLI in Rust.

gh-config-rs Loads config and hosts for gh CLI in Rust. Getting started [dependencies] gh-config = "0.2" Usage use std::error::Error; use gh_config::*

Static-checked parsing of regexes into structs

Statically-checked regex parsing into structs. This avoids common regex pitfalls like Off by one capture indexes Trying to get nonexistent captures De

A simple menu to keep all your most used one-liners and scripts in one place
A simple menu to keep all your most used one-liners and scripts in one place

Dama Desktop Agnostic Menu Aggregate This program aims to be a hackable, easy to use menu that can be paired to lightweight window managers in order t

Solving context limits when working with AI LLM models by implementing a "chunkable" attribute on your prompt structs.

Promptize Promptize attempts to solve the issues with context limits when working with AI systems. It allows a user to add an attribute to their struc

By mirroring traffic to and from your machine, mirrord surrounds your local service with a mirror image of its cloud environment.
By mirroring traffic to and from your machine, mirrord surrounds your local service with a mirror image of its cloud environment.

mirrord lets you easily mirror traffic from your Kubernetes cluster to your development environment. It comes as both Visual Studio Code extension and

A Yocto setup and management tool that helps you keep your environment up-to-date and in-sync with your team
A Yocto setup and management tool that helps you keep your environment up-to-date and in-sync with your team

yb (Yocto Buddy) yb is designed to make it easy to setup and (perhaps more importantly) keep Yocto environments up-to-date and in-sync with your team.

Quickly setup your development environment on your Chromebook/ChromeOS  or any Linux distribution 🐧 ❄️ πŸ’» πŸš€ ✨
Quickly setup your development environment on your Chromebook/ChromeOS or any Linux distribution 🐧 ❄️ πŸ’» πŸš€ ✨

Crosup 🐧 πŸ’» πŸš€ ✨ Crosup is a CLI tool to help you quickly setup your development environment on a new Chromebook (ChromeOS) or any Linux distribution

Rust Programming Fundamentals - one course to rule them all, one course to find them...

Ultimate Rust Crash Course This is the companion repository for the Ultimate Rust Crash Course published online, presented live at O'Reilly virtual ev

A super simple /sbin/init for Linux which allows running one and only one program

Summary High-performance /sbin/init program for Linux This is designed to do literally nothing but accept binaries over the network and run them as a

Fast, initializable, and thread safe static variables

tagged_cell Fast, initializable, and thread safe static variables Overview Borrows the excellent ZST based tagging implementation (linked below) to gu

Rust crate that provides a convenient macro to quickly plot variables.
Rust crate that provides a convenient macro to quickly plot variables.

Debug Plotter This crate provides a convenient macro to quickly plot variables. Documentation For more information on how to use this crate, please ta

Easy reading and writing of `serde` structs to/from Google Sheets

serde_sheets Read and write structs directly from google sheets using serde and csv Implement serde::Serialize to write and serde::Deserialize to read

Simple validation for Rust structs

validator Macros 1.1 custom derive to simplify struct validation inspired by marshmallow and Django validators. The minimum supported version is Rust

A Rust proc-macro crate which derives functions to compile and parse back enums and structs to and from a bytecode representation

Bytecode A simple way to derive bytecode for you Enums and Structs. What is this This is a crate that provides a proc macro which will derive bytecode

Comments
  • Implement rename helper attribute

    Implement rename helper attribute

    Thank you for the lovely crate! I implemented "rename" attribute like #[serde(rename)] because I encountered the case I would like to separate field names and environment variable names.

    Overview

    For instance, if we set an environment variable as ENV_VARIABLE_A, need to prepare the following Rust struct:

    #[derive(LoadEnv)]
    struct Example {
        env_variable_a: String,
    }
    

    Suppose we'd like to name the field as a. In this case, we can leverage the rename attribute:

    #[derive(LoadEnv)]
    struct Example {
        #[econf(rename = "env_variable_a")]
        a: String, // we can rename field's name as we like
    }
    
    enhancement 
    opened by yuk1ty 0
  • Version 0.2

    Version 0.2

    • Introduce Loader to abstract duplication check, loading, parsing.
    • Change LoadEnv trait interface which receives Loader
    • Update documents

    econf 0.1 and econf-derive 0.2 are not compatible and vice versa

    breaking-change 
    opened by YushiOMOTE 0
  • Mapping options to nested structs

    Mapping options to nested structs

    Hey! I love how simple this library is and wanted to use it on something I'm writing. I came across something I got confused about and wanted to know if there was a way I wasn't immediately obvious to.

    Specifically, I have an option value that I would expect to get parsed in a bit different of a way:

    For example, I have:

    #[derive(Debug, Default, econf::LoadEnv, PartialEq, Eq)]
    struct Config {
        simple_value: String,
        config: Option<InnerConfig>,
    }
    
    #[derive(Debug, Default, econf::LoadEnv, serde::Deserialize, PartialEq, Eq)]
    struct InnerConfig {
        inner_value: String,
    }
    
    fn main() {
        let config = Config::default();
    
        std::env::set_var("TEST_SIMPLE_VALUE", "test_value");
        std::env::set_var("TEST_CONFIG", r#"{inner_value: "test_value"}"#);
    
        let expected_config = Config {
            simple_value: "test_value".to_string(),
            config: Some(InnerConfig {
                inner_value: "test_value".to_string(),
            }),
        };
        let parsed_config = econf::load(config, "TEST");
    
        assert_eq!(expected_config, parsed_config);
    
        std::env::remove_var("TEST_SIMPLE_VALUE");
        std::env::remove_var("TEST_CONFIG");
    }
    

    Specifically for parsing of config: Option<InnerConfig>, while I understand why it works the way it does due to the documentation:

    Instead of this:

    std::env::set_var("TEST_CONFIG", r#"{inner_value: "test_value"}"#);
    

    I would love to be able to do this:

    std::env::set_var("TEST_CONFIG_INNER_VALUE", "test_value"});
    

    Is there a current way to do this? Also willing to contribute and add this functionality if you point me to the right places and think it's a doable feature.

    opened by clintjedwards 0
Releases(v0.2.1)
  • v0.2.1(Jul 14, 2022)

  • v0.2.0(Jun 17, 2022)

  • v0.1.4(Jun 15, 2022)

    πŸš€ Enhancements

    • Fix readme (#7) @YushiOMOTE
    • Implement skip helper attribute (#6) @julianskartor

    Thanks again to @YushiOMOTE and @julianskartor! πŸŽ‰

    Source code(tar.gz)
    Source code(zip)
  • v0.1.3(Jun 9, 2022)

    • Add release drafter (#3) @YushiOMOTE

    πŸš€ Enhancements

    • Add support for PathBuf (#2) @julianskartor

    Thanks again to @YushiOMOTE and @julianskartor! πŸŽ‰

    Source code(tar.gz)
    Source code(zip)
Owner
Yushi OMOTE
Rust, C/C++, Python, Kotlin/Java, React, x86
Yushi OMOTE
Containerize your development and continuous integration environments. πŸ₯‚

Toast ?? Toast is a tool for doing work in containers. You define tasks in a YAML file called a toastfile, and Toast runs them in a containerized envi

Stephan Boyer 1.4k Dec 27, 2022
🐳 πŸ“¦ Bringing docker containers to your AUR helper since 2022

zeus Releases | CI | Issues | Installing | Building Zeus. A simple AUR helper which utilizes docker containers allowing developers and users alike to

1337 16 Dec 17, 2022
Rust Macro which loads files into the rust binary at compile time during release and loads the file from the fs during dev.

Rust Embed Rust Custom Derive Macro which loads files into the rust binary at compile time during release and loads the file from the fs during dev. Y

Peter 1k Jan 5, 2023
Deserialize (potentially nested) environment variables into your custom structs

envious allows you to deserialize your serde enabled structs from environment variables. See it in action: use serde::{Deserialize, Serialize}; #[der

Marcel MΓΌller 46 Feb 19, 2023
vault client using jwt authentication that define environment variables from vault secrets before executing into something else

envlt envlt, like env, allows you to define environment variables and then execute into something else, but instead of static values, it uses using si

Eric Burghard 6 Nov 13, 2022
Experimental one-shot benchmarking/profiling harness for Rust

Iai Experimental One-shot Benchmark Framework in Rust Getting Started | User Guide | Released API Docs | Changelog Iai is an experimental benchmarking

Brook Heisler 409 Dec 25, 2022
Annotation to easily define ad-hoc / one-shot extension traits

Annotation to easily define ad-hoc / one-shot extension traits

Daniel Henry-Mantilla 2 Apr 19, 2022
Build a config structure from environment variables in Rust without boilerplate

Yasec Yet another stupid environment config (YASEC) creates settings from environment variables. (Envconig-rs fork) Features Nested configuration stru

null 4 Dec 28, 2021
A Rust-based Garry's Mod module for fetching environment variables.

gm_environ Using Environment Variables in Garry's Mod. Installation Download a copy of the module from the releases (or compile from source) Move the

Joshua Piper 2 Jan 4, 2022
Envful is a CLI tool that verifies the presence of environment variables

Envful is a CLI tool that verifies the presence of environment variables. It looks inside your .env file and the host system. You can use it to run any process while ensuring all the variables are set.

Alex Vilchis 65 Sep 8, 2022