Skip to content

Instantly share code, notes, and snippets.

@iacore
Created July 28, 2023 19:44
Show Gist options
  • Save iacore/393ace2b2843bc7952db5c5db50a087d to your computer and use it in GitHub Desktop.
Save iacore/393ace2b2843bc7952db5c5db50a087d to your computer and use it in GitHub Desktop.
Zig dotenv
pub const EnvMap = struct {
arena: std.heap.ArenaAllocator,
pairs: std.ArrayList(Pair),
pub const Pair = struct {
k: []const u8,
v: []const u8,
};
pub fn init_from_dotenv(allocator: std.mem.Allocator) !@This() {
var arena = std.heap.ArenaAllocator.init(allocator);
const _alloc = arena.allocator();
var pairs = std.ArrayList(Pair).init(_alloc);
// std.fs.cwd().openFile(".env", .{});
const f = try std.fs.cwd().openFile("../.env", .{});
var buf = [1]u8{0} ** 1024;
while (true) {
const a = try f.reader().readUntilDelimiterOrEof(&buf, '\n') orelse break;
const i = std.mem.indexOfScalar(u8, a, '=') orelse return error.DotenvNotEqualSign;
const pair = try pairs.addOne();
pair.k = try _alloc.dupe(u8, a[0..i]);
pair.v = try _alloc.dupe(u8, a[i + 1 ..]);
}
return .{
.arena = arena,
.pairs = pairs,
};
}
pub fn deinit(this: @This()) void {
this.arena.deinit();
}
pub fn get(this: @This(), key: []const u8) ?[]const u8 {
for (this.pairs.items) |pair| {
if (std.mem.eql(u8, key, pair.k)) return pair.v;
}
return std.os.getenv(key);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment