Skip to content

Commit ecf5445

Browse files
authored
Fix Windows home directory for specific user (#861)
* Fix Windows home directory for specific user * Fix test failure
1 parent 7242610 commit ecf5445

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
@@ -377,12 +377,17 @@ extension String {
377377

378378
return fallback
379379
}
380+
381+
guard !user.isEmpty else {
382+
return fallbackUserDirectory()
383+
}
380384

381385
return user.withCString(encodedAs: UTF16.self) { pwszUserName in
382386
var cbSID: DWORD = 0
383387
var cchReferencedDomainName: DWORD = 0
384388
var eUse: SID_NAME_USE = SidTypeUnknown
385-
guard LookupAccountNameW(nil, pwszUserName, nil, &cbSID, nil, &cchReferencedDomainName, &eUse) else {
389+
LookupAccountNameW(nil, pwszUserName, nil, &cbSID, nil, &cchReferencedDomainName, &eUse)
390+
guard cbSID > 0 else {
386391
return fallbackUserDirectory()
387392
}
388393

@@ -397,10 +402,11 @@ extension String {
397402
fatalError("unable to convert SID to string for user \(user)")
398403
}
399404

400-
return #"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\#\(String(decodingCString: pwszSID!, as: UTF16.self))"#.withCString(encodedAs: UTF16.self) { pwszKeyPath in
405+
return #"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\\#(String(decodingCString: pwszSID!, as: UTF16.self))"#.withCString(encodedAs: UTF16.self) { pwszKeyPath in
401406
return "ProfileImagePath".withCString(encodedAs: UTF16.self) { pwszKey in
402407
var cbData: DWORD = 0
403-
guard RegGetValueW(HKEY_LOCAL_MACHINE, pwszKeyPath, pwszKey, RRF_RT_REG_SZ, nil, nil, &cbData) == ERROR_SUCCESS else {
408+
RegGetValueW(HKEY_LOCAL_MACHINE, pwszKeyPath, pwszKey, RRF_RT_REG_SZ, nil, nil, &cbData)
409+
guard cbData > 0 else {
404410
fatalError("unable to query ProfileImagePath for user \(user)")
405411
}
406412
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)