ignore.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. # Copyright (C) 2017 Jelmer Vernooij <jelmer@jelmer.uk>
  2. #
  3. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  4. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  5. # General Public License as public by the Free Software Foundation; version 2.0
  6. # or (at your option) any later version. You can redistribute it and/or
  7. # modify it under the terms of either of these two licenses.
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # You should have received a copy of the licenses; if not, see
  16. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  17. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  18. # License, Version 2.0.
  19. #
  20. """Parsing of gitignore files.
  21. For details for the matching rules, see https://git-scm.com/docs/gitignore
  22. """
  23. import os.path
  24. import re
  25. from collections.abc import Iterable
  26. from contextlib import suppress
  27. from typing import TYPE_CHECKING, BinaryIO, Optional, Union
  28. if TYPE_CHECKING:
  29. from .repo import Repo
  30. from .config import Config, get_xdg_config_home_path
  31. def _pattern_to_str(pattern) -> str:
  32. """Convert a pattern to string, handling both Pattern objects and raw patterns."""
  33. if hasattr(pattern, "pattern"):
  34. pattern_bytes = pattern.pattern
  35. else:
  36. pattern_bytes = pattern
  37. return pattern_bytes.decode() if isinstance(pattern_bytes, bytes) else pattern_bytes
  38. def _check_parent_exclusion(path: str, matching_patterns: list) -> bool:
  39. """Check if a parent directory exclusion prevents negation patterns from taking effect.
  40. Args:
  41. path: Path to check
  42. matching_patterns: List of Pattern objects that matched the path
  43. Returns:
  44. True if parent exclusion applies (negation should be ineffective), False otherwise
  45. """
  46. # Find the final negation pattern that would include this file
  47. final_negation_pattern = None
  48. for pattern in reversed(matching_patterns):
  49. if not pattern.is_exclude: # is_exclude=False means negation/inclusion
  50. final_negation_pattern = pattern
  51. break
  52. if not final_negation_pattern:
  53. return False # No negation to check
  54. final_pattern_str = _pattern_to_str(final_negation_pattern)
  55. # Check each exclusion pattern to see if it excludes a parent directory
  56. for pattern in matching_patterns:
  57. if not pattern.is_exclude: # Skip negations
  58. continue
  59. pattern_str = _pattern_to_str(pattern)
  60. if _pattern_excludes_parent(pattern_str, path, final_pattern_str):
  61. return True
  62. return False # No parent exclusion applies
  63. def _pattern_excludes_parent(
  64. pattern_str: str, path: str, final_pattern_str: str
  65. ) -> bool:
  66. """Check if a pattern excludes a parent directory of the given path."""
  67. # Case 1: Direct directory exclusion (pattern ending with /)
  68. if pattern_str.endswith("/"):
  69. excluded_dir = pattern_str[:-1] # Remove trailing /
  70. return "/" in path and path.startswith(excluded_dir + "/")
  71. # Case 2: Recursive exclusion patterns (**/dir/**)
  72. if pattern_str.startswith("**/") and pattern_str.endswith("/**"):
  73. dir_name = pattern_str[3:-3] # Remove **/ and /**
  74. return dir_name != "" and ("/" + dir_name + "/") in ("/" + path)
  75. # Case 3: Directory glob patterns (dir/**)
  76. if pattern_str.endswith("/**") and not pattern_str.startswith("**/"):
  77. dir_prefix = pattern_str[:-3] # Remove /**
  78. if path.startswith(dir_prefix + "/"):
  79. # Check if this is a nested path (more than one level under dir_prefix)
  80. remaining_path = path[len(dir_prefix + "/") :]
  81. if "/" in remaining_path:
  82. # This is a nested path - parent directory exclusion applies
  83. # BUT only for directory negations, not file negations
  84. return final_pattern_str.endswith("/")
  85. return False
  86. def _translate_segment(segment: bytes) -> bytes:
  87. """Translate a single path segment to regex, following Git rules exactly."""
  88. if segment == b"*":
  89. return b"[^/]+"
  90. res = b""
  91. i, n = 0, len(segment)
  92. while i < n:
  93. c = segment[i : i + 1]
  94. i += 1
  95. if c == b"*":
  96. res += b"[^/]*"
  97. elif c == b"?":
  98. res += b"[^/]"
  99. elif c == b"\\":
  100. if i < n:
  101. res += re.escape(segment[i : i + 1])
  102. i += 1
  103. else:
  104. res += re.escape(c)
  105. elif c == b"[":
  106. j = i
  107. if j < n and segment[j : j + 1] == b"!":
  108. j += 1
  109. if j < n and segment[j : j + 1] == b"]":
  110. j += 1
  111. while j < n and segment[j : j + 1] != b"]":
  112. j += 1
  113. if j >= n:
  114. res += b"\\["
  115. else:
  116. stuff = segment[i:j].replace(b"\\", b"\\\\")
  117. i = j + 1
  118. if stuff.startswith(b"!"):
  119. stuff = b"^" + stuff[1:]
  120. elif stuff.startswith(b"^"):
  121. stuff = b"\\" + stuff
  122. res += b"[" + stuff + b"]"
  123. else:
  124. res += re.escape(c)
  125. return res
  126. def _handle_double_asterisk(segments: list[bytes], i: int) -> tuple[bytes, bool]:
  127. """Handle ** segment processing, returns (regex_part, skip_next)."""
  128. # Check if ** is at end
  129. remaining = segments[i + 1 :]
  130. if all(s == b"" for s in remaining):
  131. # ** at end - matches everything
  132. return b".*", False
  133. # Check if next segment is also **
  134. if i + 1 < len(segments) and segments[i + 1] == b"**":
  135. # Consecutive ** segments
  136. # Check if this ends with a directory pattern (trailing /)
  137. remaining_after_next = segments[i + 2 :]
  138. is_dir_pattern = (
  139. len(remaining_after_next) == 1 and remaining_after_next[0] == b""
  140. )
  141. if is_dir_pattern:
  142. # Pattern like c/**/**/ - requires at least one intermediate directory
  143. return b"[^/]+/(?:[^/]+/)*", True
  144. else:
  145. # Pattern like c/**/**/d - allows zero intermediate directories
  146. return b"(?:[^/]+/)*", True
  147. else:
  148. # ** in middle - handle differently depending on what follows
  149. if i == 0:
  150. # ** at start - any prefix
  151. return b"(?:.*/)??", False
  152. else:
  153. # ** in middle - match zero or more complete directory segments
  154. return b"(?:[^/]+/)*", False
  155. def _handle_leading_patterns(pat: bytes, res: bytes) -> tuple[bytes, bytes]:
  156. """Handle leading patterns like ``/**/``, ``**/``, or ``/``."""
  157. if pat.startswith(b"/**/"):
  158. # Leading /** is same as **
  159. return pat[4:], b"(.*/)?"
  160. elif pat.startswith(b"**/"):
  161. # Leading **/
  162. return pat[3:], b"(.*/)?"
  163. elif pat.startswith(b"/"):
  164. # Leading / means relative to .gitignore location
  165. return pat[1:], b""
  166. else:
  167. return pat, b""
  168. def translate(pat: bytes) -> bytes:
  169. """Translate a gitignore pattern to a regular expression following Git rules exactly."""
  170. res = b"(?ms)"
  171. # Check for invalid patterns with // - Git treats these as broken patterns
  172. if b"//" in pat:
  173. # Pattern with // doesn't match anything in Git
  174. return b"(?!.*)" # Negative lookahead - matches nothing
  175. # Don't normalize consecutive ** patterns - Git treats them specially
  176. # c/**/**/ requires at least one intermediate directory
  177. # So we keep the pattern as-is
  178. # Handle patterns with no slashes (match at any level)
  179. if b"/" not in pat[:-1]: # No slash except possibly at end
  180. res += b"(.*/)?"
  181. # Handle leading patterns
  182. pat, prefix_added = _handle_leading_patterns(pat, res)
  183. if prefix_added:
  184. res += prefix_added
  185. # Process the rest of the pattern
  186. if pat == b"**":
  187. res += b".*"
  188. else:
  189. segments = pat.split(b"/")
  190. i = 0
  191. while i < len(segments):
  192. segment = segments[i]
  193. # Add slash separator (except for first segment)
  194. if i > 0 and segments[i - 1] != b"**":
  195. res += re.escape(b"/")
  196. if segment == b"**":
  197. regex_part, skip_next = _handle_double_asterisk(segments, i)
  198. res += regex_part
  199. if regex_part == b".*": # End of pattern
  200. break
  201. if skip_next:
  202. i += 1
  203. else:
  204. res += _translate_segment(segment)
  205. i += 1
  206. # Add optional trailing slash for files
  207. if not pat.endswith(b"/"):
  208. res += b"/?"
  209. return res + b"\\Z"
  210. def read_ignore_patterns(f: BinaryIO) -> Iterable[bytes]:
  211. """Read a git ignore file.
  212. Args:
  213. f: File-like object to read from
  214. Returns: List of patterns
  215. """
  216. for line in f:
  217. line = line.rstrip(b"\r\n")
  218. # Ignore blank lines, they're used for readability.
  219. if not line.strip():
  220. continue
  221. if line.startswith(b"#"):
  222. # Comment
  223. continue
  224. # Trailing spaces are ignored unless they are quoted with a backslash.
  225. while line.endswith(b" ") and not line.endswith(b"\\ "):
  226. line = line[:-1]
  227. line = line.replace(b"\\ ", b" ")
  228. yield line
  229. def match_pattern(path: bytes, pattern: bytes, ignorecase: bool = False) -> bool:
  230. """Match a gitignore-style pattern against a path.
  231. Args:
  232. path: Path to match
  233. pattern: Pattern to match
  234. ignorecase: Whether to do case-sensitive matching
  235. Returns:
  236. bool indicating whether the pattern matched
  237. """
  238. return Pattern(pattern, ignorecase).match(path)
  239. class Pattern:
  240. """A single ignore pattern."""
  241. def __init__(self, pattern: bytes, ignorecase: bool = False) -> None:
  242. self.pattern = pattern
  243. self.ignorecase = ignorecase
  244. # Handle negation
  245. if pattern.startswith(b"!"):
  246. self.is_exclude = False
  247. pattern = pattern[1:]
  248. else:
  249. # Handle escaping of ! and # at start only
  250. if (
  251. pattern.startswith(b"\\")
  252. and len(pattern) > 1
  253. and pattern[1:2] in (b"!", b"#")
  254. ):
  255. pattern = pattern[1:]
  256. self.is_exclude = True
  257. # Check if this is a directory-only pattern
  258. self.is_directory_only = pattern.endswith(b"/")
  259. flags = 0
  260. if self.ignorecase:
  261. flags = re.IGNORECASE
  262. self._re = re.compile(translate(pattern), flags)
  263. def __bytes__(self) -> bytes:
  264. return self.pattern
  265. def __str__(self) -> str:
  266. return os.fsdecode(self.pattern)
  267. def __eq__(self, other: object) -> bool:
  268. return (
  269. isinstance(other, type(self))
  270. and self.pattern == other.pattern
  271. and self.ignorecase == other.ignorecase
  272. )
  273. def __repr__(self) -> str:
  274. return f"{type(self).__name__}({self.pattern!r}, {self.ignorecase!r})"
  275. def match(self, path: bytes) -> bool:
  276. """Try to match a path against this ignore pattern.
  277. Args:
  278. path: Path to match (relative to ignore location)
  279. Returns: boolean
  280. """
  281. if self._re.match(path):
  282. return True
  283. # Special handling for directory patterns that exclude files under them
  284. if self.is_directory_only and self.is_exclude:
  285. # For exclusion directory patterns, also match files under the directory
  286. if not path.endswith(b"/"):
  287. # This is a file - check if it's under any directory that matches the pattern
  288. path_dir = path.rsplit(b"/", 1)[0] + b"/"
  289. if len(path.split(b"/")) > 1 and self._re.match(path_dir):
  290. return True
  291. return False
  292. class IgnoreFilter:
  293. def __init__(
  294. self, patterns: Iterable[bytes], ignorecase: bool = False, path=None
  295. ) -> None:
  296. self._patterns: list[Pattern] = []
  297. self._ignorecase = ignorecase
  298. self._path = path
  299. for pattern in patterns:
  300. self.append_pattern(pattern)
  301. def append_pattern(self, pattern: bytes) -> None:
  302. """Add a pattern to the set."""
  303. self._patterns.append(Pattern(pattern, self._ignorecase))
  304. def find_matching(self, path: Union[bytes, str]) -> Iterable[Pattern]:
  305. """Yield all matching patterns for path.
  306. Args:
  307. path: Path to match
  308. Returns:
  309. Iterator over iterators
  310. """
  311. if not isinstance(path, bytes):
  312. path = os.fsencode(path)
  313. for pattern in self._patterns:
  314. if pattern.match(path):
  315. yield pattern
  316. def is_ignored(self, path: bytes) -> Optional[bool]:
  317. """Check whether a path is ignored using Git-compliant logic.
  318. For directories, include a trailing slash.
  319. Returns: status is None if file is not mentioned, True if it is
  320. included, False if it is explicitly excluded.
  321. """
  322. matching_patterns = list(self.find_matching(path))
  323. if not matching_patterns:
  324. return None
  325. # Basic rule: last matching pattern wins
  326. last_pattern = matching_patterns[-1]
  327. result = last_pattern.is_exclude
  328. # Apply Git's parent directory exclusion rule for negations
  329. if not result: # Only applies to inclusions (negations)
  330. result = self._apply_parent_exclusion_rule(
  331. path.decode() if isinstance(path, bytes) else path, matching_patterns
  332. )
  333. return result
  334. def _apply_parent_exclusion_rule(
  335. self, path: str, matching_patterns: list[Pattern]
  336. ) -> bool:
  337. """Apply Git's parent directory exclusion rule.
  338. "It is not possible to re-include a file if a parent directory of that file is excluded."
  339. """
  340. return _check_parent_exclusion(path, matching_patterns)
  341. @classmethod
  342. def from_path(
  343. cls, path: Union[str, os.PathLike], ignorecase: bool = False
  344. ) -> "IgnoreFilter":
  345. with open(path, "rb") as f:
  346. return cls(read_ignore_patterns(f), ignorecase, path=path)
  347. def __repr__(self) -> str:
  348. path = getattr(self, "_path", None)
  349. if path is not None:
  350. return f"{type(self).__name__}.from_path({path!r})"
  351. else:
  352. return f"<{type(self).__name__}>"
  353. class IgnoreFilterStack:
  354. """Check for ignore status in multiple filters."""
  355. def __init__(self, filters) -> None:
  356. self._filters = filters
  357. def is_ignored(self, path: str) -> Optional[bool]:
  358. """Check whether a path is explicitly included or excluded in ignores.
  359. Args:
  360. path: Path to check
  361. Returns:
  362. None if the file is not mentioned, True if it is included,
  363. False if it is explicitly excluded.
  364. """
  365. status = None
  366. for filter in self._filters:
  367. status = filter.is_ignored(path)
  368. if status is not None:
  369. return status
  370. return status
  371. def default_user_ignore_filter_path(config: Config) -> str:
  372. """Return default user ignore filter path.
  373. Args:
  374. config: A Config object
  375. Returns:
  376. Path to a global ignore file
  377. """
  378. try:
  379. value = config.get((b"core",), b"excludesFile")
  380. assert isinstance(value, bytes)
  381. return value.decode(encoding="utf-8")
  382. except KeyError:
  383. pass
  384. return get_xdg_config_home_path("git", "ignore")
  385. class IgnoreFilterManager:
  386. """Ignore file manager with Git-compliant behavior."""
  387. def __init__(
  388. self,
  389. top_path: str,
  390. global_filters: list[IgnoreFilter],
  391. ignorecase: bool,
  392. ) -> None:
  393. self._path_filters: dict[str, Optional[IgnoreFilter]] = {}
  394. self._top_path = top_path
  395. self._global_filters = global_filters
  396. self._ignorecase = ignorecase
  397. def __repr__(self) -> str:
  398. return f"{type(self).__name__}({self._top_path}, {self._global_filters!r}, {self._ignorecase!r})"
  399. def _load_path(self, path: str) -> Optional[IgnoreFilter]:
  400. try:
  401. return self._path_filters[path]
  402. except KeyError:
  403. pass
  404. p = os.path.join(self._top_path, path, ".gitignore")
  405. try:
  406. self._path_filters[path] = IgnoreFilter.from_path(p, self._ignorecase)
  407. except OSError:
  408. self._path_filters[path] = None
  409. return self._path_filters[path]
  410. def find_matching(self, path: str) -> Iterable[Pattern]:
  411. """Find matching patterns for path.
  412. Args:
  413. path: Path to check
  414. Returns:
  415. Iterator over Pattern instances
  416. """
  417. if os.path.isabs(path):
  418. raise ValueError(f"{path} is an absolute path")
  419. filters = [(0, f) for f in self._global_filters]
  420. if os.path.sep != "/":
  421. path = path.replace(os.path.sep, "/")
  422. parts = path.split("/")
  423. matches = []
  424. for i in range(len(parts) + 1):
  425. dirname = "/".join(parts[:i])
  426. for s, f in filters:
  427. relpath = "/".join(parts[s:i])
  428. if i < len(parts):
  429. # Paths leading up to the final part are all directories,
  430. # so need a trailing slash.
  431. relpath += "/"
  432. matches += list(f.find_matching(relpath))
  433. ignore_filter = self._load_path(dirname)
  434. if ignore_filter is not None:
  435. filters.insert(0, (i, ignore_filter))
  436. return iter(matches)
  437. def is_ignored(self, path: str) -> Optional[bool]:
  438. """Check whether a path is explicitly included or excluded in ignores.
  439. Args:
  440. path: Path to check. For directories, the path should end with '/'.
  441. Returns:
  442. None if the file is not mentioned, True if it is included,
  443. False if it is explicitly excluded.
  444. """
  445. matches = list(self.find_matching(path))
  446. if not matches:
  447. return None
  448. # Standard behavior - last matching pattern wins
  449. result = matches[-1].is_exclude
  450. # Apply Git's parent directory exclusion rule for negations
  451. if not result: # Only check if we would include due to negation
  452. result = _check_parent_exclusion(path, matches)
  453. # Apply special case for issue #1203: directory traversal with ** patterns
  454. if result and path.endswith("/"):
  455. result = self._apply_directory_traversal_rule(path, matches)
  456. return result
  457. def _apply_directory_traversal_rule(self, path: str, matches: list) -> bool:
  458. """Apply directory traversal rule for issue #1203.
  459. If a directory would be ignored by a ** pattern, but there are negation
  460. patterns for its subdirectories, then the directory itself should not
  461. be ignored (to allow traversal).
  462. """
  463. # Get the last pattern that determined the result
  464. last_excluding_pattern = None
  465. for match in matches:
  466. if match.is_exclude:
  467. last_excluding_pattern = match
  468. if last_excluding_pattern and (
  469. last_excluding_pattern.pattern.endswith(b"**")
  470. or b"**" in last_excluding_pattern.pattern
  471. ):
  472. # Check if subdirectories would be unignored
  473. test_subdir = path + "test/"
  474. test_matches = list(self.find_matching(test_subdir))
  475. if test_matches:
  476. # Use standard logic for test case - last matching pattern wins
  477. test_result = test_matches[-1].is_exclude
  478. if test_result is False:
  479. return False
  480. return True # Keep original result
  481. @classmethod
  482. def from_repo(cls, repo: "Repo") -> "IgnoreFilterManager":
  483. """Create a IgnoreFilterManager from a repository.
  484. Args:
  485. repo: Repository object
  486. Returns:
  487. A `IgnoreFilterManager` object
  488. """
  489. global_filters = []
  490. for p in [
  491. os.path.join(repo.controldir(), "info", "exclude"),
  492. default_user_ignore_filter_path(repo.get_config_stack()),
  493. ]:
  494. with suppress(OSError):
  495. global_filters.append(IgnoreFilter.from_path(os.path.expanduser(p)))
  496. config = repo.get_config_stack()
  497. ignorecase = config.get_boolean((b"core"), (b"ignorecase"), False)
  498. return cls(repo.path, global_filters, ignorecase)