github.com/gogf/gf/v2@v2.7.4/os/gfile/gfile_home.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package gfile
     8  
     9  import (
    10  	"bytes"
    11  	"os"
    12  	"os/exec"
    13  	"os/user"
    14  	"runtime"
    15  	"strings"
    16  
    17  	"github.com/gogf/gf/v2/errors/gerror"
    18  )
    19  
    20  // Home returns absolute path of current user's home directory.
    21  // The optional parameter `names` specifies the sub-folders/sub-files,
    22  // which will be joined with current system separator and returned with the path.
    23  func Home(names ...string) (string, error) {
    24  	path, err := getHomePath()
    25  	if err != nil {
    26  		return "", err
    27  	}
    28  	for _, name := range names {
    29  		path += Separator + name
    30  	}
    31  	return path, nil
    32  }
    33  
    34  // getHomePath returns absolute path of current user's home directory.
    35  func getHomePath() (string, error) {
    36  	u, err := user.Current()
    37  	if nil == err {
    38  		return u.HomeDir, nil
    39  	}
    40  	if runtime.GOOS == "windows" {
    41  		return homeWindows()
    42  	}
    43  	return homeUnix()
    44  }
    45  
    46  // homeUnix retrieves and returns the home on unix system.
    47  func homeUnix() (string, error) {
    48  	if home := os.Getenv("HOME"); home != "" {
    49  		return home, nil
    50  	}
    51  	var stdout bytes.Buffer
    52  	cmd := exec.Command("sh", "-c", "eval echo ~$USER")
    53  	cmd.Stdout = &stdout
    54  	if err := cmd.Run(); err != nil {
    55  		err = gerror.Wrapf(err, `retrieve home directory failed`)
    56  		return "", err
    57  	}
    58  
    59  	result := strings.TrimSpace(stdout.String())
    60  	if result == "" {
    61  		return "", gerror.New("blank output when reading home directory")
    62  	}
    63  
    64  	return result, nil
    65  }
    66  
    67  // homeWindows retrieves and returns the home on windows system.
    68  func homeWindows() (string, error) {
    69  	var (
    70  		drive = os.Getenv("HOMEDRIVE")
    71  		path  = os.Getenv("HOMEPATH")
    72  		home  = drive + path
    73  	)
    74  	if drive == "" || path == "" {
    75  		home = os.Getenv("USERPROFILE")
    76  	}
    77  	if home == "" {
    78  		return "", gerror.New("environment keys HOMEDRIVE, HOMEPATH and USERPROFILE are empty")
    79  	}
    80  
    81  	return home, nil
    82  }