src/os: Add UserHomeDir() function to os package

This commit adds the `UserHomeDir()` function to the `os` package.
This commit is contained in:
ZauberNerd
2022-03-05 00:24:33 +00:00
committed by Ron Evans
parent 6f31712b7d
commit 6fb90b6fc4
2 changed files with 45 additions and 0 deletions
+27
View File
@@ -12,6 +12,7 @@ package os
import (
"errors"
"io"
"runtime"
"syscall"
)
@@ -259,3 +260,29 @@ func Getwd() (string, error) {
func TempDir() string {
return tempDir()
}
// UserHomeDir returns the current user's home directory.
//
// On Unix, including macOS, it returns the $HOME environment variable.
// On Windows, it returns %USERPROFILE%.
// On Plan 9, it returns the $home environment variable.
func UserHomeDir() (string, error) {
env, enverr := "HOME", "$HOME"
switch runtime.GOOS {
case "windows":
env, enverr = "USERPROFILE", "%userprofile%"
case "plan9":
env, enverr = "home", "$home"
}
if v := Getenv(env); v != "" {
return v, nil
}
// On some geese the home directory is not always defined.
switch runtime.GOOS {
case "android":
return "/sdcard", nil
case "ios":
return "/", nil
}
return "", errors.New(enverr + " is not defined")
}