mirror of
https://github.com/apple/swift-nio
synced 2026-11-26 04:57:49 +00:00
Add homeDirectory accessor to FileSystem (#3471)
Add homeDirectory accessor to FileSystem ### Motivation: Addresses #3381 by adding a `homeDirectory` property to FileSystem, equivalent to `FileManager.default.homeDirectoryForCurrentUser`. ### Modifications: - Added `homeDirectory` property to `FileSystemProtocol` and implemented in `FileSystem` - Implementation checks `HOME` environment variable first, falls back to `USERPROFILE` on Windows, or uses `getpwuid_r(3)` on POSIX systems - Added system call wrappers (`system_getuid`, `libc_getpwuid_r`) with proper platform guards - Added `FileSystemError.getpwuid_r()` error helper ### Result: Users can now access the home directory via `FileSystem.homeDirectory`, returning a `FilePath` asynchronously. Follows the same pattern as `currentWorkingDirectory` and `temporaryDirectory`. Co-authored-by: Cory Benfield <lukasa@apple.com>
This commit is contained in:
1 parent
4a9a971110
commit
608e511d7a
11 files changed
+267
No files matched your search
@@ -651,6 +651,35 @@ public struct FileSystem: Sendable, FileSystemProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the path of the current user's home directory.
|
||||
///
|
||||
/// #### Implementation details
|
||||
///
|
||||
/// This function first checks the `HOME` environment variable (and `USERPROFILE` on Windows).
|
||||
/// If not set, on Darwin/Linux/Android it uses `getpwuid_r(3)` to query the password database.
|
||||
///
|
||||
/// Note: `getpwuid_r` can potentially block on I/O (e.g., when using NIS or LDAP),
|
||||
/// which is why this property is async when falling back to the password database.
|
||||
///
|
||||
/// - Returns: The path to the current user's home directory.
|
||||
public var homeDirectory: FilePath {
|
||||
get async throws {
|
||||
if let path = Libc.homeDirectoryFromEnvironment() {
|
||||
return path
|
||||
}
|
||||
|
||||
#if canImport(Darwin) || canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
return try await self.threadPool.runIfActive {
|
||||
try Libc.homeDirectoryFromPasswd().mapError { errno in
|
||||
FileSystemError.getpwuid_r(errno: errno, location: .here())
|
||||
}.get()
|
||||
}
|
||||
#else
|
||||
throw FileSystemError.getpwuid_r(errno: .noSuchFileOrDirectory, location: .here())
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a path to a temporary directory.
|
||||
///
|
||||
/// #### Implementation details
|
||||
|
||||
Reference in new issue
Block a user