elvish/util/gethome.go

35 lines
727 B
Go
Raw Normal View History

package util
2016-02-11 07:12:48 +08:00
import (
"fmt"
"os"
2016-02-11 07:12:48 +08:00
"os/user"
"strings"
2016-02-11 07:12:48 +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) {
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())
}
return strings.TrimRight(u.HomeDir, "/"), nil
2016-02-11 07:12:48 +08:00
}