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

Unable to parse 3-digit RGB string #1466

Open
omgraae opened this issue Jan 31, 2025 · 1 comment
Open

Unable to parse 3-digit RGB string #1466

omgraae opened this issue Jan 31, 2025 · 1 comment

Comments

@omgraae
Copy link

omgraae commented Jan 31, 2025

Issue Description

Problem

The method from_string in the RGBColor class was failing when an invalid RGB hex string was passed. Specifically, the method expected a 6-digit hex string but did not handle cases where a 3-digit hex string was provided, leading to a ValueError when attempting to convert an empty string to an integer.

Background

I am using pygments to perform syntax highlighting on source-code. For reasons, the color-codes are ?sometimes? in a 3-digit format. To fix my immediate issue, I selected to alter the class rather than validating and/or translating input before calling it. I have only seen the 3-digit HEX codes in my project, but did consider issues from other types of colour coding from arbitrary input. Probably an elegant way exists to translate something like the 3-digit hex or even color names:
w3schools colors names

A solution

The method was updated locally on my computer to handle both 6-digit and 3-digit RGB hex strings. The updated method uses regular expressions to validate the input string and appropriately converts 3-digit hex strings by duplicating each digit.

Code Changes

file: shared.py

import re

Class: RGBColor

    @classmethod
    def from_string(cls, rgb_hex_str: str) -> RGBColor:
        """Return a new instance from an RGB color hex string like ``'3C2F80'`` or like ``'1FC'``."""
        if re.match(r"^[0-9a-fA-F]{6}$", rgb_hex_str):
            r = int(rgb_hex_str[:2], 16)
            g = int(rgb_hex_str[2:4], 16)
            b = int(rgb_hex_str[4:], 16)
        elif re.match(r"^[0-9a-fA-F]{3}$", rgb_hex_str):
            """Correct translation into 6 digit hex codes is doubling every digit."""
            r = int(rgb_hex_str[0] * 2, 16)
            g = int(rgb_hex_str[1] * 2, 16)
            b = int(rgb_hex_str[2] * 2, 16)
        else:
            raise ValueError(f"Invalid RGB hex string: {rgb_hex_str}")
        return cls(r, g, b)
@omgraae
Copy link
Author

omgraae commented Jan 31, 2025

python-docx_v1.1.2_rgb.patch

Apply with:

patch .venv/lib/python*/site-packages/docx/shared.py < python-docx_v1.1.2_rgb.patch
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant