fileutils.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. package fileutils
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "github.com/Sirupsen/logrus"
  11. )
  12. func Exclusion(pattern string) bool {
  13. return pattern[0] == '!'
  14. }
  15. func Empty(pattern string) bool {
  16. return pattern == ""
  17. }
  18. // Cleanpatterns takes a slice of patterns returns a new
  19. // slice of patterns cleaned with filepath.Clean, stripped
  20. // of any empty patterns and lets the caller know whether the
  21. // slice contains any exception patterns (prefixed with !).
  22. func CleanPatterns(patterns []string) ([]string, [][]string, bool, error) {
  23. // Loop over exclusion patterns and:
  24. // 1. Clean them up.
  25. // 2. Indicate whether we are dealing with any exception rules.
  26. // 3. Error if we see a single exclusion marker on it's own (!).
  27. cleanedPatterns := []string{}
  28. patternDirs := [][]string{}
  29. exceptions := false
  30. for _, pattern := range patterns {
  31. // Eliminate leading and trailing whitespace.
  32. pattern = strings.TrimSpace(pattern)
  33. if Empty(pattern) {
  34. continue
  35. }
  36. if Exclusion(pattern) {
  37. if len(pattern) == 1 {
  38. logrus.Errorf("Illegal exclusion pattern: %s", pattern)
  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. // Matches 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. logrus.Errorf("Error matching: %s (pattern: %s)", file, pattern)
  84. return false, err
  85. }
  86. if !match && parentPath != "." {
  87. // Check to see if the pattern matches one of our parent dirs.
  88. if len(patDirs[i]) <= len(parentPathDirs) {
  89. match, _ = filepath.Match(strings.Join(patDirs[i], "/"),
  90. strings.Join(parentPathDirs[:len(patDirs[i])], "/"))
  91. }
  92. }
  93. if match {
  94. matched = !negative
  95. }
  96. }
  97. if matched {
  98. logrus.Debugf("Skipping excluded path: %s", file)
  99. }
  100. return matched, nil
  101. }
  102. func CopyFile(src, dst string) (int64, error) {
  103. cleanSrc := filepath.Clean(src)
  104. cleanDst := filepath.Clean(dst)
  105. if cleanSrc == cleanDst {
  106. return 0, nil
  107. }
  108. sf, err := os.Open(cleanSrc)
  109. if err != nil {
  110. return 0, err
  111. }
  112. defer sf.Close()
  113. if err := os.Remove(cleanDst); err != nil && !os.IsNotExist(err) {
  114. return 0, err
  115. }
  116. df, err := os.Create(cleanDst)
  117. if err != nil {
  118. return 0, err
  119. }
  120. defer df.Close()
  121. return io.Copy(df, sf)
  122. }
  123. func GetTotalUsedFds() int {
  124. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  125. logrus.Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  126. } else {
  127. return len(fds)
  128. }
  129. return -1
  130. }
  131. // ReadSymlinkedDirectory returns the target directory of a symlink.
  132. // The target of the symbolic link may not be a file.
  133. func ReadSymlinkedDirectory(path string) (string, error) {
  134. var realPath string
  135. var err error
  136. if realPath, err = filepath.Abs(path); err != nil {
  137. return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err)
  138. }
  139. if realPath, err = filepath.EvalSymlinks(realPath); err != nil {
  140. return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err)
  141. }
  142. realPathInfo, err := os.Stat(realPath)
  143. if err != nil {
  144. return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err)
  145. }
  146. if !realPathInfo.Mode().IsDir() {
  147. return "", fmt.Errorf("canonical path points to a file '%s'", realPath)
  148. }
  149. return realPath, nil
  150. }