ignore.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. # Copyright (C) 2017 Jelmer Vernooij <jelmer@jelmer.uk>
  2. #
  3. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  4. # General Public License as public by the Free Software Foundation; version 2.0
  5. # or (at your option) any later version. You can redistribute it and/or
  6. # modify it under the terms of either of these two licenses.
  7. #
  8. # Unless required by applicable law or agreed to in writing, software
  9. # distributed under the License is distributed on an "AS IS" BASIS,
  10. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. # See the License for the specific language governing permissions and
  12. # limitations under the License.
  13. #
  14. # You should have received a copy of the licenses; if not, see
  15. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  16. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  17. # License, Version 2.0.
  18. #
  19. """Parsing of gitignore files.
  20. For details for the matching rules, see https://git-scm.com/docs/gitignore
  21. """
  22. import os.path
  23. import re
  24. import sys
  25. def _translate_segment(segment):
  26. if segment == b"*":
  27. return b'[^/]+'
  28. res = b""
  29. i, n = 0, len(segment)
  30. while i < n:
  31. c = segment[i:i+1]
  32. i = i+1
  33. if c == b'*':
  34. res += b'[^/]*'
  35. elif c == b'?':
  36. res += b'.'
  37. elif c == b'[':
  38. j = i
  39. if j < n and segment[j:j+1] == b'!':
  40. j = j+1
  41. if j < n and segment[j:j+1] == b']':
  42. j = j+1
  43. while j < n and segment[j:j+1] != b']':
  44. j = j+1
  45. if j >= n:
  46. res += b'\\['
  47. else:
  48. stuff = segment[i:j].replace(b'\\', b'\\\\')
  49. i = j+1
  50. if stuff.startswith(b'!'):
  51. stuff = b'^' + stuff[1:]
  52. elif stuff.startswith(b'^'):
  53. stuff = b'\\' + stuff
  54. res += b'[' + stuff + b']'
  55. else:
  56. res += re.escape(c)
  57. return res
  58. def translate(pat):
  59. """Translate a shell PATTERN to a regular expression.
  60. There is no way to quote meta-characters.
  61. Originally copied from fnmatch in Python 2.7, but modified for Dulwich
  62. to cope with features in Git ignore patterns.
  63. """
  64. res = b'(?ms)'
  65. if b'/' not in pat[:-1]:
  66. # If there's no slash, this is a filename-based match
  67. res += b'(.*/)?'
  68. if pat.startswith(b'**/'):
  69. # Leading **/
  70. pat = pat[2:]
  71. res += b'(.*/)?'
  72. if pat.startswith(b'/'):
  73. pat = pat[1:]
  74. for i, segment in enumerate(pat.split(b'/')):
  75. if segment == b'**':
  76. res += b'(/.*)?'
  77. continue
  78. else:
  79. res += ((re.escape(b'/') if i > 0 else b'') +
  80. _translate_segment(segment))
  81. if not pat.endswith(b'/'):
  82. res += b'/?'
  83. return res + b'\\Z'
  84. def read_ignore_patterns(f):
  85. """Read a git ignore file.
  86. :param f: File-like object to read from
  87. :return: List of patterns
  88. """
  89. for line in f:
  90. line = line.rstrip(b"\r\n")
  91. # Ignore blank lines, they're used for readability.
  92. if not line:
  93. continue
  94. if line.startswith(b'#'):
  95. # Comment
  96. continue
  97. # Trailing spaces are ignored unless they are quoted with a backslash.
  98. while line.endswith(b' ') and not line.endswith(b'\\ '):
  99. line = line[:-1]
  100. line = line.replace(b'\\ ', b' ')
  101. yield line
  102. def match_pattern(path, pattern, ignorecase=False):
  103. """Match a gitignore-style pattern against a path.
  104. :param path: Path to match
  105. :param pattern: Pattern to match
  106. :param ignorecase: Whether to do case-sensitive matching
  107. :return: bool indicating whether the pattern matched
  108. """
  109. return Pattern(pattern, ignorecase).match(path)
  110. class Pattern(object):
  111. """A single ignore pattern."""
  112. def __init__(self, pattern, ignorecase=False):
  113. self.pattern = pattern
  114. self.ignorecase = ignorecase
  115. if pattern[0:1] == b'!':
  116. self.is_exclude = False
  117. pattern = pattern[1:]
  118. else:
  119. if pattern[0:1] == b'\\':
  120. pattern = pattern[1:]
  121. self.is_exclude = True
  122. flags = 0
  123. if self.ignorecase:
  124. flags = re.IGNORECASE
  125. self._re = re.compile(translate(pattern), flags)
  126. def __bytes__(self):
  127. return self.pattern
  128. def __str__(self):
  129. return self.pattern.decode(sys.getfilesystemencoding())
  130. def __eq__(self, other):
  131. return (type(self) == type(other) and
  132. self.pattern == other.pattern and
  133. self.ignorecase == other.ignorecase)
  134. def __repr__(self):
  135. return "%s(%s, %r)" % (
  136. type(self).__name__, self.pattern, self.ignorecase)
  137. def match(self, path):
  138. """Try to match a path against this ignore pattern.
  139. :param path: Path to match (relative to ignore location)
  140. :return: boolean
  141. """
  142. return bool(self._re.match(path))
  143. class IgnoreFilter(object):
  144. def __init__(self, patterns, ignorecase=False):
  145. self._patterns = []
  146. self._ignorecase = ignorecase
  147. for pattern in patterns:
  148. self.append_pattern(pattern)
  149. def append_pattern(self, pattern):
  150. """Add a pattern to the set."""
  151. self._patterns.append(Pattern(pattern, self._ignorecase))
  152. def find_matching(self, path):
  153. """Yield all matching patterns for path.
  154. :param path: Path to match
  155. :return: Iterator over iterators
  156. """
  157. if not isinstance(path, bytes):
  158. path = path.encode(sys.getfilesystemencoding())
  159. for pattern in self._patterns:
  160. if pattern.match(path):
  161. yield pattern
  162. def is_ignored(self, path):
  163. """Check whether a path is ignored.
  164. For directories, include a trailing slash.
  165. :return: status is None if file is not mentioned, True if it is
  166. included, False if it is explicitly excluded.
  167. """
  168. status = None
  169. for pattern in self.find_matching(path):
  170. status = pattern.is_exclude
  171. return status
  172. @classmethod
  173. def from_path(cls, path, ignorecase=False):
  174. with open(path, 'rb') as f:
  175. ret = cls(read_ignore_patterns(f), ignorecase)
  176. ret._path = path
  177. return ret
  178. def __repr__(self):
  179. if getattr(self, '_path', None) is None:
  180. return "<%s>" % (type(self).__name__)
  181. else:
  182. return "%s.from_path(%r)" % (type(self).__name__, self._path)
  183. class IgnoreFilterStack(object):
  184. """Check for ignore status in multiple filters."""
  185. def __init__(self, filters):
  186. self._filters = filters
  187. def is_ignored(self, path):
  188. """Check whether a path is explicitly included or excluded in ignores.
  189. :param path: Path to check
  190. :return: None if the file is not mentioned, True if it is included,
  191. False if it is explicitly excluded.
  192. """
  193. status = None
  194. for filter in self._filters:
  195. status = filter.is_ignored(path)
  196. if status is not None:
  197. return status
  198. return status
  199. def default_user_ignore_filter_path(config):
  200. """Return default user ignore filter path.
  201. :param config: A Config object
  202. :return: Path to a global ignore file
  203. """
  204. try:
  205. return config.get((b'core', ), b'excludesFile')
  206. except KeyError:
  207. pass
  208. xdg_config_home = os.environ.get(
  209. "XDG_CONFIG_HOME", os.path.expanduser("~/.config/"),
  210. )
  211. return os.path.join(xdg_config_home, 'git', 'ignore')
  212. class IgnoreFilterManager(object):
  213. """Ignore file manager."""
  214. def __init__(self, top_path, global_filters, ignorecase):
  215. self._path_filters = {}
  216. self._top_path = top_path
  217. self._global_filters = global_filters
  218. self._ignorecase = ignorecase
  219. def __repr__(self):
  220. return "%s(%s, %r, %r)" % (
  221. type(self).__name__, self._top_path,
  222. self._global_filters,
  223. self._ignorecase)
  224. def _load_path(self, path):
  225. try:
  226. return self._path_filters[path]
  227. except KeyError:
  228. pass
  229. p = os.path.join(self._top_path, path, '.gitignore')
  230. try:
  231. self._path_filters[path] = IgnoreFilter.from_path(
  232. p, self._ignorecase)
  233. except IOError:
  234. self._path_filters[path] = None
  235. return self._path_filters[path]
  236. def find_matching(self, path):
  237. """Find matching patterns for path.
  238. Stops after the first ignore file with matches.
  239. :param path: Path to check
  240. :return: Iterator over Pattern instances
  241. """
  242. if os.path.isabs(path):
  243. raise ValueError('%s is an absolute path' % path)
  244. filters = [(0, f) for f in self._global_filters]
  245. if os.path.sep != '/':
  246. path = path.replace(os.path.sep, '/')
  247. parts = path.split('/')
  248. for i in range(len(parts)+1):
  249. dirname = '/'.join(parts[:i])
  250. for s, f in filters:
  251. relpath = '/'.join(parts[s:i])
  252. if i < len(parts):
  253. # Paths leading up to the final part are all directories,
  254. # so need a trailing slash.
  255. relpath += '/'
  256. matches = list(f.find_matching(relpath))
  257. if matches:
  258. return iter(matches)
  259. ignore_filter = self._load_path(dirname)
  260. if ignore_filter is not None:
  261. filters.insert(0, (i, ignore_filter))
  262. return iter([])
  263. def is_ignored(self, path):
  264. """Check whether a path is explicitly included or excluded in ignores.
  265. :param path: Path to check
  266. :return: None if the file is not mentioned, True if it is included,
  267. False if it is explicitly excluded.
  268. """
  269. matches = list(self.find_matching(path))
  270. if matches:
  271. return matches[-1].is_exclude
  272. return None
  273. @classmethod
  274. def from_repo(cls, repo):
  275. """Create a IgnoreFilterManager from a repository.
  276. :param repo: Repository object
  277. :return: A `IgnoreFilterManager` object
  278. """
  279. global_filters = []
  280. for p in [
  281. os.path.join(repo.controldir(), 'info', 'exclude'),
  282. default_user_ignore_filter_path(repo.get_config_stack())]:
  283. try:
  284. global_filters.append(IgnoreFilter.from_path(p))
  285. except IOError:
  286. pass
  287. config = repo.get_config_stack()
  288. ignorecase = config.get_boolean((b'core'), (b'ignorecase'), False)
  289. return cls(repo.path, global_filters, ignorecase)