util.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. "fmt"
  9. "os"
  10. "path/filepath"
  11. "runtime"
  12. "strings"
  13. )
  14. func ExpandTilde(path string) (string, error) {
  15. if path == "~" {
  16. return getHomeDir()
  17. }
  18. path = filepath.FromSlash(path)
  19. if !strings.HasPrefix(path, fmt.Sprintf("~%c", PathSeparator)) {
  20. return path, nil
  21. }
  22. home, err := getHomeDir()
  23. if err != nil {
  24. return "", err
  25. }
  26. return filepath.Join(home, path[2:]), nil
  27. }
  28. func getHomeDir() (string, error) {
  29. if runtime.GOOS == "windows" {
  30. // Legacy -- we prioritize this for historical reasons, whereas
  31. // os.UserHomeDir uses %USERPROFILE% always.
  32. home := filepath.Join(os.Getenv("HomeDrive"), os.Getenv("HomePath"))
  33. if home != "" {
  34. return home, nil
  35. }
  36. }
  37. return os.UserHomeDir()
  38. }
  39. var (
  40. windowsDisallowedCharacters = string([]rune{
  41. '<', '>', ':', '"', '|', '?', '*',
  42. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
  43. 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
  44. 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
  45. 31,
  46. })
  47. windowsDisallowedNames = []string{"CON", "PRN", "AUX", "NUL",
  48. "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
  49. "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
  50. }
  51. )
  52. func WindowsInvalidFilename(name string) error {
  53. // None of the path components should end in space or period, or be a
  54. // reserved name. COM0 and LPT0 are missing from the Microsoft docs,
  55. // but Windows Explorer treats them as invalid too.
  56. // (https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file)
  57. for _, part := range strings.Split(name, `\`) {
  58. if len(part) == 0 {
  59. continue
  60. }
  61. switch part[len(part)-1] {
  62. case ' ', '.':
  63. // Names ending in space or period are not valid.
  64. return errInvalidFilenameWindowsSpacePeriod
  65. }
  66. upperCased := strings.ToUpper(part)
  67. for _, disallowed := range windowsDisallowedNames {
  68. if upperCased == disallowed {
  69. return errInvalidFilenameWindowsReservedName
  70. }
  71. if strings.HasPrefix(upperCased, disallowed+".") {
  72. // nul.txt.jpg is also disallowed
  73. return errInvalidFilenameWindowsReservedName
  74. }
  75. }
  76. }
  77. // The path must not contain any disallowed characters
  78. if strings.ContainsAny(name, windowsDisallowedCharacters) {
  79. return errInvalidFilenameWindowsReservedChar
  80. }
  81. return nil
  82. }
  83. // IsParent compares paths purely lexicographically, meaning it returns false
  84. // if path and parent aren't both absolute or relative.
  85. func IsParent(path, parent string) bool {
  86. if parent == path {
  87. // Twice the same root on windows would not be caught at the end.
  88. return false
  89. }
  90. if filepath.IsAbs(path) != filepath.IsAbs(parent) {
  91. return false
  92. }
  93. if parent == "" || parent == "." {
  94. // The empty string is the parent of everything except the empty
  95. // string and ".". (Avoids panic in the last step.)
  96. return path != "" && path != "."
  97. }
  98. if parent == "/" {
  99. // The root is the parent of everything except itself, which would
  100. // not be caught below.
  101. return path != "/"
  102. }
  103. if parent[len(parent)-1] != PathSeparator {
  104. parent += string(PathSeparator)
  105. }
  106. return strings.HasPrefix(path, parent)
  107. }
  108. func CommonPrefix(first, second string) string {
  109. if filepath.IsAbs(first) != filepath.IsAbs(second) {
  110. // Whatever
  111. return ""
  112. }
  113. firstParts := strings.Split(filepath.Clean(first), string(PathSeparator))
  114. secondParts := strings.Split(filepath.Clean(second), string(PathSeparator))
  115. isAbs := filepath.IsAbs(first) && filepath.IsAbs(second)
  116. count := len(firstParts)
  117. if len(secondParts) < len(firstParts) {
  118. count = len(secondParts)
  119. }
  120. common := make([]string, 0, count)
  121. for i := 0; i < count; i++ {
  122. if firstParts[i] != secondParts[i] {
  123. break
  124. }
  125. common = append(common, firstParts[i])
  126. }
  127. if isAbs {
  128. if runtime.GOOS == "windows" && isVolumeNameOnly(common) {
  129. // Because strings.Split strips out path separators, if we're at the volume name, we end up without a separator
  130. // Wedge an empty element to be joined with.
  131. common = append(common, "")
  132. } else if len(common) == 1 {
  133. // If isAbs on non Windows, first element in both first and second is "", hence joining that returns nothing.
  134. return string(PathSeparator)
  135. }
  136. }
  137. // This should only be true on Windows when drive letters are different or when paths are relative.
  138. // In case of UNC paths we should end up with more than a single element hence joining is fine
  139. if len(common) == 0 {
  140. return ""
  141. }
  142. // This has to be strings.Join, because filepath.Join([]string{"", "", "?", "C:", "Audrius"}...) returns garbage
  143. result := strings.Join(common, string(PathSeparator))
  144. return filepath.Clean(result)
  145. }
  146. func isVolumeNameOnly(parts []string) bool {
  147. isNormalVolumeName := len(parts) == 1 && strings.HasSuffix(parts[0], ":")
  148. isUNCVolumeName := len(parts) == 4 && strings.HasSuffix(parts[3], ":")
  149. return isNormalVolumeName || isUNCVolumeName
  150. }