ignore.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. package ignore
  16. import (
  17. "bufio"
  18. "fmt"
  19. "io"
  20. "os"
  21. "path/filepath"
  22. "regexp"
  23. "strings"
  24. "sync"
  25. "github.com/syncthing/syncthing/internal/fnmatch"
  26. )
  27. type Pattern struct {
  28. match *regexp.Regexp
  29. include bool
  30. }
  31. type Matcher struct {
  32. patterns []Pattern
  33. matches *cache
  34. mut sync.Mutex
  35. }
  36. func Load(file string, cache bool) (*Matcher, error) {
  37. seen := make(map[string]bool)
  38. matcher, err := loadIgnoreFile(file, seen)
  39. if !cache || err != nil {
  40. return matcher, err
  41. }
  42. cacheMut.Lock()
  43. defer cacheMut.Unlock()
  44. // Get the current cache object for the given file
  45. cached, ok := caches[file]
  46. if !ok || !patternsEqual(cached.patterns, matcher.patterns) {
  47. // Nothing in cache or a cache mismatch, create a new cache which will
  48. // store matches for the given set of patterns.
  49. // Initialize oldMatches to indicate that we are interested in
  50. // caching.
  51. cached = newCache(matcher.patterns)
  52. matcher.matches = cached
  53. caches[file] = cached
  54. return matcher, nil
  55. }
  56. // Patterns haven't changed, so we can reuse the old matches, create a new
  57. // matches map and update the pointer. (This prevents matches map from
  58. // growing indefinately, as we only cache whatever we've matched in the last
  59. // iteration, rather than through runtime history)
  60. matcher.matches = cached
  61. return matcher, nil
  62. }
  63. func Parse(r io.Reader, file string) (*Matcher, error) {
  64. seen := map[string]bool{
  65. file: true,
  66. }
  67. return parseIgnoreFile(r, file, seen)
  68. }
  69. func (m *Matcher) Match(file string) (result bool) {
  70. if len(m.patterns) == 0 {
  71. return false
  72. }
  73. if m.matches != nil {
  74. // Check the cache for a known result.
  75. res, ok := m.matches.get(file)
  76. if ok {
  77. return res
  78. }
  79. // Update the cache with the result at return time
  80. defer func() {
  81. m.matches.set(file, result)
  82. }()
  83. }
  84. // Check all the patterns for a match.
  85. for _, pattern := range m.patterns {
  86. if pattern.match.MatchString(file) {
  87. return pattern.include
  88. }
  89. }
  90. // Default to false.
  91. return false
  92. }
  93. // Patterns return a list of the loaded regexp patterns, as strings
  94. func (m *Matcher) Patterns() []string {
  95. patterns := make([]string, len(m.patterns))
  96. for i, pat := range m.patterns {
  97. if pat.include {
  98. patterns[i] = pat.match.String()
  99. } else {
  100. patterns[i] = "(?exclude)" + pat.match.String()
  101. }
  102. }
  103. return patterns
  104. }
  105. func loadIgnoreFile(file string, seen map[string]bool) (*Matcher, error) {
  106. if seen[file] {
  107. return nil, fmt.Errorf("Multiple include of ignore file %q", file)
  108. }
  109. seen[file] = true
  110. fd, err := os.Open(file)
  111. if err != nil {
  112. return nil, err
  113. }
  114. defer fd.Close()
  115. return parseIgnoreFile(fd, file, seen)
  116. }
  117. func parseIgnoreFile(fd io.Reader, currentFile string, seen map[string]bool) (*Matcher, error) {
  118. var exps Matcher
  119. addPattern := func(line string) error {
  120. include := true
  121. if strings.HasPrefix(line, "!") {
  122. line = line[1:]
  123. include = false
  124. }
  125. if strings.HasPrefix(line, "/") {
  126. // Pattern is rooted in the current dir only
  127. exp, err := fnmatch.Convert(line[1:], fnmatch.FNM_PATHNAME)
  128. if err != nil {
  129. return fmt.Errorf("Invalid pattern %q in ignore file", line)
  130. }
  131. exps.patterns = append(exps.patterns, Pattern{exp, include})
  132. } else if strings.HasPrefix(line, "**/") {
  133. // Add the pattern as is, and without **/ so it matches in current dir
  134. exp, err := fnmatch.Convert(line, fnmatch.FNM_PATHNAME)
  135. if err != nil {
  136. return fmt.Errorf("Invalid pattern %q in ignore file", line)
  137. }
  138. exps.patterns = append(exps.patterns, Pattern{exp, include})
  139. exp, err = fnmatch.Convert(line[3:], fnmatch.FNM_PATHNAME)
  140. if err != nil {
  141. return fmt.Errorf("Invalid pattern %q in ignore file", line)
  142. }
  143. exps.patterns = append(exps.patterns, Pattern{exp, include})
  144. } else if strings.HasPrefix(line, "#include ") {
  145. includeFile := filepath.Join(filepath.Dir(currentFile), line[len("#include "):])
  146. includes, err := loadIgnoreFile(includeFile, seen)
  147. if err != nil {
  148. return err
  149. }
  150. exps.patterns = append(exps.patterns, includes.patterns...)
  151. } else {
  152. // Path name or pattern, add it so it matches files both in
  153. // current directory and subdirs.
  154. exp, err := fnmatch.Convert(line, fnmatch.FNM_PATHNAME)
  155. if err != nil {
  156. return fmt.Errorf("Invalid pattern %q in ignore file", line)
  157. }
  158. exps.patterns = append(exps.patterns, Pattern{exp, include})
  159. exp, err = fnmatch.Convert("**/"+line, fnmatch.FNM_PATHNAME)
  160. if err != nil {
  161. return fmt.Errorf("Invalid pattern %q in ignore file", line)
  162. }
  163. exps.patterns = append(exps.patterns, Pattern{exp, include})
  164. }
  165. return nil
  166. }
  167. scanner := bufio.NewScanner(fd)
  168. var err error
  169. for scanner.Scan() {
  170. line := strings.TrimSpace(scanner.Text())
  171. switch {
  172. case line == "":
  173. continue
  174. case strings.HasPrefix(line, "//"):
  175. continue
  176. case strings.HasPrefix(line, "#"):
  177. err = addPattern(line)
  178. case strings.HasSuffix(line, "/**"):
  179. err = addPattern(line)
  180. case strings.HasSuffix(line, "/"):
  181. err = addPattern(line)
  182. if err == nil {
  183. err = addPattern(line + "**")
  184. }
  185. default:
  186. err = addPattern(line)
  187. if err == nil {
  188. err = addPattern(line + "/**")
  189. }
  190. }
  191. if err != nil {
  192. return nil, err
  193. }
  194. }
  195. return &exps, nil
  196. }
  197. func patternsEqual(a, b []Pattern) bool {
  198. if len(a) != len(b) {
  199. return false
  200. }
  201. for i := range a {
  202. if a[i].include != b[i].include || a[i].match.String() != b[i].match.String() {
  203. return false
  204. }
  205. }
  206. return true
  207. }