pathutil_unix.go raw

   1  //go:build aix || darwin || dragonfly || freebsd || (js && wasm) || nacl || linux || netbsd || openbsd || solaris
   2  
   3  package pathutil
   4  
   5  import (
   6  	"errors"
   7  	"io/fs"
   8  	"os"
   9  	"path/filepath"
  10  	"strings"
  11  )
  12  
  13  // UserHomeDir returns the home directory of the current user.
  14  func UserHomeDir() string {
  15  	if home := os.Getenv("HOME"); home != "" {
  16  		return home
  17  	}
  18  
  19  	return "/"
  20  }
  21  
  22  // Exists returns true if the specified path exists.
  23  func Exists(path string) bool {
  24  	_, err := os.Stat(path)
  25  	return err == nil || errors.Is(err, fs.ErrExist)
  26  }
  27  
  28  // ExpandHome substitutes `~` and `$HOME` at the start of the specified `path`.
  29  func ExpandHome(path string) string {
  30  	home := UserHomeDir()
  31  	if path == "" || home == "" {
  32  		return path
  33  	}
  34  	if path[0] == '~' {
  35  		return filepath.Join(home, path[1:])
  36  	}
  37  	if strings.HasPrefix(path, "$HOME") {
  38  		return filepath.Join(home, path[5:])
  39  	}
  40  
  41  	return path
  42  }
  43