Skip to content

Commit cae539b

Browse files
fix(mentions): neutralize mentions in HTML blocks, split table cells and URLs with backticks (#5027)
1 parent b75a0d2 commit cae539b

6 files changed

Lines changed: 195 additions & 95 deletions

File tree

‎pr_agent/algo/mentions/blocks.py‎

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -24,25 +24,30 @@
2424
(re.compile(r"<!\[CDATA\["), ("]]>",)),
2525
(re.compile(rf"</?(?:{_HTML_BLOCK_TAGS})(?:[\s>]|/>|$)", re.IGNORECASE), ()),
2626
)
27+
_TAG_LINE_RE = re.compile(
28+
r"(?:<[A-Za-z][A-Za-z0-9-]*+(?:[ \t\v\f]++[A-Za-z_:][A-Za-z0-9_.:-]*+(?:[ \t\v\f]*+=[ \t\v\f]*+"
29+
r"(?:[^ \t\v\f\"'=<>`]++|'[^']*+'|\"[^\"]*+\"))?+)*+[ \t\v\f]*+/?>|</[A-Za-z][A-Za-z0-9-]*+[ \t\v\f]*+>)[ \t\f]*$"
30+
)
2731

2832

29-
def _html_block_ends(line: str) -> tuple[str, ...] | None:
33+
def _html_block_ends(line: str, interrupting: bool) -> tuple[str, ...] | None:
3034
for start, ends in _HTML_BLOCK_STARTS:
3135
if start.match(line):
3236
return ends
33-
return None
37+
return () if not interrupting and _TAG_LINE_RE.match(line) else None
3438

3539

3640
def _table_cells(line: str) -> list[str]:
3741
return _TABLE_PIPE_RE.split(line.strip().removeprefix("|").removesuffix("|"))
3842

3943

40-
def _is_table_delimiter(line: str, header: str) -> bool:
41-
if "|" not in line:
42-
return False
43-
cells = _table_cells(line)
44-
return (len(cells) == len(_table_cells(header))
45-
and all(_TABLE_CELL_RE.fullmatch(cell.strip()) for cell in cells))
44+
def _cell_cuts(line: str, offset: int) -> list[int]:
45+
return [offset + pipe.start() for pipe in _TABLE_PIPE_RE.finditer(line)]
46+
47+
48+
def _delimiter_cells(line: str) -> int:
49+
cells = _table_cells(line) if "|" in line else []
50+
return len(cells) if cells and all(_TABLE_CELL_RE.fullmatch(cell.strip()) for cell in cells) else 0
4651

4752

4853
def _opens_fence(line: str) -> re.Match | None:
@@ -52,14 +57,14 @@ def _opens_fence(line: str) -> re.Match | None:
5257
return None
5358

5459

55-
def _starts_html(line: str) -> tuple[str, ...] | None:
56-
return _html_block_ends(line.lstrip(" ")) if indent_of(line) <= 3 else None
60+
def _starts_html(line: str, interrupting: bool) -> tuple[str, ...] | None:
61+
return _html_block_ends(line.lstrip(" "), interrupting) if indent_of(line) <= 3 else None
5762

5863

5964
def _continues_paragraph(line: str) -> bool:
6065
return bool(line.strip()) and not (
6166
_opens_fence(line) or _ATX_RE.match(line) or THEMATIC_RE.match(line)
62-
or _starts_html(line) is not None)
67+
or _starts_html(line, False) is not None)
6368

6469

