Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Find the reverse-replacements by strictly using single pass and maximal munch #761

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions src/retrocookie/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,18 +119,31 @@ def __init__(
self.replacements = get_replacements(
context, include_variables, exclude_variables
)
self._replacement_map = dict(self.replacements)
ordered_replacees = sorted(
self._replacement_map, key=len, reverse=True
)
self._replacement_regex = re.compile(b"|".join(
re.escape(s) for s in ordered_replacees
))

def _single_substitution_replacer(self, match: re.Match) -> bytes:
return self._replacement_map[match.group(0)]

def _replacer(self, content: bytes) -> bytes:
return self._replacement_regex.sub(
self._single_substitution_replacer, content
)

def filename_callback(self, filename: bytes) -> bytes:
"""Rewrite filenames."""
for old, new in self.replacements:
filename = filename.replace(old, new)
filename = self._replacer(filename)
return b"/".join((self.template_directory, filename))

def blob_callback(self, blob: Blob, metadata: Dict[str, Any]) -> None:
"""Rewrite blobs."""
blob.data = escape_jinja(blob.data)
for old, new in self.replacements:
blob.data = blob.data.replace(old, new)
blob.data = self._replacer(blob.data)

def _create_filter(self) -> RepoFilter:
"""Create the filter."""
Expand Down
Loading