get user home

This commit is contained in:
Liang Ding 2015-02-16 10:06:17 +08:00
parent ce489a73e7
commit c5f3942ed7
4 changed files with 76 additions and 4 deletions

View File

@ -161,14 +161,22 @@ func initWide(confPath, confIP, confPort, confServer, confLogLevel, confStaticSe
logger.Debugf("${pwd} [%s]", Wide.WD)
// User Home
userHome := ""
user, err := user.Current()
if nil != err {
logger.Error("Can't get user's home, please report this issue to developer")
if nil == err {
userHome = user.HomeDir
} else {
// cross compile support for darwin
home, er := util.OS.Home()
if nil != er {
logger.Error("Can't get user's home, please report this issue to developer", err, er)
os.Exit(-1)
os.Exit(-1)
}
userHome = home
}
userHome := user.HomeDir
logger.Debugf("${user.home} [%s]", userHome)
// Playground Directory

View File

@ -25,6 +25,7 @@ func TestGetAPIPath(t *testing.T) {
apiPath := Go.GetAPIPath()
v := runtime.Version()[2:]
v = v[:3]
verNum, err := strconv.ParseFloat(v, 64)

View File

@ -15,10 +15,13 @@
package util
import (
"bytes"
"errors"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
type myos struct{}
@ -38,3 +41,52 @@ func (*myos) Pwd() string {
return filepath.Dir(pwd)
}
// Home returns the home directory for the executing user.
//
// This uses an OS-specific method for discovering the home directory.
// An error is returned if a home directory cannot be detected.
func (*myos) Home() (string, error) {
if OS.IsWindows() {
return homeWindows()
}
// Unix-like system, so just assume Unix
return homeUnix()
}
func homeUnix() (string, error) {
// First prefer the HOME environmental variable
if home := os.Getenv("HOME"); home != "" {
return home, nil
}
// If that fails, try the shell
var stdout bytes.Buffer
cmd := exec.Command("sh", "-c", "eval echo ~$USER")
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil {
return "", err
}
result := strings.TrimSpace(stdout.String())
if result == "" {
return "", errors.New("blank output when reading home directory")
}
return result, nil
}
func homeWindows() (string, error) {
drive := os.Getenv("HOMEDRIVE")
path := os.Getenv("HOMEPATH")
home := drive + path
if drive == "" || path == "" {
home = os.Getenv("USERPROFILE")
}
if home == "" {
return "", errors.New("HOMEDRIVE, HOMEPATH, and USERPROFILE are blank")
}
return home, nil
}

View File

@ -36,3 +36,14 @@ func TestPwd(t *testing.T) {
return
}
}
func TestHome(t *testing.T) {
home, err := OS.Home()
if nil != err {
t.Error("Can not get user home")
return
}
t.Log(home)
}