Skip to content

Commit

Permalink
Sanitized regex markers (#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
trag1c authored Jun 11, 2024
1 parent 0410b88 commit 439aa61
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
2 changes: 2 additions & 0 deletions dahlia/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,5 @@
8: "\033[48;5;{}m",
24: "\033[48;2;{}m",
}

REGEX_BREAKING_MARKERS = set("^$.|()[]\\*+?")
9 changes: 8 additions & 1 deletion dahlia/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
import re
from typing import TYPE_CHECKING

from dahlia.constants import ANSI_REGEX, CODE_REGEXES, NO_GROUP_CODES
from dahlia.constants import (
ANSI_REGEX,
CODE_REGEXES,
NO_GROUP_CODES,
REGEX_BREAKING_MARKERS,
)

if TYPE_CHECKING:
from collections.abc import Iterator
Expand Down Expand Up @@ -52,4 +57,6 @@ def _with_marker(marker: str) -> list[re.Pattern[str]]:
if len(marker) != 1:
msg = "The marker has to be a single character"
raise ValueError(msg)
if marker in REGEX_BREAKING_MARKERS:
marker = "\\" + marker
return [re.compile(marker + i) for i in CODE_REGEXES]
11 changes: 10 additions & 1 deletion tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import pytest

from dahlia.constants import REGEX_BREAKING_MARKERS
from dahlia.lib import Dahlia, Depth


Expand Down Expand Up @@ -46,13 +47,21 @@ def test_conversion(depth: Depth, string: str, expected: str) -> None:
("x", "&ee§ee§§_4x"),
],
)
def test_markers(marker: str, expected: str) -> None:
def test_marker_clashing(marker: str, expected: str) -> None:
assert (
Dahlia(marker=marker, auto_reset=False, depth=Depth.LOW).convert("&ee§ee§§_4x")
== expected
)


@pytest.mark.parametrize("marker", REGEX_BREAKING_MARKERS)
def test_regex_markers(marker: str) -> None:
assert (
Dahlia(depth=Depth.LOW, marker=marker).convert(f"{marker}4xe5")
== "\x1b[31mxe5\x1b[0m"
)


@pytest.mark.parametrize("marker", ["", "&&"])
def test_invalid_marker(marker: str) -> None:
with pytest.raises(ValueError, match="The marker has to be a single character"):
Expand Down

0 comments on commit 439aa61

Please sign in to comment.