ignore.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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 published 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. Important: When checking if directories are ignored, include a trailing slash in the path.
  23. For example, use "dir/" instead of "dir" to check if a directory is ignored.
  24. """
  25. __all__ = [
  26. "IgnoreFilter",
  27. "IgnoreFilterManager",
  28. "IgnoreFilterStack",
  29. "Pattern",
  30. "default_user_ignore_filter_path",
  31. "match_pattern",
  32. "read_ignore_patterns",
  33. "translate",
  34. ]
  35. import os.path
  36. import re
  37. from collections.abc import Iterable, Sequence
  38. from contextlib import suppress
  39. from typing import TYPE_CHECKING, BinaryIO
  40. if TYPE_CHECKING:
  41. from .repo import Repo
  42. from .config import Config, get_xdg_config_home_path
  43. def _pattern_to_str(pattern: "Pattern | bytes | str") -> str:
  44. """Convert a pattern to string, handling both Pattern objects and raw patterns."""
  45. if isinstance(pattern, Pattern):
  46. pattern_data: bytes | str = pattern.pattern
  47. else:
  48. pattern_data = pattern
  49. return pattern_data.decode() if isinstance(pattern_data, bytes) else pattern_data
  50. def _check_parent_exclusion(path: str, matching_patterns: Sequence["Pattern"]) -> bool:
  51. """Check if a parent directory exclusion prevents negation patterns from taking effect.
  52. Args:
  53. path: Path to check
  54. matching_patterns: List of Pattern objects that matched the path
  55. Returns:
  56. True if parent exclusion applies (negation should be ineffective), False otherwise
  57. """
  58. # Find the last negation pattern
  59. final_negation = next(
  60. (p for p in reversed(matching_patterns) if not p.is_exclude), None
  61. )
  62. if not final_negation:
  63. return False
  64. final_pattern_str = _pattern_to_str(final_negation)
  65. # Check if any exclusion pattern excludes a parent directory
  66. return any(
  67. pattern.is_exclude
  68. and _pattern_excludes_parent(_pattern_to_str(pattern), path, final_pattern_str)
  69. for pattern in matching_patterns
  70. )
  71. def _pattern_excludes_parent(
  72. pattern_str: str, path: str, final_pattern_str: str
  73. ) -> bool:
  74. """Check if a pattern excludes a parent directory of the given path."""
  75. # Handle **/middle/** patterns
  76. if pattern_str.startswith("**/") and pattern_str.endswith("/**"):
  77. middle = pattern_str[3:-3]
  78. return f"/{middle}/" in f"/{path}" or path.startswith(f"{middle}/")
  79. # Handle dir/** patterns
  80. if pattern_str.endswith("/**") and not pattern_str.startswith("**/"):
  81. base_dir = pattern_str[:-3]
  82. if not path.startswith(base_dir + "/"):
  83. return False
  84. remaining = path[len(base_dir) + 1 :]
  85. # Special case: dir/** allows immediate child file negations
  86. if (
  87. not path.endswith("/")
  88. and final_pattern_str.startswith("!")
  89. and "/" not in remaining
  90. ):
  91. neg_pattern = final_pattern_str[1:]
  92. if neg_pattern == path or ("*" in neg_pattern and "**" not in neg_pattern):
  93. return False
  94. # Nested files with ** negation patterns
  95. if "**" in final_pattern_str and Pattern(final_pattern_str[1:].encode()).match(
  96. path.encode()
  97. ):
  98. return False
  99. return True
  100. # Directory patterns (ending with /) can exclude parent directories
  101. if pattern_str.endswith("/") and "/" in path:
  102. p = Pattern(pattern_str.encode())
  103. parts = path.split("/")
  104. return any(
  105. p.match(("/".join(parts[:i]) + "/").encode()) for i in range(1, len(parts))
  106. )
  107. return False
  108. def _translate_segment(segment: bytes) -> bytes:
  109. """Translate a single path segment to regex, following Git rules exactly."""
  110. if segment == b"*":
  111. return b"[^/]+"
  112. res = b""
  113. i, n = 0, len(segment)
  114. while i < n:
  115. c = segment[i : i + 1]
  116. i += 1
  117. if c == b"*":
  118. res += b"[^/]*"
  119. elif c == b"?":
  120. res += b"[^/]"
  121. elif c == b"\\":
  122. if i < n:
  123. res += re.escape(segment[i : i + 1])
  124. i += 1
  125. else:
  126. res += re.escape(c)
  127. elif c == b"[":
  128. j = i
  129. if j < n and segment[j : j + 1] == b"!":
  130. j += 1
  131. if j < n and segment[j : j + 1] == b"]":
  132. j += 1
  133. while j < n and segment[j : j + 1] != b"]":
  134. j += 1
  135. if j >= n:
  136. res += b"\\["
  137. else:
  138. stuff = segment[i:j].replace(b"\\", b"\\\\")
  139. i = j + 1
  140. if stuff.startswith(b"!"):
  141. stuff = b"^" + stuff[1:]
  142. elif stuff.startswith(b"^"):
  143. stuff = b"\\" + stuff
  144. res += b"[" + stuff + b"]"
  145. else:
  146. res += re.escape(c)
  147. return res
  148. def _handle_double_asterisk(segments: Sequence[bytes], i: int) -> tuple[bytes, bool]:
  149. """Handle ** segment processing, returns (regex_part, skip_next)."""
  150. # Check if ** is at end
  151. remaining = segments[i + 1 :]
  152. if all(s == b"" for s in remaining):
  153. # ** at end - matches everything
  154. return b".*", False
  155. # Check if next segment is also **
  156. if i + 1 < len(segments) and segments[i + 1] == b"**":
  157. # Consecutive ** segments
  158. # Check if this ends with a directory pattern (trailing /)
  159. remaining_after_next = segments[i + 2 :]
  160. is_dir_pattern = (
  161. len(remaining_after_next) == 1 and remaining_after_next[0] == b""
  162. )
  163. if is_dir_pattern:
  164. # Pattern like c/**/**/ - requires at least one intermediate directory
  165. return b"[^/]+/(?:[^/]+/)*", True
  166. else:
  167. # Pattern like c/**/**/d - allows zero intermediate directories
  168. return b"(?:[^/]+/)*", True
  169. else:
  170. # ** in middle - handle differently depending on what follows
  171. if i == 0:
  172. # ** at start - any prefix
  173. return b"(?:.*/)??", False
  174. else:
  175. # ** in middle - match zero or more complete directory segments
  176. return b"(?:[^/]+/)*", False
  177. def _handle_leading_patterns(pat: bytes, res: bytes) -> tuple[bytes, bytes]:
  178. """Handle leading patterns like ``/**/``, ``**/``, or ``/``."""
  179. if pat.startswith(b"/**/"):
  180. # Leading /** is same as **
  181. return pat[4:], b"(.*/)?"
  182. elif pat.startswith(b"**/"):
  183. # Leading **/
  184. return pat[3:], b"(.*/)?"
  185. elif pat.startswith(b"/"):
  186. # Leading / means relative to .gitignore location
  187. return pat[1:], b""
  188. else:
  189. return pat, b""
  190. def translate(pat: bytes) -> bytes:
  191. """Translate a gitignore pattern to a regular expression following Git rules exactly."""
  192. res = b"(?ms)"
  193. # Check for invalid patterns with // - Git treats these as broken patterns
  194. if b"//" in pat:
  195. # Pattern with // doesn't match anything in Git
  196. return b"(?!.*)" # Negative lookahead - matches nothing
  197. # Don't normalize consecutive ** patterns - Git treats them specially
  198. # c/**/**/ requires at least one intermediate directory
  199. # So we keep the pattern as-is
  200. # Handle patterns with no slashes (match at any level)
  201. if b"/" not in pat[:-1]: # No slash except possibly at end
  202. res += b"(.*/)?"
  203. # Handle leading patterns
  204. pat, prefix_added = _handle_leading_patterns(pat, res)
  205. if prefix_added:
  206. res += prefix_added
  207. # Process the rest of the pattern
  208. if pat == b"**":
  209. res += b".*"
  210. else:
  211. segments = pat.split(b"/")
  212. i = 0
  213. while i < len(segments):
  214. segment = segments[i]
  215. # Add slash separator (except for first segment)
  216. if i > 0 and segments[i - 1] != b"**":
  217. res += re.escape(b"/")
  218. if segment == b"**":
  219. regex_part, skip_next = _handle_double_asterisk(segments, i)
  220. res += regex_part
  221. if regex_part == b".*": # End of pattern
  222. break
  223. if skip_next:
  224. i += 1
  225. else:
  226. res += _translate_segment(segment)
  227. i += 1
  228. # Add optional trailing slash for files
  229. if not pat.endswith(b"/"):
  230. res += b"/?"
  231. return res + b"\\Z"
  232. def read_ignore_patterns(f: BinaryIO) -> Iterable[bytes]:
  233. """Read a git ignore file.
  234. Args:
  235. f: File-like object to read from
  236. Returns: List of patterns
  237. """
  238. for line in f:
  239. line = line.rstrip(b"\r\n")
  240. # Ignore blank lines, they're used for readability.
  241. if not line.strip():
  242. continue
  243. if line.startswith(b"#"):
  244. # Comment
  245. continue
  246. # Trailing spaces are ignored unless they are quoted with a backslash.
  247. while line.endswith(b" ") and not line.endswith(b"\\ "):
  248. line = line[:-1]
  249. line = line.replace(b"\\ ", b" ")
  250. yield line
  251. def match_pattern(path: bytes, pattern: bytes, ignorecase: bool = False) -> bool:
  252. """Match a gitignore-style pattern against a path.
  253. Args:
  254. path: Path to match
  255. pattern: Pattern to match
  256. ignorecase: Whether to do case-sensitive matching
  257. Returns:
  258. bool indicating whether the pattern matched
  259. """
  260. return Pattern(pattern, ignorecase).match(path)
  261. class Pattern:
  262. """A single ignore pattern."""
  263. def __init__(self, pattern: bytes, ignorecase: bool = False) -> None:
  264. """Initialize a Pattern object.
  265. Args:
  266. pattern: The gitignore pattern as bytes.
  267. ignorecase: Whether to perform case-insensitive matching.
  268. """
  269. self.pattern = pattern
  270. self.ignorecase = ignorecase
  271. # Handle negation
  272. if pattern.startswith(b"!"):
  273. self.is_exclude = False
  274. pattern = pattern[1:]
  275. else:
  276. # Handle escaping of ! and # at start only
  277. if (
  278. pattern.startswith(b"\\")
  279. and len(pattern) > 1
  280. and pattern[1:2] in (b"!", b"#")
  281. ):
  282. pattern = pattern[1:]
  283. self.is_exclude = True
  284. # Check if this is a directory-only pattern
  285. self.is_directory_only = pattern.endswith(b"/")
  286. flags = 0
  287. if self.ignorecase:
  288. flags = re.IGNORECASE
  289. self._re = re.compile(translate(pattern), flags)
  290. def __bytes__(self) -> bytes:
  291. """Return the pattern as bytes.
  292. Returns:
  293. The original pattern as bytes.
  294. """
  295. return self.pattern
  296. def __str__(self) -> str:
  297. """Return the pattern as a string.
  298. Returns:
  299. The pattern decoded as a string.
  300. """
  301. return os.fsdecode(self.pattern)
  302. def __eq__(self, other: object) -> bool:
  303. """Check equality with another Pattern object.
  304. Args:
  305. other: The object to compare with.
  306. Returns:
  307. True if patterns and ignorecase flags are equal, False otherwise.
  308. """
  309. return (
  310. isinstance(other, type(self))
  311. and self.pattern == other.pattern
  312. and self.ignorecase == other.ignorecase
  313. )
  314. def __repr__(self) -> str:
  315. """Return a string representation of the Pattern object.
  316. Returns:
  317. A string representation for debugging.
  318. """
  319. return f"{type(self).__name__}({self.pattern!r}, {self.ignorecase!r})"
  320. def match(self, path: bytes) -> bool:
  321. """Try to match a path against this ignore pattern.
  322. Args:
  323. path: Path to match (relative to ignore location)
  324. Returns: boolean
  325. """
  326. # For negation directory patterns (e.g., !dir/), only match directories
  327. if self.is_directory_only and not self.is_exclude and not path.endswith(b"/"):
  328. return False
  329. # Check if the regex matches
  330. if self._re.match(path):
  331. return True
  332. # For exclusion directory patterns, also match files under the directory
  333. if (
  334. self.is_directory_only
  335. and self.is_exclude
  336. and not path.endswith(b"/")
  337. and b"/" in path
  338. ):
  339. return bool(self._re.match(path.rsplit(b"/", 1)[0] + b"/"))
  340. return False
  341. class IgnoreFilter:
  342. """Filter to apply gitignore patterns.
  343. Important: When checking if directories are ignored, include a trailing slash.
  344. For example, use is_ignored("dir/") instead of is_ignored("dir").
  345. """
  346. def __init__(
  347. self,
  348. patterns: Iterable[bytes],
  349. ignorecase: bool = False,
  350. path: str | None = None,
  351. ) -> None:
  352. """Initialize an IgnoreFilter with a set of patterns.
  353. Args:
  354. patterns: An iterable of gitignore patterns as bytes.
  355. ignorecase: Whether to perform case-insensitive matching.
  356. path: Optional path to the ignore file for debugging purposes.
  357. """
  358. self._patterns: list[Pattern] = []
  359. self._ignorecase = ignorecase
  360. self._path = path
  361. for pattern in patterns:
  362. self.append_pattern(pattern)
  363. def append_pattern(self, pattern: bytes) -> None:
  364. """Add a pattern to the set."""
  365. self._patterns.append(Pattern(pattern, self._ignorecase))
  366. def find_matching(self, path: bytes | str) -> Iterable[Pattern]:
  367. """Yield all matching patterns for path.
  368. Args:
  369. path: Path to match
  370. Returns:
  371. Iterator over iterators
  372. """
  373. if not isinstance(path, bytes):
  374. path = os.fsencode(path)
  375. for pattern in self._patterns:
  376. if pattern.match(path):
  377. yield pattern
  378. def is_ignored(self, path: bytes | str) -> bool | None:
  379. """Check whether a path is ignored using Git-compliant logic.
  380. For directories, include a trailing slash.
  381. Returns: status is None if file is not mentioned, True if it is
  382. included, False if it is explicitly excluded.
  383. """
  384. matching_patterns = list(self.find_matching(path))
  385. if not matching_patterns:
  386. return None
  387. # Basic rule: last matching pattern wins
  388. last_pattern = matching_patterns[-1]
  389. result = last_pattern.is_exclude
  390. # Apply Git's parent directory exclusion rule for negations
  391. if not result: # Only applies to inclusions (negations)
  392. result = self._apply_parent_exclusion_rule(
  393. path.decode() if isinstance(path, bytes) else path, matching_patterns
  394. )
  395. return result
  396. def _apply_parent_exclusion_rule(
  397. self, path: str, matching_patterns: list[Pattern]
  398. ) -> bool:
  399. """Apply Git's parent directory exclusion rule.
  400. "It is not possible to re-include a file if a parent directory of that file is excluded."
  401. """
  402. return _check_parent_exclusion(path, matching_patterns)
  403. @classmethod
  404. def from_path(
  405. cls, path: str | os.PathLike[str], ignorecase: bool = False
  406. ) -> "IgnoreFilter":
  407. """Create an IgnoreFilter from a file path.
  408. Args:
  409. path: Path to the ignore file.
  410. ignorecase: Whether to perform case-insensitive matching.
  411. Returns:
  412. An IgnoreFilter instance with patterns loaded from the file.
  413. """
  414. with open(path, "rb") as f:
  415. return cls(read_ignore_patterns(f), ignorecase, path=str(path))
  416. def __repr__(self) -> str:
  417. """Return string representation of IgnoreFilter."""
  418. path = getattr(self, "_path", None)
  419. if path is not None:
  420. return f"{type(self).__name__}.from_path({path!r})"
  421. else:
  422. return f"<{type(self).__name__}>"
  423. class IgnoreFilterStack:
  424. """Check for ignore status in multiple filters."""
  425. def __init__(self, filters: list[IgnoreFilter]) -> None:
  426. """Initialize an IgnoreFilterStack with multiple filters.
  427. Args:
  428. filters: A list of IgnoreFilter objects to check in order.
  429. """
  430. self._filters = filters
  431. def is_ignored(self, path: str) -> bool | None:
  432. """Check whether a path is explicitly included or excluded in ignores.
  433. Args:
  434. path: Path to check
  435. Returns:
  436. None if the file is not mentioned, True if it is included,
  437. False if it is explicitly excluded.
  438. """
  439. for filter in self._filters:
  440. status = filter.is_ignored(path)
  441. if status is not None:
  442. return status
  443. return None
  444. def __repr__(self) -> str:
  445. """Return a string representation of the IgnoreFilterStack.
  446. Returns:
  447. A string representation for debugging.
  448. """
  449. return f"{type(self).__name__}({self._filters!r})"
  450. def default_user_ignore_filter_path(config: Config) -> str:
  451. """Return default user ignore filter path.
  452. Args:
  453. config: A Config object
  454. Returns:
  455. Path to a global ignore file
  456. """
  457. try:
  458. value = config.get((b"core",), b"excludesFile")
  459. assert isinstance(value, bytes)
  460. return value.decode(encoding="utf-8")
  461. except KeyError:
  462. pass
  463. return get_xdg_config_home_path("git", "ignore")
  464. class IgnoreFilterManager:
  465. """Ignore file manager with Git-compliant behavior.
  466. Important: When checking if directories are ignored, include a trailing slash.
  467. For example, use is_ignored("dir/") instead of is_ignored("dir").
  468. """
  469. def __init__(
  470. self,
  471. top_path: str,
  472. global_filters: list[IgnoreFilter],
  473. ignorecase: bool,
  474. ) -> None:
  475. """Initialize an IgnoreFilterManager.
  476. Args:
  477. top_path: The top-level directory path to manage ignores for.
  478. global_filters: List of global ignore filters to apply.
  479. ignorecase: Whether to perform case-insensitive matching.
  480. """
  481. self._path_filters: dict[str, IgnoreFilter | None] = {}
  482. self._top_path = top_path
  483. self._global_filters = global_filters
  484. self._ignorecase = ignorecase
  485. def __repr__(self) -> str:
  486. """Return string representation of IgnoreFilterManager."""
  487. return f"{type(self).__name__}({self._top_path}, {self._global_filters!r}, {self._ignorecase!r})"
  488. def _load_path(self, path: str) -> IgnoreFilter | None:
  489. try:
  490. return self._path_filters[path]
  491. except KeyError:
  492. pass
  493. p = os.path.join(self._top_path, path, ".gitignore")
  494. try:
  495. self._path_filters[path] = IgnoreFilter.from_path(p, self._ignorecase)
  496. except (FileNotFoundError, NotADirectoryError):
  497. self._path_filters[path] = None
  498. except OSError as e:
  499. # On Windows, opening a path that contains a symlink can fail with
  500. # errno 22 (Invalid argument) when the symlink points outside the repo
  501. if e.errno == 22:
  502. self._path_filters[path] = None
  503. else:
  504. raise
  505. return self._path_filters[path]
  506. def find_matching(self, path: str) -> Iterable[Pattern]:
  507. """Find matching patterns for path.
  508. Args:
  509. path: Path to check
  510. Returns:
  511. Iterator over Pattern instances
  512. """
  513. if os.path.isabs(path):
  514. raise ValueError(f"{path} is an absolute path")
  515. filters = [(0, f) for f in self._global_filters]
  516. if os.path.sep != "/":
  517. path = path.replace(os.path.sep, "/")
  518. parts = path.split("/")
  519. matches = []
  520. for i in range(len(parts) + 1):
  521. dirname = "/".join(parts[:i])
  522. for s, f in filters:
  523. relpath = "/".join(parts[s:i])
  524. if i < len(parts):
  525. # Paths leading up to the final part are all directories,
  526. # so need a trailing slash.
  527. relpath += "/"
  528. matches += list(f.find_matching(relpath))
  529. ignore_filter = self._load_path(dirname)
  530. if ignore_filter is not None:
  531. filters.insert(0, (i, ignore_filter))
  532. return iter(matches)
  533. def is_ignored(self, path: str) -> bool | None:
  534. """Check whether a path is explicitly included or excluded in ignores.
  535. Args:
  536. path: Path to check. For directories, the path should end with '/'.
  537. Returns:
  538. None if the file is not mentioned, True if it is included,
  539. False if it is explicitly excluded.
  540. """
  541. matches = list(self.find_matching(path))
  542. if not matches:
  543. return None
  544. # Standard behavior - last matching pattern wins
  545. result = matches[-1].is_exclude
  546. # Apply Git's parent directory exclusion rule for negations
  547. if not result: # Only check if we would include due to negation
  548. result = _check_parent_exclusion(path, matches)
  549. # Apply special case for issue #1203: directory traversal with ** patterns
  550. if result and path.endswith("/"):
  551. result = self._apply_directory_traversal_rule(path, matches)
  552. return result
  553. def _apply_directory_traversal_rule(
  554. self, path: str, matches: list["Pattern"]
  555. ) -> bool:
  556. """Apply directory traversal rule for issue #1203.
  557. If a directory would be ignored by a ** pattern, but there are negation
  558. patterns for its subdirectories, then the directory itself should not
  559. be ignored (to allow traversal).
  560. """
  561. # Original logic for traversal check
  562. last_excluding_pattern = None
  563. for match in matches:
  564. if match.is_exclude:
  565. last_excluding_pattern = match
  566. if last_excluding_pattern and (
  567. last_excluding_pattern.pattern.endswith(b"**")
  568. or b"**" in last_excluding_pattern.pattern
  569. ):
  570. # Check if subdirectories would be unignored
  571. test_subdir = path + "test/"
  572. test_matches = list(self.find_matching(test_subdir))
  573. if test_matches:
  574. # Use standard logic for test case - last matching pattern wins
  575. test_result = test_matches[-1].is_exclude
  576. if test_result is False:
  577. return False
  578. return True # Keep original result
  579. @classmethod
  580. def from_repo(cls, repo: "Repo") -> "IgnoreFilterManager":
  581. """Create a IgnoreFilterManager from a repository.
  582. Args:
  583. repo: Repository object
  584. Returns:
  585. A `IgnoreFilterManager` object
  586. """
  587. global_filters = []
  588. for p in [
  589. os.path.join(repo.controldir(), "info", "exclude"),
  590. default_user_ignore_filter_path(repo.get_config_stack()),
  591. ]:
  592. with suppress(OSError):
  593. global_filters.append(IgnoreFilter.from_path(os.path.expanduser(p)))
  594. config = repo.get_config_stack()
  595. ignorecase = config.get_boolean((b"core"), (b"ignorecase"), False)
  596. return cls(repo.path, global_filters, ignorecase)