Zig 0.16: env vars

This commit is contained in:
LN Liberda 2026-05-22 21:14:16 +02:00
parent 608befe26c
commit 5659a7980f
2 changed files with 8 additions and 6 deletions

View file

@ -62,6 +62,7 @@ pub const allocator = std.mem.Allocator{
};
pub var io: std.Io = undefined;
pub var environ_map: *std.process.Environ.Map = undefined;
// Custom panic impl to reset the terminal before spewing out an error message.
@ -284,11 +285,11 @@ fn argConfig(args: *Args, opt: Args.Option, infile: bool) !void {
else if (opt.is("-L") or opt.is("--follow-symlinks")) config.follow_symlinks = true
else if (opt.is("--no-follow-symlinks")) config.follow_symlinks = false
else if (opt.is("--exclude")) {
const arg = if (infile) (util.expanduser(try args.arg(), allocator) catch unreachable) else try args.arg();
const arg = if (infile) (util.expanduser(try args.arg(), allocator, environ_map) catch unreachable) else try args.arg();
defer if (infile) allocator.free(arg);
exclude.addPattern(arg);
} else if (opt.is("-X") or opt.is("--exclude-from")) {
const arg = if (infile) (util.expanduser(try args.arg(), allocator) catch unreachable) else try args.arg();
const arg = if (infile) (util.expanduser(try args.arg(), allocator, environ_map) catch unreachable) else try args.arg();
defer if (infile) allocator.free(arg);
readExcludeFile(arg) catch |e| try args.die("Error reading excludes from {s}: {s}.\n", .{ arg, ui.errorString(e) });
} else if (opt.is("--exclude-caches")) config.exclude_caches = true
@ -468,6 +469,7 @@ fn readImport(path: [:0]const u8) !void {
pub fn main(init: std.process.Init) void {
io = init.io;
ui.main_thread = std.Thread.getCurrentId();
environ_map = init.environ_map;
// Grab thousands_sep from the current C locale.
_ = c.setlocale(c.LC_ALL, "");
@ -490,11 +492,11 @@ pub fn main(init: std.process.Init) void {
if (loadConf) {
tryReadArgsFile("/etc/ncdu.conf");
if (std.posix.getenvZ("XDG_CONFIG_HOME")) |p| {
if (init.environ_map.get("XDG_CONFIG_HOME")) |p| {
const path = std.fs.path.joinZ(allocator, &.{p, "ncdu", "config"}) catch unreachable;
defer allocator.free(path);
tryReadArgsFile(path);
} else if (std.posix.getenvZ("HOME")) |p| {
} else if (init.environ_map.get("HOME")) |p| {
const path = std.fs.path.joinZ(allocator, &.{p, ".config", "ncdu", "config"}) catch unreachable;
defer allocator.free(path);
tryReadArgsFile(path);

View file

@ -173,14 +173,14 @@ test "strnatcmp" {
}
pub fn expanduser(path: []const u8, alloc: std.mem.Allocator) ![:0]u8 {
pub fn expanduser(path: []const u8, alloc: std.mem.Allocator, environ_map: *std.process.Environ.Map) ![:0]u8 {
if (path.len == 0 or path[0] != '~') return alloc.dupeZ(u8, path);
const len = std.mem.indexOfScalar(u8, path, '/') orelse path.len;
const home_raw = blk: {
const pwd = pwd: {
if (len == 1) {
if (std.posix.getenvZ("HOME")) |p| break :blk p;
if (environ_map.get("HOME")) |p| break :blk p;
break :pwd c.getpwuid(c.getuid());
} else {
const name = try alloc.dupeZ(u8, path[1..len]);