Skip to content

Commit

Permalink
add XDG base directory spec support
Browse files Browse the repository at this point in the history
  • Loading branch information
dweiller committed Jul 19, 2024
1 parent 9f04168 commit e4b5171
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
7 changes: 7 additions & 0 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,15 @@ pub fn build(b: *std.Build) !void {
"Default compiler installation directory (default: zig)",
) orelse "zig";

const use_xdg = b.option(
bool,
"use-xdg",
"Use the XDG base directory specification (default: false)",
) orelse false;

const build_options = b.addOptions();
build_options.addOption([]const u8, "default_dir", default_dir);
build_options.addOption(bool, "use_xdg", use_xdg);

const zigup_exe_native = blk: {
const exe = addZigupExe(b, target, optimize, build_options);
Expand Down
34 changes: 28 additions & 6 deletions zigup.zig
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,15 @@ fn ignoreHttpCallback(request: []const u8) void {
}

fn getHomeDir() ![]const u8 {
return std.posix.getenv("HOME") orelse {
const home = std.posix.getenv("HOME") orelse {
std.log.err("cannot find install directory, $HOME environment variable is not set", .{});
return error.MissingHomeEnvironmentVariable;
};
if (!std.fs.path.isAbsolute(home)) {
std.log.err("$HOME environment variable '{s}' is not an absolute path", .{home});
return error.AlreadyReported;
}
return home;
}

fn allocInstallDirString(allocator: Allocator) ![]const u8 {
Expand All @@ -135,12 +140,29 @@ fn allocInstallDirString(allocator: Allocator) ![]const u8 {
defer allocator.free(self_exe_dir);
return std.fs.path.join(allocator, &.{ self_exe_dir, build_options.default_dir });
}
const home = try getHomeDir();
if (!std.fs.path.isAbsolute(home)) {
std.log.err("$HOME environment variable '{s}' is not an absolute path", .{home});
return error.BadHomeEnvironmentVariable;

if (build_options.use_xdg) {
if (std.posix.getenv("XDG_DATA_HOME")) |xdg_data_home| {
if (xdg_data_home.len > 0) {
if (!std.fs.path.isAbsolute(xdg_data_home)) {
std.log.err(
"$XDG_DATA_HOME environment variable '{s}' is not an absolute path",
.{xdg_data_home},
);
return error.AlreadyReported;
}
return std.fs.path.join(allocator, &.{ xdg_data_home, "zigup" });
}
}
const sep = .{std.fs.path.sep};
return std.fs.path.join(allocator, &.{
try getHomeDir(), ".local" ++ sep ++ "share" ++ sep ++ "zigup",
});
}
return std.fs.path.join(allocator, &[_][]const u8{ home, build_options.default_dir });

return std.fs.path.join(allocator, &[_][]const u8{
try getHomeDir(), build_options.default_dir,
});
}
const GetInstallDirOptions = struct {
create: bool,
Expand Down

0 comments on commit e4b5171

Please sign in to comment.