Skip to content

Commit 54c2645

Browse files
committed
allow for comments in the env file, and fix the readme
1 parent 8cfcc1d commit 54c2645

File tree

4 files changed

+30
-3
lines changed

4 files changed

+30
-3
lines changed

.env

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# A comment here
2+
3+
VALUE1=1
4+
VALUE2=2
5+
VALUE3=3
6+
7+
# some blank lines
8+
9+
10+
11+
# VALUE4=4

.gitignore

-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
11
zig-out/
22
.zig-cache/
3-
.env

README.md

+14-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,18 @@ Load ENV vars from .env files on boot
33

44
--
55

6+
On boot, calling `env.init(alloc, ".env")` will return an env that
7+
includes values from the `.env` file
8+
9+
Lines starting with `#` are treated as comments
10+
11+
All other lines will take the form
12+
13+
```
14+
ENV_VAR_NAME=VALUE
15+
```
16+
17+
Lines that do not have a `=` sign will be skipped
618

719
## Install
820

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

1527
```zig
16-
const zts = b.dependency("dotenv", .{ dependency options here );
28+
const dotenv = b.dependency("dotenv", .{ dependency options here );
1729
exe.root_module.addImport("dotenv", dotenv.module("dotenv"));
1830
```
1931

@@ -39,7 +51,7 @@ pub fn main() !void {
3951
defer gpa.deinit();
4052
4153
// init the dotenv object - this will read the .env file at runtime
42-
const env = try dotenv.init(allocator, ".env");
54+
var env = try dotenv.init(allocator, ".env");
4355
defer env.deinit();
4456
4557
// gen "Env" vars

src/dotenv.zig

+5
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ pub fn init(allocator: Allocator, filename: ?[]const u8) !Self {
1919
var in_stream = buf_reader.reader();
2020
var buf: [1024]u8 = undefined;
2121
while (try in_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| {
22+
// ignore commented out lines
23+
if (line.len > 0 and line[0] == '#') {
24+
continue;
25+
}
2226
// split into KEY and Value
2327
if (std.mem.indexOf(u8, line, "=")) |index| {
2428
const key = line[0..index];
@@ -57,4 +61,5 @@ test "load an env file" {
5761
try testing.expectEqualStrings("1", expanded_env.get("VALUE1").?);
5862
try testing.expectEqualStrings("2", expanded_env.get("VALUE2").?);
5963
try testing.expectEqualStrings("3", expanded_env.get("VALUE3").?);
64+
try testing.expectEqual(null, expanded_env.get("VALUE4"));
6065
}

0 commit comments

Comments
 (0)