github.com/wtfutil/wtf@v0.43.0/utils/homedir.go (about)

     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  
     5  package utils
     6  
     7  import (
     8  	"errors"
     9  	"os"
    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.
    16  func ExpandHomeDir(path string) (string, error) {
    17  	if path == "" {
    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 := os.UserHomeDir()
    30  	if err != nil {
    31  		return "", err
    32  	}
    33  
    34  	return filepath.Join(dir, path[1:]), nil
    35  }