Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit a77c369

Browse files
authored
Move glob_to_regex and re_word_boundary to matrix-python-common (#11505)
1 parent 4eb7796 commit a77c369

File tree

8 files changed

+13
-123
lines changed

8 files changed

+13
-123
lines changed

changelog.d/11505.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Move `glob_to_regex` and `re_word_boundary` to `matrix-python-common`.

synapse/config/room_directory.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,9 @@
1515

1616
from typing import List
1717

18+
from matrix_common.regex import glob_to_regex
19+
1820
from synapse.types import JsonDict
19-
from synapse.util import glob_to_regex
2021

2122
from ._base import Config, ConfigError
2223

synapse/config/tls.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,12 @@
1616
import os
1717
from typing import List, Optional, Pattern
1818

19+
from matrix_common.regex import glob_to_regex
20+
1921
from OpenSSL import SSL, crypto
2022
from twisted.internet._sslverify import Certificate, trustRootFromCertificates
2123

2224
from synapse.config._base import Config, ConfigError
23-
from synapse.util import glob_to_regex
2425

2526
logger = logging.getLogger(__name__)
2627

synapse/federation/federation_server.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
Union,
2929
)
3030

31+
from matrix_common.regex import glob_to_regex
3132
from prometheus_client import Counter, Gauge, Histogram
3233

3334
from twisted.internet import defer
@@ -66,7 +67,7 @@
6667
)
6768
from synapse.storage.databases.main.lock import Lock
6869
from synapse.types import JsonDict, get_domain_from_id
69-
from synapse.util import glob_to_regex, json_decoder, unwrapFirstError
70+
from synapse.util import json_decoder, unwrapFirstError
7071
from synapse.util.async_helpers import Linearizer, concurrently_execute
7172
from synapse.util.caches.response_cache import ResponseCache
7273
from synapse.util.stringutils import parse_server_name

synapse/push/push_rule_evaluator.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,10 @@
1717
import re
1818
from typing import Any, Dict, List, Optional, Pattern, Tuple, Union
1919

20+
from matrix_common.regex import glob_to_regex, to_word_pattern
21+
2022
from synapse.events import EventBase
2123
from synapse.types import JsonDict, UserID
22-
from synapse.util import glob_to_regex, re_word_boundary
2324
from synapse.util.caches.lrucache import LruCache
2425

2526
logger = logging.getLogger(__name__)
@@ -184,7 +185,7 @@ def _contains_display_name(self, display_name: Optional[str]) -> bool:
184185
r = regex_cache.get((display_name, False, True), None)
185186
if not r:
186187
r1 = re.escape(display_name)
187-
r1 = re_word_boundary(r1)
188+
r1 = to_word_pattern(r1)
188189
r = re.compile(r1, flags=re.IGNORECASE)
189190
regex_cache[(display_name, False, True)] = r
190191

@@ -213,7 +214,7 @@ def _glob_matches(glob: str, value: str, word_boundary: bool = False) -> bool:
213214
try:
214215
r = regex_cache.get((glob, True, word_boundary), None)
215216
if not r:
216-
r = glob_to_regex(glob, word_boundary)
217+
r = glob_to_regex(glob, word_boundary=word_boundary)
217218
regex_cache[(glob, True, word_boundary)] = r
218219
return bool(r.search(value))
219220
except re.error:

synapse/python_dependencies.py

+1
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@
8787
# with the latest security patches.
8888
"cryptography>=3.4.7",
8989
"ijson>=3.1",
90+
"matrix-common==1.0.0",
9091
]
9192

9293
CONDITIONAL_REQUIREMENTS = {

synapse/util/__init__.py

+1-58
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,8 @@
1414

1515
import json
1616
import logging
17-
import re
1817
import typing
19-
from typing import Any, Callable, Dict, Generator, Optional, Pattern
18+
from typing import Any, Callable, Dict, Generator, Optional
2019

2120
import attr
2221
from frozendict import frozendict
@@ -35,9 +34,6 @@
3534
logger = logging.getLogger(__name__)
3635

3736

38-
_WILDCARD_RUN = re.compile(r"([\?\*]+)")
39-
40-
4137
def _reject_invalid_json(val: Any) -> None:
4238
"""Do not allow Infinity, -Infinity, or NaN values in JSON."""
4339
raise ValueError("Invalid JSON value: '%s'" % val)
@@ -185,56 +181,3 @@ def log_failure(
185181
if not consumeErrors:
186182
return failure
187183
return None
188-
189-
190-
def glob_to_regex(glob: str, word_boundary: bool = False) -> Pattern:
191-
"""Converts a glob to a compiled regex object.
192-
193-
Args:
194-
glob: pattern to match
195-
word_boundary: If True, the pattern will be allowed to match at word boundaries
196-
anywhere in the string. Otherwise, the pattern is anchored at the start and
197-
end of the string.
198-
199-
Returns:
200-
compiled regex pattern
201-
"""
202-
203-
# Patterns with wildcards must be simplified to avoid performance cliffs
204-
# - The glob `?**?**?` is equivalent to the glob `???*`
205-
# - The glob `???*` is equivalent to the regex `.{3,}`
206-
chunks = []
207-
for chunk in _WILDCARD_RUN.split(glob):
208-
# No wildcards? re.escape()
209-
if not _WILDCARD_RUN.match(chunk):
210-
chunks.append(re.escape(chunk))
211-
continue
212-
213-
# Wildcards? Simplify.
214-
qmarks = chunk.count("?")
215-
if "*" in chunk:
216-
chunks.append(".{%d,}" % qmarks)
217-
else:
218-
chunks.append(".{%d}" % qmarks)
219-
220-
res = "".join(chunks)
221-
222-
if word_boundary:
223-
res = re_word_boundary(res)
224-
else:
225-
# \A anchors at start of string, \Z at end of string
226-
res = r"\A" + res + r"\Z"
227-
228-
return re.compile(res, re.IGNORECASE)
229-
230-
231-
def re_word_boundary(r: str) -> str:
232-
"""
233-
Adds word boundary characters to the start and end of an
234-
expression to require that the match occur as a whole word,
235-
but do so respecting the fact that strings starting or ending
236-
with non-word characters will change word boundaries.
237-
"""
238-
# we can't use \b as it chokes on unicode. however \W seems to be okay
239-
# as shorthand for [^0-9A-Za-z_].
240-
return r"(^|\W)%s(\W|$)" % (r,)

tests/util/test_glob_to_regex.py

-59
This file was deleted.

0 commit comments

Comments
 (0)