ignore.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package ignore
  7. import (
  8. "bufio"
  9. "bytes"
  10. "crypto/md5"
  11. "fmt"
  12. "io"
  13. "os"
  14. "path/filepath"
  15. "regexp"
  16. "strings"
  17. "time"
  18. "github.com/syncthing/syncthing/lib/fnmatch"
  19. "github.com/syncthing/syncthing/lib/sync"
  20. )
  21. type Pattern struct {
  22. match *regexp.Regexp
  23. include bool
  24. }
  25. func (p Pattern) String() string {
  26. if p.include {
  27. return p.match.String()
  28. }
  29. return "(?exclude)" + p.match.String()
  30. }
  31. type Matcher struct {
  32. patterns []Pattern
  33. withCache bool
  34. matches *cache
  35. curHash string
  36. stop chan struct{}
  37. mut sync.Mutex
  38. }
  39. func New(withCache bool) *Matcher {
  40. m := &Matcher{
  41. withCache: withCache,
  42. stop: make(chan struct{}),
  43. mut: sync.NewMutex(),
  44. }
  45. if withCache {
  46. go m.clean(2 * time.Hour)
  47. }
  48. return m
  49. }
  50. func (m *Matcher) Load(file string) error {
  51. // No locking, Parse() does the locking
  52. fd, err := os.Open(file)
  53. if err != nil {
  54. // We do a parse with empty patterns to clear out the hash, cache etc.
  55. m.Parse(&bytes.Buffer{}, file)
  56. return err
  57. }
  58. defer fd.Close()
  59. return m.Parse(fd, file)
  60. }
  61. func (m *Matcher) Parse(r io.Reader, file string) error {
  62. m.mut.Lock()
  63. defer m.mut.Unlock()
  64. seen := map[string]bool{file: true}
  65. patterns, err := parseIgnoreFile(r, file, seen)
  66. // Error is saved and returned at the end. We process the patterns
  67. // (possibly blank) anyway.
  68. newHash := hashPatterns(patterns)
  69. if newHash == m.curHash {
  70. // We've already loaded exactly these patterns.
  71. return err
  72. }
  73. m.curHash = newHash
  74. m.patterns = patterns
  75. if m.withCache {
  76. m.matches = newCache(patterns)
  77. }
  78. return err
  79. }
  80. func (m *Matcher) Match(file string) (result bool) {
  81. if m == nil {
  82. return false
  83. }
  84. m.mut.Lock()
  85. defer m.mut.Unlock()
  86. if len(m.patterns) == 0 {
  87. return false
  88. }
  89. if m.matches != nil {
  90. // Check the cache for a known result.
  91. res, ok := m.matches.get(file)
  92. if ok {
  93. return res
  94. }
  95. // Update the cache with the result at return time
  96. defer func() {
  97. m.matches.set(file, result)
  98. }()
  99. }
  100. // Check all the patterns for a match.
  101. for _, pattern := range m.patterns {
  102. if pattern.match.MatchString(file) {
  103. return pattern.include
  104. }
  105. }
  106. // Default to false.
  107. return false
  108. }
  109. // Patterns return a list of the loaded regexp patterns, as strings
  110. func (m *Matcher) Patterns() []string {
  111. if m == nil {
  112. return nil
  113. }
  114. m.mut.Lock()
  115. defer m.mut.Unlock()
  116. patterns := make([]string, len(m.patterns))
  117. for i, pat := range m.patterns {
  118. patterns[i] = pat.String()
  119. }
  120. return patterns
  121. }
  122. func (m *Matcher) Hash() string {
  123. m.mut.Lock()
  124. defer m.mut.Unlock()
  125. return m.curHash
  126. }
  127. func (m *Matcher) Stop() {
  128. close(m.stop)
  129. }
  130. func (m *Matcher) clean(d time.Duration) {
  131. t := time.NewTimer(d / 2)
  132. for {
  133. select {
  134. case <-m.stop:
  135. return
  136. case <-t.C:
  137. m.mut.Lock()
  138. if m.matches != nil {
  139. m.matches.clean(d)
  140. }
  141. t.Reset(d / 2)
  142. m.mut.Unlock()
  143. }
  144. }
  145. }
  146. func hashPatterns(patterns []Pattern) string {
  147. h := md5.New()
  148. for _, pat := range patterns {
  149. h.Write([]byte(pat.String()))
  150. h.Write([]byte("\n"))
  151. }
  152. return fmt.Sprintf("%x", h.Sum(nil))
  153. }
  154. func loadIgnoreFile(file string, seen map[string]bool) ([]Pattern, error) {
  155. if seen[file] {
  156. return nil, fmt.Errorf("Multiple include of ignore file %q", file)
  157. }
  158. seen[file] = true
  159. fd, err := os.Open(file)
  160. if err != nil {
  161. return nil, err
  162. }
  163. defer fd.Close()
  164. return parseIgnoreFile(fd, file, seen)
  165. }
  166. func parseIgnoreFile(fd io.Reader, currentFile string, seen map[string]bool) ([]Pattern, error) {
  167. var patterns []Pattern
  168. addPattern := func(line string) error {
  169. include := true
  170. if strings.HasPrefix(line, "!") {
  171. line = line[1:]
  172. include = false
  173. }
  174. flags := fnmatch.PathName
  175. if strings.HasPrefix(line, "(?i)") {
  176. line = line[4:]
  177. flags |= fnmatch.CaseFold
  178. }
  179. if strings.HasPrefix(line, "/") {
  180. // Pattern is rooted in the current dir only
  181. exp, err := fnmatch.Convert(line[1:], flags)
  182. if err != nil {
  183. return fmt.Errorf("invalid pattern %q in ignore file", line)
  184. }
  185. patterns = append(patterns, Pattern{exp, include})
  186. } else if strings.HasPrefix(line, "**/") {
  187. // Add the pattern as is, and without **/ so it matches in current dir
  188. exp, err := fnmatch.Convert(line, flags)
  189. if err != nil {
  190. return fmt.Errorf("invalid pattern %q in ignore file", line)
  191. }
  192. patterns = append(patterns, Pattern{exp, include})
  193. exp, err = fnmatch.Convert(line[3:], flags)
  194. if err != nil {
  195. return fmt.Errorf("invalid pattern %q in ignore file", line)
  196. }
  197. patterns = append(patterns, Pattern{exp, include})
  198. } else if strings.HasPrefix(line, "#include ") {
  199. includeRel := line[len("#include "):]
  200. includeFile := filepath.Join(filepath.Dir(currentFile), includeRel)
  201. includes, err := loadIgnoreFile(includeFile, seen)
  202. if err != nil {
  203. return fmt.Errorf("include of %q: %v", includeRel, err)
  204. }
  205. patterns = append(patterns, includes...)
  206. } else {
  207. // Path name or pattern, add it so it matches files both in
  208. // current directory and subdirs.
  209. exp, err := fnmatch.Convert(line, flags)
  210. if err != nil {
  211. return fmt.Errorf("invalid pattern %q in ignore file", line)
  212. }
  213. patterns = append(patterns, Pattern{exp, include})
  214. exp, err = fnmatch.Convert("**/"+line, flags)
  215. if err != nil {
  216. return fmt.Errorf("invalid pattern %q in ignore file", line)
  217. }
  218. patterns = append(patterns, Pattern{exp, include})
  219. }
  220. return nil
  221. }
  222. scanner := bufio.NewScanner(fd)
  223. var err error
  224. for scanner.Scan() {
  225. line := strings.TrimSpace(scanner.Text())
  226. switch {
  227. case line == "":
  228. continue
  229. case strings.HasPrefix(line, "//"):
  230. continue
  231. case strings.HasPrefix(line, "#"):
  232. err = addPattern(line)
  233. case strings.HasSuffix(line, "/**"):
  234. err = addPattern(line)
  235. case strings.HasSuffix(line, "/"):
  236. err = addPattern(line)
  237. if err == nil {
  238. err = addPattern(line + "**")
  239. }
  240. default:
  241. err = addPattern(line)
  242. if err == nil {
  243. err = addPattern(line + "/**")
  244. }
  245. }
  246. if err != nil {
  247. return nil, err
  248. }
  249. }
  250. return patterns, nil
  251. }