| 1 |
""" |
| 2 |
This module provides the :module:`re2` backend for :class:`~pathspec.pathspec.PathSpec`. |
| 3 |
|
| 4 |
WARNING: The *pathspec._backends.re2* package is not part of the public API. Its |
| 5 |
contents and structure are likely to change. |
| 6 |
""" |
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
from collections.abc import ( |
| 10 |
Sequence) |
| 11 |
from typing import ( |
| 12 |
Callable, # Replaced by `collections.abc.Callable` in 3.9.2. |
| 13 |
Optional) # Replaced by `X | None` in 3.10. |
| 14 |
|
| 15 |
try: |
| 16 |
import re2 |
| 17 |
except ModuleNotFoundError: |
| 18 |
re2 = None # type: ignore[assignment] |
| 19 |
|
| 20 |
from pathspec.backend import ( |
| 21 |
_Backend) |
| 22 |
from pathspec.pattern import ( |
| 23 |
RegexPattern) |
| 24 |
from pathspec._typing import ( |
| 25 |
override) # Added in 3.12. |
| 26 |
|
| 27 |
from .._utils import ( |
| 28 |
enumerate_patterns) |
| 29 |
|
| 30 |
from .base import ( |
| 31 |
re2_error) |
| 32 |
from ._base import ( |
| 33 |
RE2_OPTIONS, |
| 34 |
Re2RegexDat, |
| 35 |
Re2RegexDebug) |
| 36 |
|
| 37 |
|
| 38 |
class Re2PsBackend(_Backend): |
| 39 |
""" |
| 40 |
The :class:`Re2PsBackend` class is the :module:`re2` implementation used by |
| 41 |
:class:`~pathspec.pathspec.PathSpec` for matching files. |
| 42 |
""" |
| 43 |
|
| 44 |
def __init__( |
| 45 |
self, |
| 46 |
patterns: Sequence[RegexPattern], |
| 47 |
*, |
| 48 |
_debug_regex: Optional[bool] = None, |
| 49 |
_test_sort: Optional[Callable[[list], None]] = None, |
| 50 |
) -> None: |
| 51 |
""" |
| 52 |
Initialize the :class:`Re2PsBackend` instance. |
| 53 |
|
| 54 |
*patterns* (:class:`Sequence` of :class:`.RegexPattern`) contains the |
| 55 |
compiled patterns. |
| 56 |
""" |
| 57 |
if re2_error is not None: |
| 58 |
raise re2_error |
| 59 |
|
| 60 |
if patterns and not isinstance(patterns[0], RegexPattern): |
| 61 |
raise TypeError(f"{patterns[0]=!r} must be a RegexPattern.") |
| 62 |
|
| 63 |
use_patterns = dict(enumerate_patterns( |
| 64 |
patterns, filter=True, reverse=False, |
| 65 |
)) |
| 66 |
regex_set = self._make_set() |
| 67 |
|
| 68 |
self._debug_regex = bool(_debug_regex) |
| 69 |
""" |
| 70 |
*_debug_regex* (:class:`bool`) is whether to include additional debugging |
| 71 |
information for the regular expressions. |
| 72 |
""" |
| 73 |
|
| 74 |
self._patterns: dict[int, RegexPattern] = use_patterns |
| 75 |
""" |
| 76 |
*_patterns* (:class:`dict`) maps pattern index (:class:`int`) to pattern |
| 77 |
(:class:`RegexPattern`). |
| 78 |
""" |
| 79 |
|
| 80 |
self._regex_data: list[Re2RegexDat] = self._init_set( |
| 81 |
debug=self._debug_regex, |
| 82 |
patterns=use_patterns, |
| 83 |
regex_set=regex_set, |
| 84 |
sort_indices=_test_sort, |
| 85 |
) |
| 86 |
""" |
| 87 |
*_regex_data* (:class:`list`) maps regex index (:class:`int`) to regex data |
| 88 |
(:class:`Re2RegexDat`). |
| 89 |
""" |
| 90 |
|
| 91 |
self._set: re2.Set = regex_set # type: ignore |
| 92 |
""" |
| 93 |
*_set* (:class:`re2.Set`) is the re2 regex set. |
| 94 |
""" |
| 95 |
|
| 96 |
@staticmethod |
| 97 |
def _init_set( |
| 98 |
debug: bool, |
| 99 |
patterns: dict[int, RegexPattern], |
| 100 |
regex_set: re2.Set, # type: ignore |
| 101 |
sort_indices: Optional[Callable[[list[int]], None]], |
| 102 |
) -> list[Re2RegexDat]: |
| 103 |
""" |
| 104 |
Create the re2 regex set. |
| 105 |
|
| 106 |
*debug* (:class:`bool`) is whether to include additional debugging |
| 107 |
information for the regular expressions. |
| 108 |
|
| 109 |
*patterns* (:class:`dict`) maps pattern index (:class:`int`) to pattern |
| 110 |
(:class:`.RegexPattern`). |
| 111 |
|
| 112 |
*regex_set* (:class:`re2.Set`) is the regex set. |
| 113 |
|
| 114 |
*sort_indices* (:class:`callable` or :data:`None`) is a function used to |
| 115 |
sort the patterns by index. This is used during testing to ensure the order |
| 116 |
of patterns is not accidentally relied on. |
| 117 |
|
| 118 |
Returns a :class:`list` indexed by regex id (:class:`int`) to its data |
| 119 |
(:class:`Re2RegexDat`). |
| 120 |
""" |
| 121 |
# Sort patterns. |
| 122 |
indices = list(patterns.keys()) |
| 123 |
if sort_indices is not None: |
| 124 |
sort_indices(indices) |
| 125 |
|
| 126 |
# Prepare patterns. |
| 127 |
regex_data: list[Re2RegexDat] = [] |
| 128 |
for pattern_index in indices: |
| 129 |
pattern = patterns[pattern_index] |
| 130 |
if pattern.include is None: |
| 131 |
continue |
| 132 |
|
| 133 |
assert pattern.regex is not None, pattern |
| 134 |
assert isinstance(pattern, RegexPattern), pattern |
| 135 |
regex = pattern.regex.pattern |
| 136 |
|
| 137 |
if debug: |
| 138 |
regex_data.append(Re2RegexDebug( |
| 139 |
include=pattern.include, |
| 140 |
index=pattern_index, |
| 141 |
is_dir_pattern=False, |
| 142 |
regex=regex, |
| 143 |
)) |
| 144 |
else: |
| 145 |
regex_data.append(Re2RegexDat( |
| 146 |
include=pattern.include, |
| 147 |
index=pattern_index, |
| 148 |
is_dir_pattern=False, |
| 149 |
)) |
| 150 |
|
| 151 |
regex_set.Add(regex) |
| 152 |
|
| 153 |
# Compile patterns. |
| 154 |
regex_set.Compile() |
| 155 |
return regex_data |
| 156 |
|
| 157 |
@staticmethod |
| 158 |
def _make_set() -> re2.Set: # type: ignore |
| 159 |
""" |
| 160 |
Create the re2 regex set. |
| 161 |
|
| 162 |
Returns the set (:class:`re2.Set`). |
| 163 |
""" |
| 164 |
assert re2 is not None, (re2, re2_error) |
| 165 |
return re2.Set.SearchSet(RE2_OPTIONS) |
| 166 |
|
| 167 |
@override |
| 168 |
def match_file(self, file: str) -> tuple[Optional[bool], Optional[int]]: |
| 169 |
""" |
| 170 |
Check the file against the patterns. |
| 171 |
|
| 172 |
*file* (:class:`str`) is the normalized file path to check. |
| 173 |
|
| 174 |
Returns a :class:`tuple` containing whether to include *file* (:class:`bool` |
| 175 |
or :data:`None`), and the index of the last matched pattern (:class:`int` or |
| 176 |
:data:`None`). |
| 177 |
""" |
| 178 |
# Find best match. |
| 179 |
# - WARNING: According to the documentation on `RE2::Set::Match()`, there is |
| 180 |
# no guarantee matches will be produced in order! Later expressions have |
| 181 |
# higher priority. |
| 182 |
match_ids: Optional[list[int]] = self._set.Match(file) # type: ignore[assignment] |
| 183 |
if not match_ids: |
| 184 |
return (None, None) |
| 185 |
|
| 186 |
regex_data = self._regex_data |
| 187 |
pattern_index = max(regex_data[__id].index for __id in match_ids) |
| 188 |
pattern = self._patterns[pattern_index] |
| 189 |
return (pattern.include, pattern_index) |