DotenvParser - A simple library to parse .env files

Nicd
Fri, 22 Jan 2021 06:32:13 +0000
Libraries

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).

Link to library: https://hex.pm/packages/dotenv_parser

License: MIT (+ BSD 3 clause for one test file)

4 posts - 1 participant