std/env

The environment as settings: .env files, and variables read as text, numbers, flags, and lists, with defaults and required ones, so that every missing or wrong variable is reported at once.

import "std/env"

load_env_file(".env")?
EnvReader r = env_reader()
str host = r.require_str("DATABASE_HOST")
int port = r.get_int("DATABASE_PORT", 5432)
bool debug = r.get_bool("DEBUG", false)
r.check()?      // DATABASE_HOST is missing; DEBUG is not true or false ('maybe')
Function or method Result
parse_env(text) the variables of .env text, in order, as a map[str, str]
load_env_file(path), load_env_file(path, override: true) sets the variables of a .env file, leaving those set already unless override, and gives how many it set
env_reader() an EnvReader, whose methods read variables and keep the problems
get_str(name, fallback), require_str(name) the text of a variable; a required one must be set and not empty
get_int(name, fallback), require_int(name) a whole number
get_float(name, fallback) a number
get_bool(name, fallback) true, yes, on, or 1, or false, no, off, or 0, in any case
get_list(name, separator) the trimmed items between separators, empty ones left out
check() an ERROR of kind "invalid_environment" that lists every missing variable and every one not as wanted

A .env file has lines NAME=value, with export before them allowed and # comments. A value in single quotes is as it is; one in double quotes takes \n, \t, \", and \\, and may go on over several lines; and ${NAME} or $NAME in a value outside single quotes is the value of a variable before it or of the environment.