I was refactoring my project to use config/runtime.exs to make the config more streamlined and allow configuring (nearly) all things with environment variables. This is fine for production where I define the variables in the Systemd unit file, but in development I don’t want to waste time having to set all of them or remembering to source them from somewhere.
So I decided to write a simple .env file parsing library so I can do this on top of my config file:
if Config.config_env() == :dev do
DotenvParser.load_file(".env")
end
Now for developers, all the vars are nicely grabbed from the .env and they can be used in the runtime config (or inside the application code) with System.get_env/2. When execution ends, they are no longer set, so they don’t pollute your shell environment.
The library supports both uppercase and lowercase variable names, quoted values to prevent trimming of whitespace, comment lines and inline comments, double quoted values to unescape some escape codes like \n or \uXXXX, and lines that start with export (in case you want shell compatibility – but note that the escapes may be different).
Some prior art, some of them I looked through and some I didn’t know of before this moment:
dotenv – I figured it was abandoned but in fact at pretty much the same time as I made my own, it has reactivated and pushed a new version. Has a server mode with a reload function to reload values when they have been changed. Supports referring to previous variables in subsequent ones, which mine doesn’t. Doesn’t seem to have any unescape support?
envy – Puts values directly to system env (no possibility to return them). Doesn’t do unescaping. Has a Mix-based config reload system.