os: remove some duplication in the env var check for xdg config

This commit is contained in:
Mitchell Hashimoto
2023-10-23 08:47:16 -07:00
parent b9b33ab25d
commit 3226cbf61b

View File

@ -20,35 +20,31 @@ pub const Options = struct {
/// Get the XDG user config directory. The returned value is allocated. /// Get the XDG user config directory. The returned value is allocated.
pub fn config(alloc: Allocator, opts: Options) ![]u8 { pub fn config(alloc: Allocator, opts: Options) ![]u8 {
if (builtin.os.tag == .windows) { // First check the env var. On Windows we have to allocate so this tracks
if (std.process.getEnvVarOwned(alloc, "XDG_CONFIG_HOME")) |env| { // both whether we have the env var and whether we own it.
// If we have a subdir, then we use the env as-is to avoid a copy. const env_, const owned = switch (builtin.os.tag) {
if (opts.subdir) |subdir| { else => .{ std.os.getenv("XDG_CONFIG_HOME"), false },
defer alloc.free(env); .windows => windows: {
return try std.fs.path.join(alloc, &[_][]const u8{ if (std.process.getEnvVarOwned(alloc, "XDG_CONFIG_HOME")) |env| {
env, break :windows .{ env, true };
subdir, } else |err| switch (err) {
}); error.EnvironmentVariableNotFound => break :windows .{ null, false },
else => return err,
} }
},
};
defer if (owned) if (env_) |v| alloc.free(v);
// We don't need to dupe since it's already allocated if (env_) |env| {
return env; // If we have a subdir, then we use the env as-is to avoid a copy.
} else |err| switch (err) { if (opts.subdir) |subdir| {
error.EnvironmentVariableNotFound => {}, return try std.fs.path.join(alloc, &[_][]const u8{
else => return err, env,
subdir,
});
} }
} else {
if (std.os.getenv("XDG_CONFIG_HOME")) |env| {
// If we have a subdir, then we use the env as-is to avoid a copy.
if (opts.subdir) |subdir| {
return try std.fs.path.join(alloc, &[_][]const u8{
env,
subdir,
});
}
return try alloc.dupe(u8, env); return try alloc.dupe(u8, env);
}
} }
// If we have a cached home dir, use that. // If we have a cached home dir, use that.