util.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright (C) 2016 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package fs
  7. import (
  8. "errors"
  9. "fmt"
  10. "os"
  11. "path/filepath"
  12. "runtime"
  13. "strings"
  14. )
  15. var errNoHome = errors.New("no home directory found - set $HOME (or the platform equivalent)")
  16. func ExpandTilde(path string) (string, error) {
  17. if path == "~" {
  18. return getHomeDir()
  19. }
  20. path = filepath.FromSlash(path)
  21. if !strings.HasPrefix(path, fmt.Sprintf("~%c", PathSeparator)) {
  22. return path, nil
  23. }
  24. home, err := getHomeDir()
  25. if err != nil {
  26. return "", err
  27. }
  28. return filepath.Join(home, path[2:]), nil
  29. }
  30. func getHomeDir() (string, error) {
  31. var home string
  32. switch runtime.GOOS {
  33. case "windows":
  34. home = filepath.Join(os.Getenv("HomeDrive"), os.Getenv("HomePath"))
  35. if home == "" {
  36. home = os.Getenv("UserProfile")
  37. }
  38. default:
  39. home = os.Getenv("HOME")
  40. }
  41. if home == "" {
  42. return "", errNoHome
  43. }
  44. return home, nil
  45. }