Skip to content

Jafagervik/zenvars

Repository files navigation

Zenvars - Parse .env files into Zig structs

A zero-dependency module for parsing .env files into zig structs in under 150 lines of Zig

CI License: Zlib

Zig Compatibility

Zenvars Version Supported Zig Version
≤ 1.1 0.14.x
≥ 1.2 0.15.x

Install

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);

Usage

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 field nick_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 });
}

Functions and Types

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 when filepath is not set

Supported types

  • Floats (all kinds)
  • Integers (all kinds)
  • Strings ([]const u8 for now)
  • Bools
  • Enums
  • Optional values

About

Parse .env files into Zig structs

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •  

Languages