A tiny, libc-free Zig library and CLI tool for parsing .env files. Use it as an
in-memory config store or to export variables into your shell.
Note: zenver does not mutate the process environment.
loadFilefills an in-memory store you query withgetSingleVariable; the CLI's-eflag prints shellexportlines so your shell can set them.getenvand child processes will not see loaded variables unless youeval/sourcethe CLI output.
Build the binary:
zig buildExport variables into your current shell:
eval $(./zig-out/bin/zenver -e .env)
# or
source <(./zig-out/bin/zenver -e .env)Add zenver as a dependency:
zig fetch --save https://github.com/Blize/zenver/archive/refs/heads/main.tar.gzWire it up in your build.zig:
const zenver_dep = b.dependency("zenver", .{});
exe.root_module.addImport("zenver", zenver_dep.module("zenver"));Then use it in your code:
const std = @import("std");
const Zenver = @import("zenver").Zenver;
pub fn main(init: std.process.Init) !void {
const io = init.io;
// Zenver manages its own arena internally; pass any allocator.
var zenv = Zenver.init(std.heap.page_allocator, io, ".env");
defer zenv.deinit();
// Parse all variables from the file passed on init (or pass a path here).
try zenv.loadFile(null);
// try zenv.loadFile(".env.testing");
// Or add a single variable.
try zenv.loadSingleVariable(.{ .key = "PORT", .value = "3000" });
// Look a variable up (returns ?EnvPair).
if (zenv.getSingleVariable("PORT")) |port| {
std.log.info("PORT={s}", .{port.value});
}
std.log.info("loaded {d} variables", .{zenv.getLengthOfEnvList()});
}Parsed keys and values are owned by the Zenver instance and stay valid until
deinit() is called.
| Function | Description |
|---|---|
init(allocator, io, path) |
Create a Zenver instance (owns an internal arena) with an optional default file path |
deinit() |
Free all memory held by the instance |
loadFile(path) |
Parse a .env file into the in-memory store (skips blank and # lines) |
loadSingleVariable(pair) |
Add a single key=value pair to the store |
getSingleVariable(key) |
Look up a variable, returns ?EnvPair |
getLengthOfEnvList() |
Number of variables currently stored |
exportFile(path) |
Print export KEY=VALUE (or set on Windows) lines to stdout for shell eval/source |
# Comments and blank lines are ignored
DB_HOST=localhost
DB_PORT=5432
SECRET_KEY=mysecretkey
- Zig 0.16.0
This is a list of optional todo's which would be nice but for my small use cases have not yet affected me
- Optionally apply variables to the real process environment (so
getenvand child processes see them) via platform APIs /setenv. - Trim surrounding whitespace and strip surrounding quotes (
KEY="value",KEY='value'). - Last-wins override for duplicate keys, with
O(1)lookup via a hash map.
License MIT