Skip to content

Commit 75beff8

Browse files
Detect More Faulty Codeblocks (#3514)
* enhanced codeblock regex and made stricter requirements for valid codeblocks * added empty newline for readability * minor code cleanup
1 parent 433372b commit 75beff8

1 file changed

Lines changed: 8 additions & 6 deletions

File tree

bot/exts/info/codeblock/_parsing.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,11 @@
3535
fr"""
3636
(?P<ticks>
3737
(?P<tick>[{''.join(_TICKS)}]) # Put all ticks into a character class within a group.
38-
\2{{2}} # Match previous group 2 more times to ensure the same char.
38+
\2* # Match previous group up to N more times to ensure the same char.
3939
)
40-
(?P<lang>[A-Za-z0-9\+\-\.]+\n)? # Optionally match a language specifier followed by a newline.
40+
(?P<lang>[A-Za-z0-9+\-.]+\s)? # Optionally match a language specifier followed by a whitespace.
4141
(?P<code>.+?) # Match the actual code within the block.
42-
\1 # Match the same 3 ticks used at the start of the block.
42+
\1 # Match the same N ticks used at the start of the block.
4343
""",
4444
re.DOTALL | re.VERBOSE
4545
)
@@ -86,11 +86,12 @@ def find_code_blocks(message: str) -> Sequence[CodeBlock] | None:
8686
for match in _RE_CODE_BLOCK.finditer(message):
8787
# Used to ensure non-matched groups have an empty string as the default value.
8888
groups = match.groupdict("")
89-
language = groups["lang"].strip() # Strip the newline cause it's included in the group.
89+
language = groups["lang"].strip() # Strip the whitespace cause it's included in the group.
9090

91-
if groups["tick"] == BACKTICK and language:
91+
if groups["tick"] == BACKTICK and len(groups["ticks"]) == 3 and language and ("\n" in groups["lang"]):
9292
log.trace("Message has a valid code block with a language; returning None.")
9393
return None
94+
9495
if has_lines(groups["code"], constants.CodeBlock.minimum_lines):
9596
code_block = CodeBlock(groups["code"], language, groups["tick"])
9697
code_blocks.append(code_block)
@@ -181,14 +182,15 @@ def parse_bad_language(content: str) -> BadLanguage | None:
181182
)
182183

183184

184-
def _get_leading_spaces(content: str) -> int:
185+
def _get_leading_spaces(content: str) -> int | None:
185186
"""Return the number of spaces at the start of the first line in `content`."""
186187
leading_spaces = 0
187188
for char in content:
188189
if char == " ":
189190
leading_spaces += 1
190191
else:
191192
return leading_spaces
193+
192194
return None
193195

194196

0 commit comments

Comments
 (0)