diff --git a/src/config/Config.zig b/src/config/Config.zig index 6ef84cae7..5a9fdcc3f 100644 --- a/src/config/Config.zig +++ b/src/config/Config.zig @@ -4364,33 +4364,24 @@ pub const RepeatablePath = struct { // Check if the path starts with a tilde and expand it to the home directory on linux/mac if (std.mem.startsWith(u8, path, "~/")) { - const home_var = try internal_os.home(&buf); // cache this? - if (home_var) |home_dir| { - const rest = path[1..]; // Skip the ~ - const expanded_len = home_dir.len + rest.len; - if (expanded_len > buf.len) { - try diags.append(alloc, .{ - .message = try std.fmt.allocPrintZ( - alloc, - "error resolving file path {s}: path too long after expanding home directory", - .{path}, - ), - }); - self.value.items[i] = .{ .required = "" }; - continue; - } - - @memcpy(buf[home_dir.len..expanded_len], rest); - + if (try internal_os.expandHome(path, &buf)) |expanded_path| { log.debug( "expanding file path from home directory: path={s}", - .{buf[0..expanded_len]}, + .{expanded_path}, ); - switch (self.value.items[i]) { - .optional, .required => |*p| p.* = try alloc.dupeZ(u8, buf[0..expanded_len]), + .optional, .required => |*p| p.* = try alloc.dupeZ(u8, expanded_path), } - + continue; + } else { + try diags.append(alloc, .{ + .message = try std.fmt.allocPrintZ( + alloc, + "error expanding home path {s}", + .{path}, + ), + }); + self.value.items[i] = .{ .required = "" }; continue; } } diff --git a/src/os/homedir.zig b/src/os/homedir.zig index cf6931f22..b03e7f354 100644 --- a/src/os/homedir.zig +++ b/src/os/homedir.zig @@ -110,6 +110,22 @@ fn trimSpace(input: []const u8) []const u8 { return std.mem.trim(u8, input, " \n\t"); } +/// Expands a path that starts with a tilde (~) to the home directory of the user. +/// +/// Errors if `home` fails or if the size of the expanded path is larger than `buf.len`. +/// +/// Returns null if the value returned from `home` is null, otherwise returns a slice to the expanded path. +pub fn expandHome(path: []const u8, buf: []u8) !?[]u8 { + const home_dir = try home(buf) orelse return null; + const rest = path[1..]; // Skip the ~ + const expanded_len = home_dir.len + rest.len; + + if (expanded_len > buf.len) return Error.BufferTooSmall; + @memcpy(buf[home_dir.len..expanded_len], rest); + + return buf[0..expanded_len]; +} + test { const testing = std.testing; diff --git a/src/os/main.zig b/src/os/main.zig index 98e57b4fc..fb1782862 100644 --- a/src/os/main.zig +++ b/src/os/main.zig @@ -38,6 +38,7 @@ pub const freeTmpDir = file.freeTmpDir; pub const isFlatpak = flatpak.isFlatpak; pub const FlatpakHostCommand = flatpak.FlatpakHostCommand; pub const home = homedir.home; +pub const expandHome = homedir.expandHome; pub const ensureLocale = locale.ensureLocale; pub const clickInterval = mouse.clickInterval; pub const open = openpkg.open;