windows: implement tmpDir

This commit is contained in:
Will Pragnell
2023-09-14 18:26:08 -07:00
parent ef9ed48434
commit 57894786d4
3 changed files with 17 additions and 7 deletions

View File

@ -61,8 +61,9 @@ pub fn name(self: *TempDir) []const u8 {
}
/// Finish with the temporary directory. This deletes all contents in the
/// directory. This is safe to call multiple times.
/// directory.
pub fn deinit(self: *TempDir) void {
self.dir.close();
self.parent.deleteTree(self.name()) catch |err|
log.err("error deleting temp dir err={}", .{err});
}
@ -78,13 +79,14 @@ const b64_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345
test {
var td = try init();
defer td.deinit();
errdefer td.deinit();
const nameval = td.name();
try testing.expect(nameval.len > 0);
// Can open a new handle to it proves it exists.
_ = try td.parent.openDir(nameval, .{});
var dir = try td.parent.openDir(nameval, .{});
dir.close();
// Should be deleted after we deinit
td.deinit();

View File

@ -53,6 +53,16 @@ pub fn fixMaxFiles() void {
/// Return the recommended path for temporary files.
pub fn tmpDir() ?[]const u8 {
if (builtin.os.tag == .windows) {
// TODO: what is a good fallback path on windows?
const w_temp = std.os.getenvW(std.unicode.utf8ToUtf16LeStringLiteral("TMP")) orelse return null;
var buf = [_]u8{0} ** 256; // 256 is the maximum path length on windows
const len = std.unicode.utf16leToUtf8(buf[0..], w_temp[0..w_temp.len]) catch {
log.warn("failed to convert temp dir path from windows string", .{});
return null;
};
return buf[0..len];
}
if (std.os.getenv("TMPDIR")) |v| return v;
if (std.os.getenv("TMP")) |v| return v;
return "/tmp";

View File

@ -84,8 +84,7 @@ fn homeWindows(buf: []u8) !?[]u8 {
const fba = fba_instance.allocator();
const drive = std.process.getEnvVarOwned(fba, "HOMEDRIVE") catch |err| switch (err) {
error.OutOfMemory => return Error.BufferTooSmall,
error.InvalidUtf8,
error.EnvironmentVariableNotFound => return null,
error.InvalidUtf8, error.EnvironmentVariableNotFound => return null,
};
// could shift the contents if this ever happens
if (drive.ptr != buf.ptr) @panic("codebug");
@ -98,8 +97,7 @@ fn homeWindows(buf: []u8) !?[]u8 {
const fba = fba_instance.allocator();
const homepath = std.process.getEnvVarOwned(fba, "HOMEPATH") catch |err| switch (err) {
error.OutOfMemory => return Error.BufferTooSmall,
error.InvalidUtf8,
error.EnvironmentVariableNotFound => return null,
error.InvalidUtf8, error.EnvironmentVariableNotFound => return null,
};
// could shift the contents if this ever happens
if (homepath.ptr != path_buf.ptr) @panic("codebug");