不小心写了一个 Zig .env 解析器
Accidentally Made a Zig Dotenv Parser

原始链接: https://dayvster.com/blog/accidentally-made-a-zig-dotenv-parser/

在开发 Zig 的命令行参数解析器(“argh”)时,作者开始实现对环境变量的支持。这促使他构建了一个完整的 `.env` 文件解析器,能够从类似 `.env` 的文件中读取键值对。意识到其更广泛的实用性,他将此功能提取到一个独立的库中,名为 “zdotenv”。 Zdotenv 是一个简单、内存安全的库,用于解析 `.env` 文件。它将变量加载到哈希映射中,以便通过 `get` 方法快速访问,并处理键缺失的情况。它支持多个文件路径、注释、空行和双引号值,涵盖了常见的 `.env` 文件使用场景。 该库包含一个 `deinit` 方法以防止内存泄漏。它已经在作者的其他项目中被使用,并且可在公共仓库中找到,欢迎贡献和反馈。

Hacker News 新闻 | 过去 | 评论 | 提问 | 展示 | 招聘 | 提交 登录 意外制作了一个 Zig Dotenv 解析器 (dayvster.com) 21 分,ibobev 发表于 3 小时前 | 隐藏 | 过去 | 收藏 | 2 条评论 peterldowns 发表于 47 分钟前 [还有 2 条] 为什么你的博客文章里有这么多广告?回复 tomhow 发表于 30 分钟前 | 父评论 [–] 请不要抱怨与主题无关的烦恼——例如文章或网站格式、名称冲突或后退按钮失效。这些问题太常见了,没有讨论价值。https://news.ycombinator.com/newsguidelines.html 回复 考虑申请 YC 2026 冬季批次!申请截止日期为 11 月 10 日 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系方式 搜索:
相关文章

原文

How I ended up creating a dotenv parser while working on a CLI argument parser


Recently I’ve made a Zig based CLI argument parser called argh I’ve even written myself a roadmap I’d like to follow with this project. And so far I have been following it pretty well. However last week I began working on the next item on my roadmap which was to add support for environment variables to the arg parser, where you could set an environment variable to set the value of a flag.

Not many use cases for it I know it’s more of an edge case but I thought it would be a fun exercise to implement that. So I started working on it. I carefully scaffolded out the feature what functions I’d like to see in it how they should behave what guard rails I’d like to set to ensure type safety, memory safety, and so on.

As I was implementing all the things I scaffolded out one by one I realized that I was basically writing a fully fledged dotenv parser. And I thought to myself “hey this is pretty cool I should probably make this a separate library so other people can use it too” and it’s not deeply coupled to the arg parser so it makes sense to do that. So I did. I extracted the code out into its own repository called zdotenv.

The Library

The dotenv parser itself is pretty simple to use and I’ve even provided a basic example and tests in my repository that you can check out to see how it works. But regardless here’s a quick example of how to use it:

const std = @import("std");
const Dotenv = @import("dotenv").Dotenv;

pub fn main() !void {
    const allocator = std.heap.page_allocator;
    var dotenv = Dotenv.init(allocator);
    defer dotenv.deinit();
    try dotenv.load(&[_][]const u8{"./examples/example.env"});
    if (dotenv.get("FOO")) |val| {
        std.debug.print("FOO={s}\n", .{val});
    } else {
        std.debug.print("FOO not found\n", .{});
    }
}

This will load the environment variables from the specified file and you can then access them using the get method. The load method takes an array of file paths so you can load multiple dotenv files if you want to.

That’s it, that’s all there is to it. It’s simple and straightforward as a dotenv parser should ideally be.

I’ve also added support for specifying custom .env file names since not everyone uses the default .env file all the time, you may wanna dynamically load different env files based on the environment you’re in (development, staging, production, etc).

I’ve added support for comments, blank lines and values in double quotes. So it should cover most use cases out there.

Features

  • Loads key-value pairs from .env basically the core feature it does that it says, it parses an .env file and loads the key-value pairs into memory so that you can access them later via the get method.

  • Supports comments and blank lines it ignores comments and blank lines so you can have a well formatted .env file without any issues.

  • Provides easy access to values via hash map you can access the values using the get method which returns an optional value so you can handle the case where the key doesn’t exist. I picked a hash map for this since generally speaking your .env files won’t ever be that large so we can just store them in memory for easy and fast access.

  • Memory safe all allocations are freed with a deinit method so you don’t have to worry about memory leaks.

Conclusion

Well that’s it for now. I’ll be adding additional functionality and patches to the library as I see fit. But for now it’s a pretty solid and usable dotenv parser that you can use in your Zig projects. I for one have already used it in my notes CLI application I made a while back to compare Zig against Rust and it works like a charm.

As always I welcome contributions and feedback so if you have any ideas or suggestions feel free to open an issue or a pull request on the repository.

And if you have any questions or would like to reach out to me you can find me on Twitter

If you find my sporadic thoughts and ramblings helpful.
You can buy me a coffee if you feel like it.

It's not necessary but it's always appreciated. The content will always stay free regardless.

联系我们 contact @ memedata.com