From 0d3792122d6a9522a7692f95541d28622e7680c4 Mon Sep 17 00:00:00 2001 From: Saleem Abdulrasool Date: Mon, 23 Jan 2023 09:50:22 -0800 Subject: [PATCH] FileManager: repair `homeDirectoryForCurrentUser` on Windows `NetUserGetInfo` will not provide the home directory for the specified user most of the time, even if the user is the currently logged in user. Prefer to use the `CFCopyHomeDirectoryURLForUser` path which will provide the home directory for the current user. Fast-path that into the computed property and add a special case for `homeDirectory(forUser:)` to accommodate this behavioural difference. --- Sources/Foundation/FileManager.swift | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/Sources/Foundation/FileManager.swift b/Sources/Foundation/FileManager.swift index 9b649d2ca6..491d67b3ad 100644 --- a/Sources/Foundation/FileManager.swift +++ b/Sources/Foundation/FileManager.swift @@ -1140,7 +1140,7 @@ open class FileManager : NSObject { } open var homeDirectoryForCurrentUser: URL { - return homeDirectory(forUser: NSUserName())! + CFCopyHomeDirectoryURLForUser(nil)!.takeRetainedValue()._swiftObject } open var temporaryDirectory: URL { @@ -1149,8 +1149,13 @@ open class FileManager : NSObject { open func homeDirectory(forUser userName: String) -> URL? { guard !userName.isEmpty else { return nil } - guard let url = CFCopyHomeDirectoryURLForUser(userName._cfObject) else { return nil } - return url.takeRetainedValue()._swiftObject + // Prefer to take the `CFCopyHomeDirectoryURLForUser` path for the + // current user. + return CFCopyHomeDirectoryURLForUser(userName == NSUserName() + ? nil + : userName._cfObject)? + .takeRetainedValue() + ._swiftObject } }