1// Package homedir helps with detecting and expanding the user's home directory 2 3// Copied (mostly) verbatim from https://github.com/Atrox/homedir 4 5package utils 6 7import ( 8 "errors" 9 "os/user" 10 "path/filepath" 11) 12 13// ExpandHomeDir expands the path to include the home directory if the path 14// is prefixed with `~`. If it isn't prefixed with `~`, the path is 15// returned as-is. 16func ExpandHomeDir(path string) (string, error) { 17 if len(path) == 0 { 18 return path, nil 19 } 20 21 if path[0] != '~' { 22 return path, nil 23 } 24 25 if len(path) > 1 && path[1] != '/' && path[1] != '\\' { 26 return "", errors.New("cannot expand user-specific home dir") 27 } 28 29 dir, err := Home() 30 if err != nil { 31 return "", err 32 } 33 34 return filepath.Join(dir, path[1:]), nil 35} 36 37// Home returns the home directory for the executing user. 38// An error is returned if a home directory cannot be detected. 39func Home() (string, error) { 40 currentUser, err := user.Current() 41 if err != nil { 42 return "", err 43 } 44 45 if currentUser.HomeDir == "" { 46 return "", errors.New("cannot find user-specific home dir") 47 } 48 49 return currentUser.HomeDir, nil 50} 51