resolveUserDirectory static method
Resolves the user's home directory from the environment variables
envVars: USERPROFILE on Windows, else HOME (each with the other as
fallback). Returns null if not defined or not an existing directory.
The shell's ~ is not used as a fallback: Directory('~/') is a
literal directory named ~ (relative to the current directory), not
the home directory.
Implementation
@visibleForTesting
static Directory? resolveUserDirectory(
Map<String, String> envVars, {
required bool isWindows,
}) {
// `Platform.environment` keys are case-insensitive on Windows, but a
// plain `Map` (tests) is not: try both spellings of `USERPROFILE`.
var userProfile = envVars['USERPROFILE'] ?? envVars['UserProfile'];
var home = envVars['HOME'];
var candidates = isWindows ? [userProfile, home] : [home, userProfile];
for (var path in candidates) {
if (path == null || path.trim().isEmpty) continue;
var dir = Directory(path);
if (dir.existsSync()) {
return dir.absolute;
}
}
return null;
}