2021-01-17 21:46:25 +08:00
|
|
|
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
2020-03-28 00:37:23 +08:00
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
|
|
|
|
|
|
|
package gfile
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
|
|
|
"os/user"
|
|
|
|
"runtime"
|
|
|
|
"strings"
|
2021-11-05 14:30:50 +08:00
|
|
|
|
|
|
|
"github.com/gogf/gf/v2/errors/gerror"
|
2020-03-28 00:37:23 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
// Home returns absolute path of current user's home directory.
|
2021-11-01 19:46:39 +08:00
|
|
|
// The optional parameter `names` specifies the sub-folders/sub-files,
|
2020-03-28 00:37:23 +08:00
|
|
|
// which will be joined with current system separator and returned with the path.
|
|
|
|
func Home(names ...string) (string, error) {
|
|
|
|
path, err := getHomePath()
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
for _, name := range names {
|
|
|
|
path += Separator + name
|
|
|
|
}
|
|
|
|
return path, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// getHomePath returns absolute path of current user's home directory.
|
|
|
|
func getHomePath() (string, error) {
|
|
|
|
u, err := user.Current()
|
|
|
|
if nil == err {
|
|
|
|
return u.HomeDir, nil
|
|
|
|
}
|
2021-11-05 14:30:50 +08:00
|
|
|
if runtime.GOOS == "windows" {
|
2020-03-28 00:37:23 +08:00
|
|
|
return homeWindows()
|
|
|
|
}
|
|
|
|
return homeUnix()
|
|
|
|
}
|
|
|
|
|
|
|
|
// homeUnix retrieves and returns the home on unix system.
|
|
|
|
func homeUnix() (string, error) {
|
|
|
|
if home := os.Getenv("HOME"); home != "" {
|
|
|
|
return home, nil
|
|
|
|
}
|
|
|
|
var stdout bytes.Buffer
|
|
|
|
cmd := exec.Command("sh", "-c", "eval echo ~$USER")
|
|
|
|
cmd.Stdout = &stdout
|
|
|
|
if err := cmd.Run(); err != nil {
|
2021-12-23 00:09:00 +08:00
|
|
|
err = gerror.Wrapf(err, `retrieve home directory failed`)
|
2020-03-28 00:37:23 +08:00
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
result := strings.TrimSpace(stdout.String())
|
|
|
|
if result == "" {
|
2021-12-21 22:59:14 +08:00
|
|
|
return "", gerror.New("blank output when reading home directory")
|
2020-03-28 00:37:23 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return result, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// homeWindows retrieves and returns the home on windows system.
|
|
|
|
func homeWindows() (string, error) {
|
|
|
|
var (
|
|
|
|
drive = os.Getenv("HOMEDRIVE")
|
|
|
|
path = os.Getenv("HOMEPATH")
|
|
|
|
home = drive + path
|
|
|
|
)
|
|
|
|
if drive == "" || path == "" {
|
|
|
|
home = os.Getenv("USERPROFILE")
|
|
|
|
}
|
|
|
|
if home == "" {
|
2021-12-23 00:09:00 +08:00
|
|
|
return "", gerror.New("environment keys HOMEDRIVE, HOMEPATH and USERPROFILE are empty")
|
2020-03-28 00:37:23 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return home, nil
|
|
|
|
}
|