move tilde expansion functionality to os/homedir

This commit is contained in:
z-jxy
2024-12-28 20:38:58 -05:00
committed by Mitchell Hashimoto
parent d27761a499
commit 138a8f1602
3 changed files with 30 additions and 22 deletions

View File

@ -4364,35 +4364,26 @@ 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) {
if (try internal_os.expandHome(path, &buf)) |expanded_path| {
log.debug(
"expanding file path from home directory: path={s}",
.{expanded_path},
);
switch (self.value.items[i]) {
.optional, .required => |*p| p.* = try alloc.dupeZ(u8, expanded_path),
}
continue;
} else {
try diags.append(alloc, .{
.message = try std.fmt.allocPrintZ(
alloc,
"error resolving file path {s}: path too long after expanding home directory",
"error expanding home path {s}",
.{path},
),
});
self.value.items[i] = .{ .required = "" };
continue;
}
@memcpy(buf[home_dir.len..expanded_len], rest);
log.debug(
"expanding file path from home directory: path={s}",
.{buf[0..expanded_len]},
);
switch (self.value.items[i]) {
.optional, .required => |*p| p.* = try alloc.dupeZ(u8, buf[0..expanded_len]),
}
continue;
}
}
const abs = dir.realpath(path, &buf) catch |err| abs: {

View File

@ -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;

View File

@ -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;