fileutils.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. return nil, nil, false, errors.New("Illegal exclusion pattern: !")
  39. }
  40. exceptions = true
  41. }
  42. pattern = filepath.Clean(pattern)
  43. cleanedPatterns = append(cleanedPatterns, pattern)
  44. if Exclusion(pattern) {
  45. pattern = pattern[1:]
  46. }
  47. patternDirs = append(patternDirs, strings.Split(pattern, "/"))
  48. }
  49. return cleanedPatterns, patternDirs, exceptions, nil
  50. }
  51. // Matches returns true if file matches any of the patterns
  52. // and isn't excluded by any of the subsequent patterns.
  53. func Matches(file string, patterns []string) (bool, error) {
  54. file = filepath.Clean(file)
  55. if file == "." {
  56. // Don't let them exclude everything, kind of silly.
  57. return false, nil
  58. }
  59. patterns, patDirs, _, err := CleanPatterns(patterns)
  60. if err != nil {
  61. return false, err
  62. }
  63. return OptimizedMatches(file, patterns, patDirs)
  64. }
  65. // Matches is basically the same as fileutils.Matches() but optimized for archive.go.
  66. // It will assume that the inputs have been preprocessed and therefore the function
  67. // doen't need to do as much error checking and clean-up. This was done to avoid
  68. // repeating these steps on each file being checked during the archive process.
  69. // The more generic fileutils.Matches() can't make these assumptions.
  70. func OptimizedMatches(file string, patterns []string, patDirs [][]string) (bool, error) {
  71. matched := false
  72. parentPath := filepath.Dir(file)
  73. parentPathDirs := strings.Split(parentPath, "/")
  74. for i, pattern := range patterns {
  75. negative := false
  76. if Exclusion(pattern) {
  77. negative = true
  78. pattern = pattern[1:]
  79. }
  80. match, err := filepath.Match(pattern, file)
  81. if err != nil {
  82. return false, err
  83. }
  84. if !match && parentPath != "." {
  85. // Check to see if the pattern matches one of our parent dirs.
  86. if len(patDirs[i]) <= len(parentPathDirs) {
  87. match, _ = filepath.Match(strings.Join(patDirs[i], "/"),
  88. strings.Join(parentPathDirs[:len(patDirs[i])], "/"))
  89. }
  90. }
  91. if match {
  92. matched = !negative
  93. }
  94. }
  95. if matched {
  96. logrus.Debugf("Skipping excluded path: %s", file)
  97. }
  98. return matched, nil
  99. }
  100. func CopyFile(src, dst string) (int64, error) {
  101. cleanSrc := filepath.Clean(src)
  102. cleanDst := filepath.Clean(dst)
  103. if cleanSrc == cleanDst {
  104. return 0, nil
  105. }
  106. sf, err := os.Open(cleanSrc)
  107. if err != nil {
  108. return 0, err
  109. }
  110. defer sf.Close()
  111. if err := os.Remove(cleanDst); err != nil && !os.IsNotExist(err) {
  112. return 0, err
  113. }
  114. df, err := os.Create(cleanDst)
  115. if err != nil {
  116. return 0, err
  117. }
  118. defer df.Close()
  119. return io.Copy(df, sf)
  120. }
  121. func GetTotalUsedFds() int {
  122. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  123. logrus.Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  124. } else {
  125. return len(fds)
  126. }
  127. return -1
  128. }
  129. // ReadSymlinkedDirectory returns the target directory of a symlink.
  130. // The target of the symbolic link may not be a file.
  131. func ReadSymlinkedDirectory(path string) (string, error) {
  132. var realPath string
  133. var err error
  134. if realPath, err = filepath.Abs(path); err != nil {
  135. return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err)
  136. }
  137. if realPath, err = filepath.EvalSymlinks(realPath); err != nil {
  138. return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err)
  139. }
  140. realPathInfo, err := os.Stat(realPath)
  141. if err != nil {
  142. return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err)
  143. }
  144. if !realPathInfo.Mode().IsDir() {
  145. return "", fmt.Errorf("canonical path points to a file '%s'", realPath)
  146. }
  147. return realPath, nil
  148. }