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

Sanitized regex markers #37

Merged
merged 1 commit into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
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
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
Loading