Jafagervik/zenvars
Parse .env files into Zig structs
A zero-dependency module for parsing .env files into zig structs in under 150 lines of Zig
Zenvars Version | Supported Zig Version |
---|---|
≤ 1.1 | 0.14.x |
≥ 1.2 | 0.15.x |
First to install, run:
zig fetch --save git+https://github.com/Jafagervik/zenvars#v1.2.0
Swap out version with any of the newer versions
Add the zenvars module to your build.zig
file this:
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const zenvars_dep = b.dependency("zenvars", .{});
const zenvars = zstb_dep.module("zenvars");
const exe_mod = b.createModule(.{
.root_source_file = b.path("path/to/your/main/source/file"),
.target = target,
.optimize = optimize,
});
exe_mod.addImport("zenvars", zenvars);
Given you have a .env
file somewhere like this
# COMMENT will not be parsed
name=Me
age=42#0
male=
pi=3.14
NOTE Keys can have empty values. in that case, the default value of the struct will be used
NOTE Comments starts with #, so everything to the rightside will be ignored
NOTE The keys are case insensitive, so you could have a key
NICK_NAME
in your env file This will then map to fieldnick_name
in your struct
Now, you can simply use it as is shown in the example below:
const std = @import("std");
const zenvars = @import("zenvars");
// Default values are necessary
pub const EnvVars = struct {
name: []const u8 = "none",
age: ?i32 = null,
male: bool = false,
pi: f32 = 3.0,
tell_me: bool = false,
};
pub fn main() !void {
// IMPORTANT: An arena allocator is needed for now
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const alloc = arena.allocator();
const envs = try zenvars.parse(alloc, EnvVars, .{.filepath="/path/to/your/.env"});
// Or you might want to let the program find it
_ = try zenvars.parse(alloc, EnvVars, .{});
// You can even show the path if you'd like
_ = try zenvars.parse(alloc, EnvVars, .{ .show_path = true });
std.debug.print("name={s} age={d} male={} pi={d} tell_me={}\n", .{ p.name, p.age, p.male, p.pi, p.tell_me });
}
parse(allocator: std.mem.Allocator, comptime T: type, opts: Options)
const Options = struct {
/// If set, this will try to open the file at that specific location, otherwise
filepath: ?[]const u8 = null,
/// If true, the full path to the `.env` file will be printed
show_path: bool = false,
};
NOTE
show_path
is best used whenfilepath
is not set