github.com/zaolin/u-root@v0.0.0-20200428085104-64aaafd46c6d/cmds/core/elvish/util/gethome.go (about)

     1  package util
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"os/user"
     7  	"strings"
     8  )
     9  
    10  // GetHome finds the home directory of a specified user. When given an empty
    11  // string, it finds the home directory of the current user.
    12  func GetHome(uname string) (string, error) {
    13  	if uname == "" {
    14  		// Use $HOME as override if we are looking for the home of the current
    15  		// variable.
    16  		home := os.Getenv("HOME")
    17  		if home != "" {
    18  			return strings.TrimRight(home, pathSep), nil
    19  		}
    20  	}
    21  
    22  	// Look up the user.
    23  	var u *user.User
    24  	var err error
    25  	if uname == "" {
    26  		u, err = user.Current()
    27  	} else {
    28  		u, err = user.Lookup(uname)
    29  	}
    30  	if err != nil {
    31  		return "", fmt.Errorf("can't resolve ~%s: %s", uname, err.Error())
    32  	}
    33  	return strings.TrimRight(u.HomeDir, "/"), nil
    34  }