Skip to content

Commit

Permalink
allow for comments in the env file, and fix the readme
Browse files Browse the repository at this point in the history
  • Loading branch information
zigster64 committed Sep 27, 2024
1 parent 8cfcc1d commit 54c2645
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 3 deletions.
11 changes: 11 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# A comment here

VALUE1=1
VALUE2=2
VALUE3=3

# some blank lines



# VALUE4=4
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
zig-out/
.zig-cache/
.env
16 changes: 14 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,18 @@ Load ENV vars from .env files on boot

--

On boot, calling `env.init(alloc, ".env")` will return an env that
includes values from the `.env` file

Lines starting with `#` are treated as comments

All other lines will take the form

```
ENV_VAR_NAME=VALUE
```

Lines that do not have a `=` sign will be skipped

## Install

Expand All @@ -13,7 +25,7 @@ zig fetch --save git+https://github.com/zigster64/dotenv.zig#main
Then add to your build.zig

```zig
const zts = b.dependency("dotenv", .{ dependency options here );
const dotenv = b.dependency("dotenv", .{ dependency options here );
exe.root_module.addImport("dotenv", dotenv.module("dotenv"));
```

Expand All @@ -39,7 +51,7 @@ pub fn main() !void {
defer gpa.deinit();
// init the dotenv object - this will read the .env file at runtime
const env = try dotenv.init(allocator, ".env");
var env = try dotenv.init(allocator, ".env");
defer env.deinit();
// gen "Env" vars
Expand Down
5 changes: 5 additions & 0 deletions src/dotenv.zig
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ pub fn init(allocator: Allocator, filename: ?[]const u8) !Self {
var in_stream = buf_reader.reader();
var buf: [1024]u8 = undefined;
while (try in_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| {
// ignore commented out lines
if (line.len > 0 and line[0] == '#') {
continue;
}
// split into KEY and Value
if (std.mem.indexOf(u8, line, "=")) |index| {
const key = line[0..index];
Expand Down Expand Up @@ -57,4 +61,5 @@ test "load an env file" {
try testing.expectEqualStrings("1", expanded_env.get("VALUE1").?);
try testing.expectEqualStrings("2", expanded_env.get("VALUE2").?);
try testing.expectEqualStrings("3", expanded_env.get("VALUE3").?);
try testing.expectEqual(null, expanded_env.get("VALUE4"));
}

0 comments on commit 54c2645

Please sign in to comment.