6570
def line_flags(text: str) -> tuple[dict[int, bool], list[int], set[int]]:
@@ -72,7 +77,7 @@ def line_flags(text: str) -> tuple[dict[int, bool], list[int], set[int]]:
7277
fence_size = 0
7378
html_ends: tuple[str, ...] | None = None
7479
indented_code = False
75-
in_table = False
80+
in_table = table_visited = False
7681
empty_item = False
7782
paragraph = False
7883
header = ""
@@ -84,6 +89,7 @@ def line_flags(text: str) -> tuple[dict[int, bool], list[int], set[int]]:
8489
line = raw_line.removesuffix("\r").expandtabs(4)
8590
is_code = False
8691
in_html = False
92+
cuts = []
8793
boundary = boundary_next
8894
boundary_next = False
8995
depth, rest = continue_containers(containers, quotes, line, empty_item)
@@ -122,7 +128,7 @@ def line_flags(text: str) -> tuple[dict[int, bool], list[int], set[int]]:
122128
stripped = rest.strip()
123129
indent = indent_of(rest)
124130
fence = _opens_fence(rest)
125-
html_block = _starts_html(rest) if stripped else None
131+
html_block = _starts_html(rest, paragraph) if stripped else None
126132
if lazy:
127133
pass
128134
elif indented_code and (not stripped or indent >= 4):
@@ -144,20 +150,24 @@ def line_flags(text: str) -> tuple[dict[int, bool], list[int], set[int]]:
144150
indented_code = False
145151
single_line_block = bool(
146152
_ATX_RE.match(rest) or THEMATIC_RE.match(rest) or (paragraph and _SETEXT_RE.match(rest)))
153+
delimiter = _delimiter_cells(rest) if paragraph and indent <= 3 and not table_visited else 0
147154
if not stripped:
148155
boundary = True
149156
in_table = paragraph = False
150-
elif paragraph and indent <= 3 and _is_table_delimiter(rest, header):
157+
elif delimiter and delimiter == len(_table_cells(header)):
151158
boundary = in_table = True
152159
paragraph = False
153160
if prev_start is not None and (not boundaries or boundaries[-1] != prev_start):
154161
boundaries.append(prev_start)
162+
boundaries += _cell_cuts(text[prev_start:offset - 1], prev_start)
155163
elif in_table and not single_line_block:
156164
boundary = True
165+
cuts = _cell_cuts(raw_line, offset)
157166
elif single_line_block:
158167
boundary = boundary_next = True
159168
in_table = paragraph = False
160169
else:
170+
table_visited = paragraph and (table_visited or delimiter > 0)
161171
in_table = False
162172
paragraph = True
163173
header = rest
@@ -167,6 +177,7 @@ def line_flags(text: str) -> tuple[dict[int, bool], list[int], set[int]]:
167177
html_starts.add(offset)
168178
if boundary:
169179
boundaries.append(offset)
180+
boundaries += cuts
170181
prev_start = offset
171182
offset += len(raw_line) + 1
172183

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from .autolinks import github_autolinks, gitlab_autolinks
2+
3+
__all__ = ["github_autolinks", "gitlab_autolinks"]
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import re
2+
import string
3+
import unicodedata
4+
from bisect import bisect_left, bisect_right
5+
6+
from ..blocks import line_flags
7+
from .brackets import TICKS_RE, open_bracket_spans
8+
9+
_GITLAB_URL_RE = re.compile(r"(?<![a-z0-9+.-])[a-z][a-z0-9+.-]{1,31}://[^\s<>`()\[\]\"'*~|\\]+")
10+
_GITHUB_URL_RE = re.compile(r"(?<![A-Za-z])(?i:https?)://(?=\S)|(?<![^\s*_~(])www\.")
11+
_ANGLE_RE = re.compile(r"(?<!\\)<(?i:https?|mailto):[^\x00-\x20<>\x7f]*>")
12+
_TAIL_RE = re.compile(r"[^\s<>`()\[\]\"'*~|\\]*")
13+
_EXTENT_RE = re.compile(r"[^ \t\n\r<]*")
14+
_HTML_TAG_RE = re.compile(r"<[A-Za-z/!?](?:=[ \t\n\f\r]*(?:\"[^\"]*\"|'[^']*')|[^>])*+>?")
15+
_CONTAINER_PREFIX_RE = re.compile(r"^[ \t>]+", re.MULTILINE)
16+
17+
18+
def _is_host_char(char: str) -> bool:
19+
return not (char.isspace() or char in string.punctuation or unicodedata.category(char).startswith("P"))
20+
21+
22+
def _domain_end(text: str, start: int) -> int:
23+
end = start
24+
while end < len(text) and (text[end] in "._-" or _is_host_char(text[end])):
25+
end += 1
26+
return end
27+
28+
29+
def _is_valid_domain(domain: str) -> bool:
30+
return _is_host_char(domain[:1] or " ") and "_" not in "".join(domain.split(".")[-2:])
31+
32+
33+
def _url_ends(text: str) -> dict[int, int]:
34+
ends = {}
35+
extent_end = 0
36+
for match in _GITHUB_URL_RE.finditer(text):
37+
domain = match.start() if match.group().startswith("www") else match.end()
38+
if _is_valid_domain(text[domain:_domain_end(text, domain)]):
39+
if match.end() >= extent_end:
40+
extent_end = _EXTENT_RE.match(text, match.end()).end()
41+
ends[match.start()] = extent_end
42+
return ends
43+
44+
45+
def _html_text_spans(text: str, start: int, end: int) -> list[tuple[int, int]]:
46+
spans = []
47+
for tag in _HTML_TAG_RE.finditer(text, start, end):
48+
spans.append((start, tag.start()))
49+
start = tag.end()
50+
return [*spans, (start, end)]
51+
52+
53+
def _unlinked_spans(text: str) -> tuple[list[tuple[int, int]], list[tuple[int, int]]]:
54+
code_by_start, boundaries, html_starts = line_flags(text)
55+
masked = _CONTAINER_PREFIX_RE.sub(lambda prefix: " " * len(prefix.group()), text)
56+
ticks: dict[int, list[int]] = {}
57+
for run in TICKS_RE.finditer(masked):
58+
ticks.setdefault(len(run.group()), []).append(run.start())
59+
urls = _url_ends(masked)
60+
61+
spans = []
62+
extents = []
63+
stops = set(boundaries)
64+
run_start = html_start = None
65+
for offset, is_code in [*code_by_start.items(), (len(text) + 1, True)]:
66+
html = offset in html_starts
67+
if run_start is not None and (is_code or html or offset in stops):
68+
cells = boundaries[bisect_right(boundaries, run_start):bisect_left(boundaries, offset - 1)]
69+
cell_start = run_start
70+
for cell_end in [*cells, offset - 1]:
71+
found, linked = open_bracket_spans(masked, cell_start, cell_end, ticks, urls)
72+
spans += found
73+
extents += linked
74+
cell_start = cell_end
75+
run_start = None
76+
if html_start is not None and not html:
77+
spans += _html_text_spans(text, html_start, offset - 1)
78+
html_start = None
79+
if run_start is None and not (is_code or html):
80+
run_start = offset
81+
if html_start is None and html:
82+
html_start = offset
83+
return spans, extents
84+
85+
86+
def gitlab_autolinks(text: str) -> tuple[list[tuple[int, int]], list[tuple[int, int]]]:
87+
return [match.span() for match in _GITLAB_URL_RE.finditer(text)], []
88+
89+
90+
def github_autolinks(text: str) -> tuple[list[tuple[int, int]], list[tuple[int, int]]]:
91+
spans = [match.span() for match in _ANGLE_RE.finditer(text)]
92+
unlinked, extents = _unlinked_spans(text)
93+
unlinked_starts = [start for start, _ in unlinked]
94+
covered = 0
95+
for match in _GITHUB_URL_RE.finditer(text):
96+
if match.start() < covered:
97+
continue
98+
inside = bisect_left(unlinked_starts, match.start() + 1) - 1
99+
if inside >= 0 and match.start() < unlinked[inside][1]:
100+
continue
101+
domain = match.start() if match.group().startswith("www") else match.end()
102+
covered = _domain_end(text, domain)
103+
if _is_valid_domain(text[domain:covered]):
104+
covered = _TAIL_RE.match(text, match.end()).end()
105+
spans.append((match.start(), covered))
106+
107+
merged: list[tuple[int, int]] = []
108+
for start, end in sorted(spans):
109+
if merged and start <= merged[-1][1]:
110+
merged[-1] = (merged[-1][0], max(end, merged[-1][1]))
111+
else:
112+
merged.append((start, end))
113+
return merged, extents
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,9 @@
11
import re
22
import string
3-
import unicodedata
43
from bisect import bisect_left
54

