Skip to content

Fix Windows home directory for specific user #861

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
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
12 changes: 9 additions & 3 deletions Sources/FoundationEssentials/String/String+Path.swift
Original file line number Diff line number Diff line change
Expand Up @@ -377,12 +377,17 @@ extension String {

return fallback
}

guard !user.isEmpty else {
return fallbackUserDirectory()
}

return user.withCString(encodedAs: UTF16.self) { pwszUserName in
var cbSID: DWORD = 0
var cchReferencedDomainName: DWORD = 0
var eUse: SID_NAME_USE = SidTypeUnknown
guard LookupAccountNameW(nil, pwszUserName, nil, &cbSID, nil, &cchReferencedDomainName, &eUse) else {
LookupAccountNameW(nil, pwszUserName, nil, &cbSID, nil, &cchReferencedDomainName, &eUse)
guard cbSID > 0 else {
return fallbackUserDirectory()
}

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

return #"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\#\(String(decodingCString: pwszSID!, as: UTF16.self))"#.withCString(encodedAs: UTF16.self) { pwszKeyPath in
return #"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\\#(String(decodingCString: pwszSID!, as: UTF16.self))"#.withCString(encodedAs: UTF16.self) { pwszKeyPath in
return "ProfileImagePath".withCString(encodedAs: UTF16.self) { pwszKey in
var cbData: DWORD = 0
guard RegGetValueW(HKEY_LOCAL_MACHINE, pwszKeyPath, pwszKey, RRF_RT_REG_SZ, nil, nil, &cbData) == ERROR_SUCCESS else {
RegGetValueW(HKEY_LOCAL_MACHINE, pwszKeyPath, pwszKey, RRF_RT_REG_SZ, nil, nil, &cbData)
guard cbData > 0 else {
fatalError("unable to query ProfileImagePath for user \(user)")
}
return withUnsafeTemporaryAllocation(of: WCHAR.self, capacity: Int(cbData)) { pwszData in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,15 @@ final class FileManagerTests : XCTestCase {
try $0.setAttributes(attrs, ofItemAtPath: "foo")
}
}

func testCurrentUserHomeDirectory() throws {
#if canImport(Darwin) && !os(macOS)
throw XCTSkip("This test is not applicable on this platform")
#else
let userName = ProcessInfo.processInfo.userName
XCTAssertEqual(FileManager.default.homeDirectory(forUser: userName), FileManager.default.homeDirectoryForCurrentUser)
#endif
}

func testAttributesOfItemAtPath() throws {
try FileManagerPlayground {
Expand Down