Skip to content

Commit abb8024

Browse files
committed
Fix Windows home directory for specific user (swiftlang#861)
* Fix Windows home directory for specific user * Fix test failure
1 parent 5b61e03 commit abb8024

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

Sources/FoundationEssentials/String/String+Path.swift

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -375,12 +375,17 @@ extension String {
375375

376376
return fallback
377377
}
378+
379+
guard !user.isEmpty else {
380+
return fallbackUserDirectory()
381+
}
378382

379383
return user.withCString(encodedAs: UTF16.self) { pwszUserName in
380384
var cbSID: DWORD = 0
381385
var cchReferencedDomainName: DWORD = 0
382386
var eUse: SID_NAME_USE = SidTypeUnknown
383-
guard LookupAccountNameW(nil, pwszUserName, nil, &cbSID, nil, &cchReferencedDomainName, &eUse) else {
387+
LookupAccountNameW(nil, pwszUserName, nil, &cbSID, nil, &cchReferencedDomainName, &eUse)
388+
guard cbSID > 0 else {
384389
return fallbackUserDirectory()
385390
}
386391

@@ -395,10 +400,11 @@ extension String {
395400
fatalError("unable to convert SID to string for user \(user)")
396401
}
397402

398-
return #"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\#\(String(decodingCString: pwszSID!, as: UTF16.self))"#.withCString(encodedAs: UTF16.self) { pwszKeyPath in
403+
return #"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\\#(String(decodingCString: pwszSID!, as: UTF16.self))"#.withCString(encodedAs: UTF16.self) { pwszKeyPath in
399404
return "ProfileImagePath".withCString(encodedAs: UTF16.self) { pwszKey in
400405
var cbData: DWORD = 0
401-
guard RegGetValueW(HKEY_LOCAL_MACHINE, pwszKeyPath, pwszKey, RRF_RT_REG_SZ, nil, nil, &cbData) == ERROR_SUCCESS else {
406+
RegGetValueW(HKEY_LOCAL_MACHINE, pwszKeyPath, pwszKey, RRF_RT_REG_SZ, nil, nil, &cbData)
407+
guard cbData > 0 else {
402408
fatalError("unable to query ProfileImagePath for user \(user)")
403409
}
404410
return withUnsafeTemporaryAllocation(of: WCHAR.self, capacity: Int(cbData)) { pwszData in

Tests/FoundationEssentialsTests/FileManager/FileManagerTests.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -909,6 +909,15 @@ final class FileManagerTests : XCTestCase {
909909
try $0.setAttributes(attrs, ofItemAtPath: "foo")
910910
}
911911
}
912+
913+
func testCurrentUserHomeDirectory() throws {
914+
#if canImport(Darwin) && !os(macOS)
915+
throw XCTSkip("This test is not applicable on this platform")
916+
#else
917+
let userName = ProcessInfo.processInfo.userName
918+
XCTAssertEqual(FileManager.default.homeDirectory(forUser: userName), FileManager.default.homeDirectoryForCurrentUser)
919+
#endif
920+
}
912921

913922
func testAttributesOfItemAtPath() throws {
914923
try FileManagerPlayground {

0 commit comments

Comments
 (0)