Skip to content

Add shorthand hex color parsing #3655

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
6 changes: 6 additions & 0 deletions rich/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,8 @@ class ColorParseError(Exception):
"""The color could not be parsed."""


RE_SHORT_COLOR = re.compile(r"^\#([0-9a-f])([0-9a-f])([0-9a-f])$")

RE_COLOR = re.compile(
r"""^
\#([0-9a-f]{6})$|
Expand Down Expand Up @@ -446,6 +448,10 @@ def parse(cls, color: str) -> "Color":
number=color_number,
)

if short_match := RE_SHORT_COLOR.fullmatch(color):
r, g, b = short_match.groups()
color = f"#{r*2}{g*2}{b*2}"

color_match = RE_COLOR.match(color)
if color_match is None:
raise ColorParseError(f"{original_color!r} is not a valid color")
Expand Down
7 changes: 7 additions & 0 deletions tests/test_color.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def test_system() -> None:
assert Color.parse("default").system == ColorSystem.STANDARD
assert Color.parse("red").system == ColorSystem.STANDARD
assert Color.parse("#ff0000").system == ColorSystem.TRUECOLOR
assert Color.parse("#f00").system == ColorSystem.TRUECOLOR


def test_windows() -> None:
Expand All @@ -47,6 +48,7 @@ def test_windows() -> None:

def test_truecolor() -> None:
assert Color.parse("#ff0000").get_truecolor() == ColorTriplet(255, 0, 0)
assert Color.parse("#f00").get_truecolor() == ColorTriplet(255, 0, 0)
assert Color.parse("red").get_truecolor() == ColorTriplet(128, 0, 0)
assert Color.parse("color(1)").get_truecolor() == ColorTriplet(128, 0, 0)
assert Color.parse("color(17)").get_truecolor() == ColorTriplet(0, 0, 95)
Expand All @@ -70,6 +72,9 @@ def test_parse_success() -> None:
assert Color.parse("#112233") == Color(
"#112233", ColorType.TRUECOLOR, None, ColorTriplet(0x11, 0x22, 0x33)
)
assert Color.parse("#123") == Color(
"#112233", ColorType.TRUECOLOR, None, ColorTriplet(0x11, 0x22, 0x33)
)
assert Color.parse("rgb(90,100,110)") == Color(
"rgb(90,100,110)", ColorType.TRUECOLOR, None, ColorTriplet(90, 100, 110)
)
Expand Down Expand Up @@ -110,6 +115,8 @@ def test_parse_error() -> None:
Color.parse("nosuchcolor")
with pytest.raises(ColorParseError):
Color.parse("#xxyyzz")
with pytest.raises(ColorParseError):
Color.parse("#xyz")


def test_get_ansi_codes() -> None:
Expand Down