potenv

Crates.iopotenv
lib.rspotenv
version0.2.0
sourcesrc
created_at2023-03-21 22:29:41.141386
updated_at2024-01-15 17:18:00.156957
descriptionRust implementation of the POSIX-compliant dotenv file format specification.
homepage
repositoryhttps://github.com/ju1ius/potenv
max_upload_size
id816566
size41,326
(ju1ius)

documentation

README

potenv

Crates.io Docs.rs Codecov

A Rust implementation of the POSIX-compliant dotenv file format specification.

Usage

Load environment variables from a .env file in the current working directory:

potenv::load([".env"]).expect("Failed to load .env file.");

For convenience, an iterator over the loaded variables is returned:

let vars = potenv::load([".env"]).unwrap();
for (name, value) in vars {
  assert_eq!(value, std::env::var(name).unwrap());
}

If you just want to evaluate the dotenv files without loading them into the environment, use the following:

use potenv::Potenv;

let vars = Potenv::default()
  .evaluate([".env"])
  .unwrap();

By default, environment variables take precedence over variables defined in a dotenv file.

When this is not the desired behaviour, you can use the following:

use potenv::Potenv;

let vars = Potenv::default()
  .override_env(true)
  .load([".env"])
  .unwrap();

If you don't want to read from and/or write to the process environment, you can implement the [env::EnvProvider] trait.

For example, this is how to frobnicate all variables:

use potenv::{Potenv, env::EnvProvider};

pub struct Frobnicator;

impl EnvProvider for Frobnicator {
  fn var(&self, name: &str) -> Option<String> {
    Some("frobnicated".into())
  }
  fn set_var(&mut self, name: &str, value: &str) {}
}

let vars = Potenv::new(Frobnicator, false)
  .evaluate([".env"])
  .unwrap();
for (name, value) in vars {
  assert_eq!("frobnicated", value);
}

If you just want to mock the environment in unit-tests, the [env::EnvProvider] trait is implemented for HashMap<String, String>:

use std::collections::HashMap;
use potenv::Potenv;

let mut mock = HashMap::new();
mock.insert("name".into(), "value".into());

let vars = Potenv::new(mock, false)
  .evaluate([".env"])
  .unwrap();
Commit count: 43

cargo fmt