util.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. }
  46. var windowsDisallowedCharacters = string([]rune{
  47. '<', '>', ':', '"', '|', '?', '*',
  48. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
  49. 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
  50. 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
  51. 31,
  52. })
  53. func WindowsInvalidFilename(name string) bool {
  54. // None of the path components should end in space
  55. for _, part := range strings.Split(name, `\`) {
  56. if len(part) == 0 {
  57. continue
  58. }
  59. if part[len(part)-1] == ' ' {
  60. // Names ending in space are not valid.
  61. return true
  62. }
  63. }
  64. // The path must not contain any disallowed characters
  65. return strings.ContainsAny(name, windowsDisallowedCharacters)
  66. }