6-
from .blocks import line_flags
7-
8-
_GITLAB_URL_RE = re.compile(r"(?<![a-z0-9+.-])[a-z][a-z0-9+.-]{1,31}://[^\s<>`()\[\]\"'*~|\\]+")
9-
_GITHUB_URL_RE = re.compile(r"(?<![A-Za-z])(?i:https?)://(?=\S)|(?<![^\s*_~(])www\.")
10-
_ANGLE_RE = re.compile(r"(?<!\\)<(?i:https?|mailto):[^\x00-\x20<>\x7f]*>")
11-
_TAIL_RE = re.compile(r"[^\s<>`()\[\]\"'*~|\\]*")
125
_SPACE = " \t\n\v\f\r"
13-
_CONTAINER_PREFIX_RE = re.compile(r"^[ \t>]+", re.MULTILINE)
14-
_TICKS_RE = re.compile(r"`+")
6+
TICKS_RE = re.compile(r"`+")
157
_SPACES_RE = re.compile(r"[ \t\n\v\f\r]*")
168
_ANGLE_DEST_RE = re.compile(r"<(?:\\[\s\S]|[^\\<>\n])*>")
179
_TITLE_RE = re.compile(r"\"(?:[^\"]|(?<=\\)\")*\"|'(?:[^']|(?<=\\)')*'|\((?:[^()]|(?<=\\)[()])*\)")
@@ -27,21 +19,6 @@
2719
)
2820

2921

