2016-02-17 02:14:05 +08:00
|
|
|
package util
|
2016-02-11 07:12:48 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2016-02-12 06:43:48 +08:00
|
|
|
"os"
|
2016-02-11 07:12:48 +08:00
|
|
|
"os/user"
|
2016-02-12 06:43:48 +08:00
|
|
|
"strings"
|
2016-02-11 07:12:48 +08:00
|
|
|
)
|
|
|
|
|
2016-02-17 08:23:36 +08:00
|
|
|
// GetHome finds the home directory of a specified user. When given an empty
|
|
|
|
// string, it finds the home directory of the current user.
|
2016-02-11 07:12:48 +08:00
|
|
|
func GetHome(uname string) (string, error) {
|
2016-02-17 08:23:36 +08:00
|
|
|
if uname == "" {
|
|
|
|
// Use $HOME as override if we are looking for the home of the current
|
|
|
|
// variable.
|
|
|
|
home := os.Getenv("HOME")
|
|
|
|
if home != "" {
|
|
|
|
return strings.TrimRight(home, "/"), nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-02-17 08:40:46 +08:00
|
|
|
// Look up the user.
|
2016-02-11 07:12:48 +08:00
|
|
|
var u *user.User
|
|
|
|
var err error
|
|
|
|
if uname == "" {
|
|
|
|
u, err = user.Current()
|
|
|
|
} else {
|
|
|
|
u, err = user.Lookup(uname)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("can't resolve ~%s: %s", uname, err.Error())
|
|
|
|
}
|
2016-02-12 06:43:48 +08:00
|
|
|
return strings.TrimRight(u.HomeDir, "/"), nil
|
2016-02-11 07:12:48 +08:00
|
|
|
}
|