Skip to content

Blize/zenver

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

zenver

A tiny Zig library and CLI tool for loading .env files into environment variables.

CLI Usage

Build the binary:

zig build

Export variables into your current shell:

eval $(./zig-out/bin/zenver -e .env)
# or
source <(./zig-out/bin/zenver -e .env)

Library Usage

Add zenver as a dependency:

zig fetch --save https://github.com/Blize/zenver/archive/refs/heads/main.tar.gz

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

    var arena_allocator: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
    defer arena_allocator.deinit();
    const arena = arena_allocator.allocator();

    // Load all variables from a file
    var zenv = Zenver.init(arena, io, ".env");
    try zenv.loadFile(null);

    // If you don't provide a path on init you can provide one directly
    // or just overwrite the one you passed on init
    // try zenv.loadFile(".env.testing");

    // Or load a single variable
    try zenv.loadSingleVariable(.{ .name = "PORT", .value = "3000" });

    std.log.info("contains PORT: {any}", .{init.minimal.environ.contains(arena, "PORT")});
    std.log.info("contains PORT (unempty): {any}", .{init.minimal.environ.containsUnempty(arena, "PORT")});

    std.log.info("PORT: {?s}", .{init.minimal.environ.getPosix("PORT")});

    const environ_map = try init.minimal.environ.createMap(arena);

    for (environ_map.keys(), environ_map.values()) |key, value| {
        std.log.info("env: {s}={s}", .{ key, value });
    }
}

API

Function Description
init(allocator, path) Create a Zenver instance with an optional default file path
loadFile(path) Parse a .env file and set variables via setenv
loadSingleVariable(pair) Set a single name=value pair in the environment
exportFile(path) Print export KEY=VALUE lines to stdout

.env Format

DB_HOST=localhost
DB_PORT=5432
SECRET_KEY=mysecretkey

Requirements

  • Zig 0.16.0
  • Links libc (for setenv)

License

License AGPL v3.0

About

simple env library in zig

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages