fileutils.go 5.3 KB

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