Expand description
Sets values loaded by adotenv in the current process environment.
adotenv::load reads .env files into a LoadedEnvironment but never
changes the process environment. This crate adds that step: apply. It is
a separate crate because changing the environment is unsafe. The
environment is shared by every thread of the process, and on some platforms
reading it while another thread writes it is undefined behavior. The core
adotenv crate forbids unsafe code.
[dependencies]
adotenv = { version = "1", features = ["load"] }
adotenv-process = "1"The crate has no features of its own and supports Rust 1.81.
§Prefer passing values explicitly
Most programs do not need to change their own environment. Read values
with LoadedEnvironment::get, deserialize them with the serde feature
of adotenv, or pass them to a child process:
use std::process::Command;
use adotenv::load::load_cascade;
let loaded = load_cascade("/srv/my-app", "production")?;
let status = Command::new("my-server").envs(loaded.values()).status()?;Use apply only when code you do not control reads the process
environment, such as a library that calls std::env::var.
§Applying a loaded environment
apply checks every key and value, then sets each loaded key. A loaded
key replaces a variable of the same name. Other variables are kept and
nothing is removed. Values are set as loaded: ${HOME} is not expanded.
The changes cannot be rolled back.
The caller must guarantee that no other thread reads or writes the process
environment while apply runs. In practice, call it at the start of
main, before starting threads or an async runtime.
use adotenv::load::load_cascade;
let loaded = load_cascade(&dir, "production")?;
// SAFETY: called at startup, before any other thread exists.
unsafe { adotenv_process::apply(&loaded)? };
assert_eq!(std::env::var("APP_PORT")?, "8080");validate runs the same checks without changing anything, and is safe
to call from any thread. Both return an ApplyError for the first key or
value that the process environment cannot hold.
apply takes a LoadedEnvironment. To set resolved values, resolve them
with LoadedEnvironment::resolve_contextual and set them yourself.
Enums§
- Apply
Error - A key or value that the process environment cannot hold.