diff options
author | bibo38 <bibo38@users.noreply.github.com> | 2020-08-19 15:17:16 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-08-19 21:17:16 +0800 |
commit | 252d0fd9775e40b641e5edc6facb147741c3b217 (patch) | |
tree | 26e87a39a0ed4ba6a3bcadb2395f6cc5dc3751b0 /internal/osutil/osutil.go | |
parent | d1caae3f79e137c3ca1d59dc827fcca519f5eede (diff) |
osutil: use system API to get the username when env vars are empty (#6246)
As Golang supports getting usernames via the standard library, this function
is now used to get the username if the environment variables are empty.
Using the standard library as a fallback is intended to keep compability
to existing implementations that rely on the environment variables dictating
the current username.
Diffstat (limited to 'internal/osutil/osutil.go')
-rw-r--r-- | internal/osutil/osutil.go | 13 |
1 files changed, 11 insertions, 2 deletions
diff --git a/internal/osutil/osutil.go b/internal/osutil/osutil.go index b2205a46..4f871587 100644 --- a/internal/osutil/osutil.go +++ b/internal/osutil/osutil.go @@ -6,6 +6,7 @@ package osutil import ( "os" + "os/user" ) // IsFile returns true if given path exists as a file (i.e. not a directory). @@ -33,12 +34,20 @@ func IsExist(path string) bool { return err == nil || os.IsExist(err) } -// CurrentUsername returns the current system user via environment variables. +// CurrentUsername returns the current system user func CurrentUsername() string { username := os.Getenv("USER") if len(username) > 0 { return username } - return os.Getenv("USERNAME") + username = os.Getenv("USERNAME") + if len(username) > 0 { + return username + } + + if user, err := user.Current(); err == nil { + username = user.Username + } + return username } |