fileutils.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package fileutils // import "github.com/docker/docker/pkg/fileutils"
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "os"
  7. "path/filepath"
  8. "regexp"
  9. "strings"
  10. "text/scanner"
  11. )
  12. // PatternMatcher allows checking paths against a list of patterns
  13. type PatternMatcher struct {
  14. patterns []*Pattern
  15. exclusions bool
  16. }
  17. // NewPatternMatcher creates a new matcher object for specific patterns that can
  18. // be used later to match against patterns against paths
  19. func NewPatternMatcher(patterns []string) (*PatternMatcher, error) {
  20. pm := &PatternMatcher{
  21. patterns: make([]*Pattern, 0, len(patterns)),
  22. }
  23. for _, p := range patterns {
  24. // Eliminate leading and trailing whitespace.
  25. p = strings.TrimSpace(p)
  26. if p == "" {
  27. continue
  28. }
  29. p = filepath.Clean(p)
  30. newp := &Pattern{}
  31. if p[0] == '!' {
  32. if len(p) == 1 {
  33. return nil, errors.New("illegal exclusion pattern: \"!\"")
  34. }
  35. newp.exclusion = true
  36. p = p[1:]
  37. pm.exclusions = true
  38. }
  39. // Do some syntax checking on the pattern.
  40. // filepath's Match() has some really weird rules that are inconsistent
  41. // so instead of trying to dup their logic, just call Match() for its
  42. // error state and if there is an error in the pattern return it.
  43. // If this becomes an issue we can remove this since its really only
  44. // needed in the error (syntax) case - which isn't really critical.
  45. if _, err := filepath.Match(p, "."); err != nil {
  46. return nil, err
  47. }
  48. newp.cleanedPattern = p
  49. newp.dirs = strings.Split(p, string(os.PathSeparator))
  50. pm.patterns = append(pm.patterns, newp)
  51. }
  52. return pm, nil
  53. }
  54. // Matches matches path against all the patterns. Matches is not safe to be
  55. // called concurrently
  56. func (pm *PatternMatcher) Matches(file string) (bool, error) {
  57. matched := false
  58. file = filepath.FromSlash(file)
  59. parentPath := filepath.Dir(file)
  60. parentPathDirs := strings.Split(parentPath, string(os.PathSeparator))
  61. for _, pattern := range pm.patterns {
  62. negative := false
  63. if pattern.exclusion {
  64. negative = true
  65. }
  66. match, err := pattern.match(file)
  67. if err != nil {
  68. return false, err
  69. }
  70. if !match && parentPath != "." {
  71. // Check to see if the pattern matches one of our parent dirs.
  72. if len(pattern.dirs) <= len(parentPathDirs) {
  73. match, _ = pattern.match(strings.Join(parentPathDirs[:len(pattern.dirs)], string(os.PathSeparator)))
  74. }
  75. }
  76. if match {
  77. matched = !negative
  78. }
  79. }
  80. return matched, nil
  81. }
  82. // Exclusions returns true if any of the patterns define exclusions
  83. func (pm *PatternMatcher) Exclusions() bool {
  84. return pm.exclusions
  85. }
  86. // Patterns returns array of active patterns
  87. func (pm *PatternMatcher) Patterns() []*Pattern {
  88. return pm.patterns
  89. }
  90. // Pattern defines a single regexp used to filter file paths.
  91. type Pattern struct {
  92. cleanedPattern string
  93. dirs []string
  94. regexp *regexp.Regexp
  95. exclusion bool
  96. }
  97. func (p *Pattern) String() string {
  98. return p.cleanedPattern
  99. }
  100. // Exclusion returns true if this pattern defines exclusion
  101. func (p *Pattern) Exclusion() bool {
  102. return p.exclusion
  103. }
  104. func (p *Pattern) match(path string) (bool, error) {
  105. if p.regexp == nil {
  106. if err := p.compile(); err != nil {
  107. return false, filepath.ErrBadPattern
  108. }
  109. }
  110. b := p.regexp.MatchString(path)
  111. return b, nil
  112. }
  113. func (p *Pattern) compile() error {
  114. regStr := "^"
  115. pattern := p.cleanedPattern
  116. // Go through the pattern and convert it to a regexp.
  117. // We use a scanner so we can support utf-8 chars.
  118. var scan scanner.Scanner
  119. scan.Init(strings.NewReader(pattern))
  120. sl := string(os.PathSeparator)
  121. escSL := sl
  122. if sl == `\` {
  123. escSL += `\`
  124. }
  125. for scan.Peek() != scanner.EOF {
  126. ch := scan.Next()
  127. if ch == '*' {
  128. if scan.Peek() == '*' {
  129. // is some flavor of "**"
  130. scan.Next()
  131. // Treat **/ as ** so eat the "/"
  132. if string(scan.Peek()) == sl {
  133. scan.Next()
  134. }
  135. if scan.Peek() == scanner.EOF {
  136. // is "**EOF" - to align with .gitignore just accept all
  137. regStr += ".*"
  138. } else {
  139. // is "**"
  140. // Note that this allows for any # of /'s (even 0) because
  141. // the .* will eat everything, even /'s
  142. regStr += "(.*" + escSL + ")?"
  143. }
  144. } else {
  145. // is "*" so map it to anything but "/"
  146. regStr += "[^" + escSL + "]*"
  147. }
  148. } else if ch == '?' {
  149. // "?" is any char except "/"
  150. regStr += "[^" + escSL + "]"
  151. } else if ch == '.' || ch == '$' {
  152. // Escape some regexp special chars that have no meaning
  153. // in golang's filepath.Match
  154. regStr += `\` + string(ch)
  155. } else if ch == '\\' {
  156. // escape next char. Note that a trailing \ in the pattern
  157. // will be left alone (but need to escape it)
  158. if sl == `\` {
  159. // On windows map "\" to "\\", meaning an escaped backslash,
  160. // and then just continue because filepath.Match on
  161. // Windows doesn't allow escaping at all
  162. regStr += escSL
  163. continue
  164. }
  165. if scan.Peek() != scanner.EOF {
  166. regStr += `\` + string(scan.Next())
  167. } else {
  168. regStr += `\`
  169. }
  170. } else {
  171. regStr += string(ch)
  172. }
  173. }
  174. regStr += "$"
  175. re, err := regexp.Compile(regStr)
  176. if err != nil {
  177. return err
  178. }
  179. p.regexp = re
  180. return nil
  181. }
  182. // Matches returns true if file matches any of the patterns
  183. // and isn't excluded by any of the subsequent patterns.
  184. func Matches(file string, patterns []string) (bool, error) {
  185. pm, err := NewPatternMatcher(patterns)
  186. if err != nil {
  187. return false, err
  188. }
  189. file = filepath.Clean(file)
  190. if file == "." {
  191. // Don't let them exclude everything, kind of silly.
  192. return false, nil
  193. }
  194. return pm.Matches(file)
  195. }
  196. // CopyFile copies from src to dst until either EOF is reached
  197. // on src or an error occurs. It verifies src exists and removes
  198. // the dst if it exists.
  199. func CopyFile(src, dst string) (int64, error) {
  200. cleanSrc := filepath.Clean(src)
  201. cleanDst := filepath.Clean(dst)
  202. if cleanSrc == cleanDst {
  203. return 0, nil
  204. }
  205. sf, err := os.Open(cleanSrc)
  206. if err != nil {
  207. return 0, err
  208. }
  209. defer sf.Close()
  210. if err := os.Remove(cleanDst); err != nil && !os.IsNotExist(err) {
  211. return 0, err
  212. }
  213. df, err := os.Create(cleanDst)
  214. if err != nil {
  215. return 0, err
  216. }
  217. defer df.Close()
  218. return io.Copy(df, sf)
  219. }
  220. // ReadSymlinkedDirectory returns the target directory of a symlink.
  221. // The target of the symbolic link may not be a file.
  222. func ReadSymlinkedDirectory(path string) (string, error) {
  223. var realPath string
  224. var err error
  225. if realPath, err = filepath.Abs(path); err != nil {
  226. return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err)
  227. }
  228. if realPath, err = filepath.EvalSymlinks(realPath); err != nil {
  229. return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err)
  230. }
  231. realPathInfo, err := os.Stat(realPath)
  232. if err != nil {
  233. return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err)
  234. }
  235. if !realPathInfo.Mode().IsDir() {
  236. return "", fmt.Errorf("canonical path points to a file '%s'", realPath)
  237. }
  238. return realPath, nil
  239. }
  240. // CreateIfNotExists creates a file or a directory only if it does not already exist.
  241. func CreateIfNotExists(path string, isDir bool) error {
  242. if _, err := os.Stat(path); err != nil {
  243. if os.IsNotExist(err) {
  244. if isDir {
  245. return os.MkdirAll(path, 0755)
  246. }
  247. if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
  248. return err
  249. }
  250. f, err := os.OpenFile(path, os.O_CREATE, 0755)
  251. if err != nil {
  252. return err
  253. }
  254. f.Close()
  255. }
  256. }
  257. return nil
  258. }