Skip to content

Fix for Windows: std.os.windows.DeleteFile() #6397

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions lib/std/fs/test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -813,3 +813,26 @@ fn run_lock_file_test(contexts: []FileLockTestContext) !void {
try threads.append(try std.Thread.spawn(ctx, FileLockTestContext.run));
}
}

test "deleteDir" {
var tmp_dir = tmpDir(.{});
defer tmp_dir.cleanup();

// deleting a non-existent directory
testing.expectError(error.FileNotFound, tmp_dir.dir.deleteDir("test_dir"));

var dir = try tmp_dir.dir.makeOpenPath("test_dir", .{});
var file = try dir.createFile("test_file", .{});
file.close();
dir.close();

// deleting a non-empty directory
testing.expectError(error.DirNotEmpty, tmp_dir.dir.deleteDir("test_dir"));

dir = try tmp_dir.dir.openDir("test_dir", .{});
try dir.deleteFile("test_file");
dir.close();

// deleting an empty directory
try tmp_dir.dir.deleteDir("test_dir");
}
18 changes: 17 additions & 1 deletion lib/std/os/windows.zig
Original file line number Diff line number Diff line change
Expand Up @@ -764,6 +764,7 @@ pub const DeleteFileError = error{
Unexpected,
NotDir,
IsDir,
DirNotEmpty,
};

pub const DeleteFileOptions = struct {
Expand Down Expand Up @@ -818,14 +819,29 @@ pub fn DeleteFile(sub_path_w: []const u16, options: DeleteFileOptions) DeleteFil
0,
);
switch (rc) {
.SUCCESS => return CloseHandle(tmp_handle),
.SUCCESS => CloseHandle(tmp_handle),
.OBJECT_NAME_INVALID => unreachable,
.OBJECT_NAME_NOT_FOUND => return error.FileNotFound,
.INVALID_PARAMETER => unreachable,
.FILE_IS_A_DIRECTORY => return error.IsDir,
.NOT_A_DIRECTORY => return error.NotDir,
else => return unexpectedStatus(rc),
}

// If a directory fails to be deleted, CloseHandle will still report success
// Check if the directory still exists and return error.DirNotEmpty if true
if (options.remove_dir) {
var basic_info: FILE_BASIC_INFORMATION = undefined;
switch (ntdll.NtQueryAttributesFile(&attr, &basic_info)) {
.SUCCESS => return error.DirNotEmpty,
.OBJECT_NAME_NOT_FOUND => return,
.OBJECT_PATH_NOT_FOUND => return,
.INVALID_PARAMETER => unreachable,
.ACCESS_DENIED => return error.AccessDenied,
.OBJECT_PATH_SYNTAX_BAD => unreachable,
else => |urc| return unexpectedStatus(urc),
}
}
}

pub const MoveFileError = error{ FileNotFound, Unexpected };
Expand Down