1
// Copyright 2015 Canonical Ltd.
2
// Licensed under the LGPLv3, see LICENCE file for details.
10
"github.com/juju/errors"
13
// ResolveSudo returns the original username if sudo was used. The
14
// original username is extracted from the OS environment.
15
func ResolveSudo(username string) string {
16
return resolveSudo(username, os.Getenv)
19
func resolveSudo(username string, getenvFunc func(string) string) string {
20
if username != "root" {
23
// sudo was probably called, get the original user.
24
if username := getenvFunc("SUDO_USER"); username != "" {
30
// EnvUsername returns the username from the OS environment.
31
func EnvUsername() (string, error) {
32
return os.Getenv("USER"), nil
35
// OSUsername returns the username of the current OS user (based on UID).
36
func OSUsername() (string, error) {
37
u, err := user.Current()
39
return "", errors.Trace(err)
41
return u.Username, nil
44
// ResolveUsername returns the username determined by the provided
45
// functions. The functions are tried in the same order in which they
46
// were passed in. An error returned from any of them is immediately
47
// returned. If an empty string is returned then that signals that the
48
// function did not find the username and the next function is tried.
49
// Once a username is found, the provided resolveSudo func (if any) is
50
// called with that username and the result is returned. If no username
51
// is found then errors.NotFound is returned.
52
func ResolveUsername(resolveSudo func(string) string, usernameFuncs ...func() (string, error)) (string, error) {
53
for _, usernameFunc := range usernameFuncs {
54
username, err := usernameFunc()
56
return "", errors.Trace(err)
59
if resolveSudo != nil {
60
if original := resolveSudo(username); original != "" {
67
return "", errors.NotFoundf("username")
70
// LocalUsername determines the current username on the local host.
71
func LocalUsername() (string, error) {
72
username, err := ResolveUsername(ResolveSudo, EnvUsername, OSUsername)
74
return "", errors.Annotatef(err, "cannot get current user from the environment: %v", os.Environ())