30-
def _is_host_char(char: str) -> bool:
31-
return not (char.isspace() or char in string.punctuation or unicodedata.category(char).startswith("P"))
32-
33-
34-
def _domain_end(text: str, start: int) -> int:
35-
end = start
36-
while end < len(text) and (text[end] in "._-" or _is_host_char(text[end])):
37-
end += 1
38-
return end
39-
40-
41-
def _is_valid_domain(domain: str) -> bool:
42-
return _is_host_char(domain[:1] or " ") and "_" not in "".join(domain.split(".")[-2:])
43-
44-
4522
def _bare_destination_end(text: str, pos: int, end: int) -> int | None:
4623
start = pos
4724
depth = 0
@@ -100,8 +77,11 @@ def _spills(text: str, start: int, stop: int, end: int, last: dict[str, int]) ->
10077
return False
10178

10279

103-
def _open_bracket_spans(text: str, start: int, end: int, ticks: dict[int, list[int]]) -> list[tuple[int, int]]:
80+
def open_bracket_spans(
81+
text: str, start: int, end: int, ticks: dict[int, list[int]], urls: dict[int, int]
82+
) -> tuple[list[tuple[int, int]], list[tuple[int, int]]]:
10483
spans = []
84+
extents = []
10585
last = {closer: text.rfind(closer, start, end) for closer in ("`", *(closer for _, closer in _RAW_HTML))}
10686
depth = 0
10787
lax = False
@@ -113,7 +93,7 @@ def _open_bracket_spans(text: str, start: int, end: int, ticks: dict[int, list[i
11393
if char == "\\" and step < end and text[step] in string.punctuation:
11494
step += 1
11595
elif char == "`" and not lax:
116-
step = _TICKS_RE.match(text, pos, end).end()
96+
step = TICKS_RE.match(text, pos, end).end()
11797
runs = ticks.get(step - pos, [])
11898
closer = bisect_left(runs, step)
11999
if closer < len(runs) and runs[closer] < end:
@@ -133,6 +113,9 @@ def _open_bracket_spans(text: str, start: int, end: int, ticks: dict[int, list[i
133113
if tail_end and not lax:
134114
depth += text.count("[", step, tail_end)
135115
step = tail_end
116+
elif not depth and pos in urls:
117+
step = min(urls[pos], end)
118+
extents.append((pos, step))
136119

137120
if not before and depth:
138121
opened = pos
@@ -141,54 +124,4 @@ def _open_bracket_spans(text: str, start: int, end: int, ticks: dict[int, list[i
141124
pos = step
142125
if depth:
143126
spans.append((opened, end))
144-
return spans
145-
146-
147-
def _bracket_spans(text: str) -> list[tuple[int, int]]:
148-
code_by_start, boundaries, html_starts = line_flags(text)
149-
masked = _CONTAINER_PREFIX_RE.sub(lambda prefix: " " * len(prefix.group()), text)
150-
ticks: dict[int, list[int]] = {}
151-
for run in _TICKS_RE.finditer(masked):
152-
ticks.setdefault(len(run.group()), []).append(run.start())
153-
154-
spans = []
155-
stops = set(boundaries)
156-
run_start = None
157-
for offset, is_code in [*code_by_start.items(), (len(text) + 1, True)]:
158-
raw = is_code or offset in html_starts
159-
if run_start is not None and (raw or offset in stops):
160-
spans += _open_bracket_spans(masked, run_start, offset - 1, ticks)
161-
run_start = None
162-
if run_start is None and not raw:
163-
run_start = offset
164-
return spans
165-
166-
167-
def gitlab_autolinks(text: str) -> list[tuple[int, int]]:
168-
return [match.span() for match in _GITLAB_URL_RE.finditer(text)]
169-
170-
171-
def github_autolinks(text: str) -> list[tuple[int, int]]:
172-
spans = [match.span() for match in _ANGLE_RE.finditer(text)]
173-
brackets = _bracket_spans(text)
174-
bracket_starts = [start for start, _ in brackets]
175-
covered = 0
176-
for match in _GITHUB_URL_RE.finditer(text):
177-
if match.start() < covered:
178-
continue
179-
inside = bisect_left(bracket_starts, match.start() + 1) - 1
180-
if inside >= 0 and match.start() < brackets[inside][1]:
181-
continue
182-
domain = match.start() if match.group().startswith("www") else match.end()
183-
covered = _domain_end(text, domain)
184-
if _is_valid_domain(text[domain:covered]):
185-
covered = _TAIL_RE.match(text, match.end()).end()
186-
spans.append((match.start(), covered))
187-
188-
merged: list[tuple[int, int]] = []
189-
for start, end in sorted(spans):
190-
if merged and start <= merged[-1][1]:
191-
merged[-1] = (merged[-1][0], max(end, merged[-1][1]))
192-
else:
193-
merged.append((start, end))
194-
return merged
127+
return spans, extents

0 commit comments

Comments
 (0)