Skip to content

Commit 56c44b0

Browse files
authored
Fix Windows home directory for specific user (#861) (#868)
* Fix Windows home directory for specific user * Fix test failure
1 parent 318ea46 commit 56c44b0

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
@@ -917,6 +917,15 @@ final class FileManagerTests : XCTestCase {
917917
try $0.setAttributes(attrs, ofItemAtPath: "foo")
918918
}
919919
}
920+
921+
func testCurrentUserHomeDirectory() throws {
922+
#if canImport(Darwin) && !os(macOS)
923+
throw XCTSkip("This test is not applicable on this platform")
924+
#else
925+
let userName = ProcessInfo.processInfo.userName
926+
XCTAssertEqual(FileManager.default.homeDirectory(forUser: userName), FileManager.default.homeDirectoryForCurrentUser)
927+
#endif
928+
}
920929

921930
func testAttributesOfItemAtPath() throws {
922931
try FileManagerPlayground {

0 commit comments

Comments
 (0)