fileutils.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. package fileutils
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "github.com/Sirupsen/logrus"
  10. )
  11. // exclusion return true if the specified pattern is an exclusion
  12. func exclusion(pattern string) bool {
  13. return pattern[0] == '!'
  14. }
  15. // empty return true if the specified pattern is empty
  16. func empty(pattern string) bool {
  17. return pattern == ""
  18. }
  19. // CleanPatterns takes a slice of patterns returns a new
  20. // slice of patterns cleaned with filepath.Clean, stripped
  21. // of any empty patterns and lets the caller know whether the
  22. // slice contains any exception patterns (prefixed with !).
  23. func CleanPatterns(patterns []string) ([]string, [][]string, bool, error) {
  24. // Loop over exclusion patterns and:
  25. // 1. Clean them up.
  26. // 2. Indicate whether we are dealing with any exception rules.
  27. // 3. Error if we see a single exclusion marker on it's own (!).
  28. cleanedPatterns := []string{}
  29. patternDirs := [][]string{}
  30. exceptions := false
  31. for _, pattern := range patterns {
  32. // Eliminate leading and trailing whitespace.
  33. pattern = strings.TrimSpace(pattern)
  34. if empty(pattern) {
  35. continue
  36. }
  37. if exclusion(pattern) {
  38. if len(pattern) == 1 {
  39. return nil, nil, false, errors.New("Illegal exclusion pattern: !")
  40. }
  41. exceptions = true
  42. }
  43. pattern = filepath.Clean(pattern)
  44. cleanedPatterns = append(cleanedPatterns, pattern)
  45. if exclusion(pattern) {
  46. pattern = pattern[1:]
  47. }
  48. patternDirs = append(patternDirs, strings.Split(pattern, "/"))
  49. }
  50. return cleanedPatterns, patternDirs, exceptions, nil
  51. }
  52. // Matches returns true if file matches any of the patterns
  53. // and isn't excluded by any of the subsequent patterns.
  54. func Matches(file string, patterns []string) (bool, error) {
  55. file = filepath.Clean(file)
  56. if file == "." {
  57. // Don't let them exclude everything, kind of silly.
  58. return false, nil
  59. }
  60. patterns, patDirs, _, err := CleanPatterns(patterns)
  61. if err != nil {
  62. return false, err
  63. }
  64. return OptimizedMatches(file, patterns, patDirs)
  65. }
  66. // OptimizedMatches is basically the same as fileutils.Matches() but optimized for archive.go.
  67. // It will assume that the inputs have been preprocessed and therefore the function
  68. // doen't need to do as much error checking and clean-up. This was done to avoid
  69. // repeating these steps on each file being checked during the archive process.
  70. // The more generic fileutils.Matches() can't make these assumptions.
  71. func OptimizedMatches(file string, patterns []string, patDirs [][]string) (bool, error) {
  72. matched := false
  73. parentPath := filepath.Dir(file)
  74. parentPathDirs := strings.Split(parentPath, "/")
  75. for i, pattern := range patterns {
  76. negative := false
  77. if exclusion(pattern) {
  78. negative = true
  79. pattern = pattern[1:]
  80. }
  81. match, err := filepath.Match(pattern, file)
  82. if err != nil {
  83. return false, err
  84. }
  85. if !match && parentPath != "." {
  86. // Check to see if the pattern matches one of our parent dirs.
  87. if len(patDirs[i]) <= len(parentPathDirs) {
  88. match, _ = filepath.Match(strings.Join(patDirs[i], "/"),
  89. strings.Join(parentPathDirs[:len(patDirs[i])], "/"))
  90. }
  91. }
  92. if match {
  93. matched = !negative
  94. }
  95. }
  96. if matched {
  97. logrus.Debugf("Skipping excluded path: %s", file)
  98. }
  99. return matched, nil
  100. }
  101. // CopyFile copies from src to dst until either EOF is reached
  102. // on src or an error occurs. It verifies src exists and remove
  103. // the dst if it exists.
  104. func CopyFile(src, dst string) (int64, error) {
  105. cleanSrc := filepath.Clean(src)
  106. cleanDst := filepath.Clean(dst)
  107. if cleanSrc == cleanDst {
  108. return 0, nil
  109. }
  110. sf, err := os.Open(cleanSrc)
  111. if err != nil {
  112. return 0, err
  113. }
  114. defer sf.Close()
  115. if err := os.Remove(cleanDst); err != nil && !os.IsNotExist(err) {
  116. return 0, err
  117. }
  118. df, err := os.Create(cleanDst)
  119. if err != nil {
  120. return 0, err
  121. }
  122. defer df.Close()
  123. return io.Copy(df, sf)
  124. }
  125. // ReadSymlinkedDirectory returns the target directory of a symlink.
  126. // The target of the symbolic link may not be a file.
  127. func ReadSymlinkedDirectory(path string) (string, error) {
  128. var realPath string
  129. var err error
  130. if realPath, err = filepath.Abs(path); err != nil {
  131. return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err)
  132. }
  133. if realPath, err = filepath.EvalSymlinks(realPath); err != nil {
  134. return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err)
  135. }
  136. realPathInfo, err := os.Stat(realPath)
  137. if err != nil {
  138. return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err)
  139. }
  140. if !realPathInfo.Mode().IsDir() {
  141. return "", fmt.Errorf("canonical path points to a file '%s'", realPath)
  142. }
  143. return realPath, nil
  144. }
  145. // CreateIfNotExists creates a file or a directory only if it does not already exist.
  146. func CreateIfNotExists(path string, isDir bool) error {
  147. if _, err := os.Stat(path); err != nil {
  148. if os.IsNotExist(err) {
  149. if isDir {
  150. return os.MkdirAll(path, 0755)
  151. }
  152. if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
  153. return err
  154. }
  155. f, err := os.OpenFile(path, os.O_CREATE, 0755)
  156. if err != nil {
  157. return err
  158. }
  159. f.Close()
  160. }
  161. }
  162. return nil
  163. }