ignore.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. from contextlib import suppress
  25. from typing import (TYPE_CHECKING, BinaryIO, Dict, Iterable, List, Optional,
  26. Union)
  27. if TYPE_CHECKING:
  28. from .repo import Repo
  29. from .config import Config, get_xdg_config_home_path
  30. def _translate_segment(segment: bytes) -> bytes:
  31. if segment == b"*":
  32. return b"[^/]+"
  33. res = b""
  34. i, n = 0, len(segment)
  35. while i < n:
  36. c = segment[i : i + 1]
  37. i = i + 1
  38. if c == b"*":
  39. res += b"[^/]*"
  40. elif c == b"?":
  41. res += b"[^/]"
  42. elif c == b"\\":
  43. res += re.escape(segment[i : i + 1])
  44. i += 1
  45. elif c == b"[":
  46. j = i
  47. if j < n and segment[j : j + 1] == b"!":
  48. j = j + 1
  49. if j < n and segment[j : j + 1] == b"]":
  50. j = j + 1
  51. while j < n and segment[j : j + 1] != b"]":
  52. j = j + 1
  53. if j >= n:
  54. res += b"\\["
  55. else:
  56. stuff = segment[i:j].replace(b"\\", b"\\\\")
  57. i = j + 1
  58. if stuff.startswith(b"!"):
  59. stuff = b"^" + stuff[1:]
  60. elif stuff.startswith(b"^"):
  61. stuff = b"\\" + stuff
  62. res += b"[" + stuff + b"]"
  63. else:
  64. res += re.escape(c)
  65. return res
  66. def translate(pat: bytes) -> bytes:
  67. """Translate a shell PATTERN to a regular expression.
  68. There is no way to quote meta-characters.
  69. Originally copied from fnmatch in Python 2.7, but modified for Dulwich
  70. to cope with features in Git ignore patterns.
  71. """
  72. res = b"(?ms)"
  73. if b"/" not in pat[:-1]:
  74. # If there's no slash, this is a filename-based match
  75. res += b"(.*/)?"
  76. if pat.startswith(b"**/"):
  77. # Leading **/
  78. pat = pat[2:]
  79. res += b"(.*/)?"
  80. if pat.startswith(b"/"):
  81. pat = pat[1:]
  82. for i, segment in enumerate(pat.split(b"/")):
  83. if segment == b"**":
  84. res += b"(/.*)?"
  85. continue
  86. else:
  87. res += (re.escape(b"/") if i > 0 else b"") + _translate_segment(segment)
  88. if not pat.endswith(b"/"):
  89. res += b"/?"
  90. return res + b"\\Z"
  91. def read_ignore_patterns(f: BinaryIO) -> Iterable[bytes]:
  92. """Read a git ignore file.
  93. Args:
  94. f: File-like object to read from
  95. Returns: List of patterns
  96. """
  97. for line in f:
  98. line = line.rstrip(b"\r\n")
  99. # Ignore blank lines, they're used for readability.
  100. if not line.strip():
  101. continue
  102. if line.startswith(b"#"):
  103. # Comment
  104. continue
  105. # Trailing spaces are ignored unless they are quoted with a backslash.
  106. while line.endswith(b" ") and not line.endswith(b"\\ "):
  107. line = line[:-1]
  108. line = line.replace(b"\\ ", b" ")
  109. yield line
  110. def match_pattern(path: bytes, pattern: bytes, ignorecase: bool = False) -> bool:
  111. """Match a gitignore-style pattern against a path.
  112. Args:
  113. path: Path to match
  114. pattern: Pattern to match
  115. ignorecase: Whether to do case-sensitive matching
  116. Returns:
  117. bool indicating whether the pattern matched
  118. """
  119. return Pattern(pattern, ignorecase).match(path)
  120. class Pattern:
  121. """A single ignore pattern."""
  122. def __init__(self, pattern: bytes, ignorecase: bool = False):
  123. self.pattern = pattern
  124. self.ignorecase = ignorecase
  125. if pattern[0:1] == b"!":
  126. self.is_exclude = False
  127. pattern = pattern[1:]
  128. else:
  129. if pattern[0:1] == b"\\":
  130. pattern = pattern[1:]
  131. self.is_exclude = True
  132. flags = 0
  133. if self.ignorecase:
  134. flags = re.IGNORECASE
  135. self._re = re.compile(translate(pattern), flags)
  136. def __bytes__(self) -> bytes:
  137. return self.pattern
  138. def __str__(self) -> str:
  139. return os.fsdecode(self.pattern)
  140. def __eq__(self, other: object) -> bool:
  141. return (
  142. isinstance(other, type(self))
  143. and self.pattern == other.pattern
  144. and self.ignorecase == other.ignorecase
  145. )
  146. def __repr__(self) -> str:
  147. return "{}({!r}, {!r})".format(
  148. type(self).__name__,
  149. self.pattern,
  150. self.ignorecase,
  151. )
  152. def match(self, path: bytes) -> bool:
  153. """Try to match a path against this ignore pattern.
  154. Args:
  155. path: Path to match (relative to ignore location)
  156. Returns: boolean
  157. """
  158. return bool(self._re.match(path))
  159. class IgnoreFilter:
  160. def __init__(self, patterns: Iterable[bytes], ignorecase: bool = False, path=None):
  161. self._patterns: List[Pattern] = []
  162. self._ignorecase = ignorecase
  163. self._path = path
  164. for pattern in patterns:
  165. self.append_pattern(pattern)
  166. def append_pattern(self, pattern: bytes) -> None:
  167. """Add a pattern to the set."""
  168. self._patterns.append(Pattern(pattern, self._ignorecase))
  169. def find_matching(self, path: Union[bytes, str]) -> Iterable[Pattern]:
  170. """Yield all matching patterns for path.
  171. Args:
  172. path: Path to match
  173. Returns:
  174. Iterator over iterators
  175. """
  176. if not isinstance(path, bytes):
  177. path = os.fsencode(path)
  178. for pattern in self._patterns:
  179. if pattern.match(path):
  180. yield pattern
  181. def is_ignored(self, path: bytes) -> Optional[bool]:
  182. """Check whether a path is ignored.
  183. For directories, include a trailing slash.
  184. Returns: status is None if file is not mentioned, True if it is
  185. included, False if it is explicitly excluded.
  186. """
  187. status = None
  188. for pattern in self.find_matching(path):
  189. status = pattern.is_exclude
  190. return status
  191. @classmethod
  192. def from_path(cls, path, ignorecase: bool = False) -> "IgnoreFilter":
  193. with open(path, "rb") as f:
  194. return cls(read_ignore_patterns(f), ignorecase, path=path)
  195. def __repr__(self) -> str:
  196. path = getattr(self, "_path", None)
  197. if path is not None:
  198. return "{}.from_path({!r})".format(type(self).__name__, path)
  199. else:
  200. return "<%s>" % (type(self).__name__)
  201. class IgnoreFilterStack:
  202. """Check for ignore status in multiple filters."""
  203. def __init__(self, filters):
  204. self._filters = filters
  205. def is_ignored(self, path: str) -> Optional[bool]:
  206. """Check whether a path is explicitly included or excluded in ignores.
  207. Args:
  208. path: Path to check
  209. Returns:
  210. None if the file is not mentioned, True if it is included,
  211. False if it is explicitly excluded.
  212. """
  213. status = None
  214. for filter in self._filters:
  215. status = filter.is_ignored(path)
  216. if status is not None:
  217. return status
  218. return status
  219. def default_user_ignore_filter_path(config: Config) -> str:
  220. """Return default user ignore filter path.
  221. Args:
  222. config: A Config object
  223. Returns:
  224. Path to a global ignore file
  225. """
  226. try:
  227. value = config.get((b"core",), b"excludesFile")
  228. assert isinstance(value, bytes)
  229. return value.decode(encoding="utf-8")
  230. except KeyError:
  231. pass
  232. return get_xdg_config_home_path("git", "ignore")
  233. class IgnoreFilterManager:
  234. """Ignore file manager."""
  235. def __init__(
  236. self,
  237. top_path: str,
  238. global_filters: List[IgnoreFilter],
  239. ignorecase: bool,
  240. ):
  241. self._path_filters: Dict[str, Optional[IgnoreFilter]] = {}
  242. self._top_path = top_path
  243. self._global_filters = global_filters
  244. self._ignorecase = ignorecase
  245. def __repr__(self) -> str:
  246. return "{}({}, {!r}, {!r})".format(
  247. type(self).__name__,
  248. self._top_path,
  249. self._global_filters,
  250. self._ignorecase,
  251. )
  252. def _load_path(self, path: str) -> Optional[IgnoreFilter]:
  253. try:
  254. return self._path_filters[path]
  255. except KeyError:
  256. pass
  257. p = os.path.join(self._top_path, path, ".gitignore")
  258. try:
  259. self._path_filters[path] = IgnoreFilter.from_path(p, self._ignorecase)
  260. except OSError:
  261. self._path_filters[path] = None
  262. return self._path_filters[path]
  263. def find_matching(self, path: str) -> Iterable[Pattern]:
  264. """Find matching patterns for path.
  265. Args:
  266. path: Path to check
  267. Returns:
  268. Iterator over Pattern instances
  269. """
  270. if os.path.isabs(path):
  271. raise ValueError("%s is an absolute path" % path)
  272. filters = [(0, f) for f in self._global_filters]
  273. if os.path.sep != "/":
  274. path = path.replace(os.path.sep, "/")
  275. parts = path.split("/")
  276. matches = []
  277. for i in range(len(parts) + 1):
  278. dirname = "/".join(parts[:i])
  279. for s, f in filters:
  280. relpath = "/".join(parts[s:i])
  281. if i < len(parts):
  282. # Paths leading up to the final part are all directories,
  283. # so need a trailing slash.
  284. relpath += "/"
  285. matches += list(f.find_matching(relpath))
  286. ignore_filter = self._load_path(dirname)
  287. if ignore_filter is not None:
  288. filters.insert(0, (i, ignore_filter))
  289. return iter(matches)
  290. def is_ignored(self, path: str) -> Optional[bool]:
  291. """Check whether a path is explicitly included or excluded in ignores.
  292. Args:
  293. path: Path to check
  294. Returns:
  295. None if the file is not mentioned, True if it is included,
  296. False if it is explicitly excluded.
  297. """
  298. matches = list(self.find_matching(path))
  299. if matches:
  300. return matches[-1].is_exclude
  301. return None
  302. @classmethod
  303. def from_repo(cls, repo: "Repo") -> "IgnoreFilterManager":
  304. """Create a IgnoreFilterManager from a repository.
  305. Args:
  306. repo: Repository object
  307. Returns:
  308. A `IgnoreFilterManager` object
  309. """
  310. global_filters = []
  311. for p in [
  312. os.path.join(repo.controldir(), "info", "exclude"),
  313. default_user_ignore_filter_path(repo.get_config_stack()),
  314. ]:
  315. with suppress(OSError):
  316. global_filters.append(IgnoreFilter.from_path(os.path.expanduser(p)))
  317. config = repo.get_config_stack()
  318. ignorecase = config.get_boolean((b"core"), (b"ignorecase"), False)
  319. return cls(repo.path, global_filters, ignorecase)