-
Notifications
You must be signed in to change notification settings - Fork 4
/
osutil.go
51 lines (47 loc) · 1.31 KB
/
osutil.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package util
import (
"fmt"
"os"
"os/user"
"runtime"
)
// GetUserHomeDir returns the home directory of the current user
// If the process is run as sudo, it will return the home directory of the sudo user
// ie. the orginal user (not root), based on the SUDO_USER env var
func GetUserHomeDir() (string, error) {
var homedir string
// check we're using SUDO
// We can do this by check the SUDO_USER env var
sudoUsername := os.Getenv("SUDO_USER")
if sudoUsername != "" {
if runtime.GOOS == "darwin" {
// This is because of:
// https://github.com/golang/go/issues/24383
// os/user: LookupUser() doesn't find users on macOS when compiled with CGO_ENABLED=0
// So we'll just hard code for MACOS
homedir = "/Users/" + sudoUsername
} else {
currentUser, err := user.Lookup(sudoUsername)
if err != nil {
return "", fmt.Errorf("couldn't get user details: %w", err)
}
homedir = currentUser.HomeDir
}
} else {
var err error
homedir, err = os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("couldn't get user home dir: %w", err)
}
}
return homedir, nil
}
// RunningAsAdministrator returns true if the
// runtime has administrative privileges.
func RunningAsAdministrator() bool {
if runtime.GOOS != "windows" {
return os.Geteuid() == 0
}
// FIXME: handle windows
return true
}