pathutil_plan9.go raw

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