github.com/markusbkk/elvish@v0.0.0-20231204143114-91dc52438621/pkg/fsutil/gethome.go (about)

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