dotenv-rs / dotenv

Library to help supply environment variables in testing and development
MIT License
566 stars 45 forks source link

Overriding files #41

Open frederikhors opened 4 years ago

frederikhors commented 4 years ago

Coming from https://github.com/bkeepers/dotenv, is there a way to use these files too: https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use?

Hierarchy Priority Filename Environment Should I .gitignoreit? Notes
1st (highest) .env.development.local Development Yes! Local overrides of environment-specific settings.
1st .env.test.local Test Yes! Local overrides of environment-specific settings.
1st .env.production.local Production Yes! Local overrides of environment-specific settings.
2nd .env.local Wherever the file is Definitely. Local overrides. This file is loaded for all environments except test.
3rd .env.development Development No. Shared environment-specific settings
3rd .env.test Test No. Shared environment-specific settings
3rd .env.production Production No. Shared environment-specific settings
Last .env All Environments Depends (See below) The Original®
logankeenan commented 4 years ago

I've done this as a work around. This is only part of the table you've referenced.

fn load_environment_variables() {
    let environment = env::var("RUST_ENV").unwrap_or_else(|_| "".to_string());

    if environment == "development" {
        dotenv::from_filename(".env.development").ok();
    }
    if environment == "test" {
        dotenv::from_filename(".env.test").ok();
    }
    if environment == "production" {
        dotenv::from_filename(".env.production").ok();
    }
    dotenv::dotenv().ok();
}
MalpenZibo commented 4 years ago

I've done this in one of my projects. (Not tested)

#[derive(Deserialize, Debug, Clone)]
pub struct Config {
    auth_url: String,
    client_id: String,
    scope: String,
    redirect_uri: String,
}

fn load_config() -> Result<Config, envy::Error> {
    let profile = if cfg!(test) {
        "test"
    } else if cfg!(debug_assertions) {
        "development"
    } else {
        "production"
    };

    dotenv::from_filename(format!(".env.{}.local", profile)).ok();
    dotenv::from_filename(".env.local").ok();
    dotenv::from_filename(format!(".env.{}", profile)).ok();
    dotenv::dotenv().ok();

    envy::from_env::<Config>()
}

I've also used envy -> https://github.com/softprops/envy

pksunkara commented 4 years ago

I have my implementation here.

billy1624 commented 2 years ago

Nice workarounds! I was looking for this just now. But I wonder why this is not part of dotenv core features?