xcaeser/zig-dotenv
โก๏ธA powerful Zig library for loading, parsing, and managing environment variables from .env files
.env
fileskey=value
pairs to .env
filessetenv
, SetEnvironmentVariable
)const std = @import("std");
const dotenv = @import("dotenv");
pub const EnvKeys = enum {
OPENAI_API_KEY,
AWS_ACCESS_KEY_ID,
COGNITO_CLIENT_SECRET,
S3_BUCKET,
};
pub fn main() !void {
const allocator = std.heap.smp_allocator;
const env = dotenv.Env(EnvKeys).init(allocator, true);;
defer env.deinit();
try env.load(.{ .filename = ".env.local", .set_envs_in_process = true });
const openai = env.key(.OPENAI_API_KEY);
std.debug.print("OPENAI_API_KEY={s}\n", .{openai});
const aws_key = env.get("AWS_ACCESS_KEY_ID");
std.debug.print("AWS_ACCESS_KEY_ID={s}\n", .{aws_key});
}
.env
FileOPENAI_API_KEY=sk-your-api-key-here
AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
S3_BUCKET="my-bucket"
COGNITO_CLIENT_SECRET='abcdef123456'
home=$HOME
user=${USER}
zig fetch
zig fetch --save=dotenv https://github.com/xcaeser/zig-dotenv/archive/v0.8.0.tar.gz
build.zig
const dotenv_dep = b.dependency("dotenv", .{ .target = target, .optimize = optimize });
exe.root_module.addImport("dotenv", dotenv_dep.module("dotenv"));
// Optional: add for unit tests
exe_unit_tests.root_module.addImport("dotenv", dotenv_dep.module("dotenv"));
Env(EnvKey)
typeA reusable struct for managing environment variables:
Method | Description |
---|---|
init(allocator, include_current_process_envs) |
Initializes a new Env manager |
deinit() |
Frees all allocated memory |
load(.{ filename, set_envs_inprocess, silent }) |
Loads variables from a .env file |
loadCurrentProcessEnvs() |
Loads system variables into the internal env_map |
parse(content) |
Parses raw .env -formatted text |
get("KEY") |
Get a value by string key (panics if missing) |
key(.ENUM_KEY) |
Get a value by enum key (panics if missing) |
setProcessEnv("KEY", "VALUE") |
Set or unset environment variable |
writeAllEnvPairs(writer, include_system_vars) |
Write all variables to a writer |
writeEnvPairToFile("KEY", "VALUE", optional_filename) |
Append a key=value line to a file |
Run:
zig build test
Includes tests for parsing, file I/O, process environment setting, and edge cases.
Issues and PRs welcome! Star the repo if it helped you.
MIT โ see LICENSE.