A simple, zero-dependency dotenv implementation for Rust.
This library exposes two similar functions. The first is loadenv::load()
, which looks for a file named .env
in the current directory and loads its contents into the environment. The second is loadenv::load_buf()
, which takes a BufRead and loads its contents into the environment. This function can be used to load .env files from custom locations or from other data structures like &[u8]
.
Most of the time, load()
should be enough for your program.
The existing environment is treated as truth; variables that are already set will not be overwritten unless the $
prefix is used (see the example below). Generally, you should avoid using the $
prefix and allow the developer (or the operating system itself) to overwrite the values in .env
.
```conf
#
and must be on their own lineKEY = value
USERNAME = ben PASSWORD = k4y5FzSa9x%LA&Zy
=
is optional for empty valuesDEBUG
=
is optionalFOO=bar BOP = baz
==
is preservedFORMAT == A B C D
$PATH = /bin:/sbin:/usr/bin ```
A .env
file consists of zero or more key-value pairs in the form KEY = value
or KEY == value
. Pairs in the form KEY = value
are parsed as you might expect: whitespace before and after the =
is ignored (including whitespace at the beginning and end of the line). Pairs in the form KEY == value
denote "raw" values. In this case, every character after the ==
is kept, including whitespace.
In addition, the following rules apply to all lines:
- Empty lines are ignored.
- Lines that begin with #
are comments and are ignored. Note that comments must be on their own line.
- Whitespace before the KEY
is always ignored.
- KEY
may only contain 0-9
, A-Z
and _
.
- KEY
may be prefixed with a $
.
- value
may contain any character.
A more detailed example can be found in .env
in the root of this project.
Load the example .env file and print out the new environment. ```rust fn main() { loadenv::load().ok();
for (k, v) in std::env::vars() {
println!("{} = '{}'", k, v);
}
} ```
Load a .env from a &str. ```rust fn main() { let dotenv = "FOO=bar\nWEBSITE=https://gitlab.com\nDEBUG"; loadenv::loadbuf(dotenv.asbytes()).ok();
for (k, v) in std::env::vars() {
println!("{} = '{}'", k, v);
}
} ```
Tests must be run in single-threaded mode using cargo test -- --test-threads=1
. Otherwise, testing will be unreliable because many std::env
methods are not thread-safe. See this page for more info.