util.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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. if runtime.GOOS == "windows" {
  32. // Legacy -- we prioritize this for historical reasons, whereas
  33. // os.UserHomeDir uses %USERPROFILE% always.
  34. home := filepath.Join(os.Getenv("HomeDrive"), os.Getenv("HomePath"))
  35. if home != "" {
  36. return home, nil
  37. }
  38. }
  39. return os.UserHomeDir()
  40. }
  41. var windowsDisallowedCharacters = string([]rune{
  42. '<', '>', ':', '"', '|', '?', '*',
  43. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
  44. 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
  45. 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
  46. 31,
  47. })
  48. func WindowsInvalidFilename(name string) bool {
  49. // None of the path components should end in space
  50. for _, part := range strings.Split(name, `\`) {
  51. if len(part) == 0 {
  52. continue
  53. }
  54. if part[len(part)-1] == ' ' {
  55. // Names ending in space are not valid.
  56. return true
  57. }
  58. }
  59. // The path must not contain any disallowed characters
  60. return strings.ContainsAny(name, windowsDisallowedCharacters)
  61. }
  62. // IsParent compares paths purely lexicographically, meaning it returns false
  63. // if path and parent aren't both absolute or relative.
  64. func IsParent(path, parent string) bool {
  65. if parent == path {
  66. // Twice the same root on windows would not be caught at the end.
  67. return false
  68. }
  69. if filepath.IsAbs(path) != filepath.IsAbs(parent) {
  70. return false
  71. }
  72. if parent == "" || parent == "." {
  73. // The empty string is the parent of everything except the empty
  74. // string and ".". (Avoids panic in the last step.)
  75. return path != "" && path != "."
  76. }
  77. if parent == "/" {
  78. // The root is the parent of everything except itself, which would
  79. // not be caught below.
  80. return path != "/"
  81. }
  82. if parent[len(parent)-1] != PathSeparator {
  83. parent += string(PathSeparator)
  84. }
  85. return strings.HasPrefix(path, parent)
  86. }
  87. func CommonPrefix(first, second string) string {
  88. if filepath.IsAbs(first) != filepath.IsAbs(second) {
  89. // Whatever
  90. return ""
  91. }
  92. firstParts := strings.Split(filepath.Clean(first), string(PathSeparator))
  93. secondParts := strings.Split(filepath.Clean(second), string(PathSeparator))
  94. isAbs := filepath.IsAbs(first) && filepath.IsAbs(second)
  95. count := len(firstParts)
  96. if len(secondParts) < len(firstParts) {
  97. count = len(secondParts)
  98. }
  99. common := make([]string, 0, count)
  100. for i := 0; i < count; i++ {
  101. if firstParts[i] != secondParts[i] {
  102. break
  103. }
  104. common = append(common, firstParts[i])
  105. }
  106. if isAbs {
  107. if runtime.GOOS == "windows" && isVolumeNameOnly(common) {
  108. // Because strings.Split strips out path separators, if we're at the volume name, we end up without a separator
  109. // Wedge an empty element to be joined with.
  110. common = append(common, "")
  111. } else if len(common) == 1 {
  112. // If isAbs on non Windows, first element in both first and second is "", hence joining that returns nothing.
  113. return string(PathSeparator)
  114. }
  115. }
  116. // This should only be true on Windows when drive letters are different or when paths are relative.
  117. // In case of UNC paths we should end up with more than a single element hence joining is fine
  118. if len(common) == 0 {
  119. return ""
  120. }
  121. // This has to be strings.Join, because filepath.Join([]string{"", "", "?", "C:", "Audrius"}...) returns garbage
  122. result := strings.Join(common, string(PathSeparator))
  123. return filepath.Clean(result)
  124. }
  125. func isVolumeNameOnly(parts []string) bool {
  126. isNormalVolumeName := len(parts) == 1 && strings.HasSuffix(parts[0], ":")
  127. isUNCVolumeName := len(parts) == 4 && strings.HasSuffix(parts[3], ":")
  128. return isNormalVolumeName || isUNCVolumeName
  129. }