Skip to content
Myr

Validate `style()` color arguments (#3677)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Rowlando13 · committed by GitHub · parents 8dd4d60, 07c909f · Browse files · 3 files+87 added−14 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+87 added−14 removed

  • tests:+59 added−0 removed
  • other:+28 added−14 removed

3 files+87 added−14 removed

modified:src/click/termui.py+26 added-14 removed
568 unmodified lines
569 echo("\033[2J\033[1;1H", nl=False)570571572def _interpret_color(color: int | tuple[int, int, int] | str, offset: int = 0) -> str:573 if isinstance(color, int):574 return f"{38 + offset};5;{color:d}"573 """Interprets a color value and returns the corresponding ANSI code."""574 if isinstance(color, str) and color in _ansi_colors:575 return str(_ansi_colors[color] + offset)576576 if isinstance(color, (tuple, list)):577 # bool is an int subclass: without the exclusion, True and False would578 # silently render as the palette indices 1 and 0.579 elif isinstance(color, int) and not isinstance(color, bool):580 if 0 <= color <= 255:581 return f"{38 + offset};5;{color:d}"582583 elif (584 isinstance(color, (tuple, list))585 and len(color) == 3586 and all(587 isinstance(c, int) and not isinstance(c, bool) and 0 <= c <= 255588 for c in color589 )590 ):591 r, g, b = color592 return f"{38 + offset};2;{r:d};{g:d};{b:d}"593580 return str(_ansi_colors[color] + offset)594 raise ValueError(_("Unknown color {colour!r}").format(colour=color))595596597def style(598 text: t.Any,
69 unmodified lines
668 :param reset: by default a reset-all code is added at the end of the669 string which means that styles do not carry over. This670 can be disabled to compose styles.671672 .. versionchanged:: 8.5673 All invalid color values raise :exc:`ValueError`. 256-color index674 ``0`` is not ignored675676 .. versionchanged:: 8.0677 A non-string ``message`` is converted to a string.678679 .. versionchanged:: 8.0
12 unmodified lines
692 text = str(text)693694 bits = []695678 if fg:679 try:680 bits.append(f"\033[{_interpret_color(fg)}m")681 except KeyError:682 raise TypeError(_("Unknown color {colour!r}").format(colour=fg)) from None696 if fg is not None:697 bits.append(f"\033[{_interpret_color(fg)}m")698684 if bg:685 try:686 bits.append(f"\033[{_interpret_color(bg, 10)}m")687 except KeyError:688 raise TypeError(_("Unknown color {colour!r}").format(colour=bg)) from None699 if bg is not None:700 bits.append(f"\033[{_interpret_color(bg, 10)}m")701702 if bold is not None:703 bits.append(f"\033[{1 if bold else 22}m")704 if dim is not None:
256 unmodified lines
modified:tests/test_utils/test_style.py+59 added
4 unmodified lines
56@pytest.mark.parametrize(7 ("styles", "ref"),8 [9 ({}, "x y\x1b[0m"),10 ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),11 ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),12 ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),13 ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),14 ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),15 ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),16 ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),17 ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),18 ({"fg": "bright_black"}, "\x1b[90mx y\x1b[0m"),19 ({"fg": "bright_red"}, "\x1b[91mx y\x1b[0m"),20 ({"fg": "bright_green"}, "\x1b[92mx y\x1b[0m"),21 ({"fg": "bright_yellow"}, "\x1b[93mx y\x1b[0m"),22 ({"fg": "bright_blue"}, "\x1b[94mx y\x1b[0m"),23 ({"fg": "bright_magenta"}, "\x1b[95mx y\x1b[0m"),24 ({"fg": "bright_cyan"}, "\x1b[96mx y\x1b[0m"),25 ({"fg": "bright_white"}, "\x1b[97mx y\x1b[0m"),26 ({"fg": "reset"}, "\x1b[39mx y\x1b[0m"),27 ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),28 ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),29 ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),30 ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),31 ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),32 ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),33 ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),34 ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),35 ({"bg": "bright_black"}, "\x1b[100mx y\x1b[0m"),36 ({"bg": "bright_red"}, "\x1b[101mx y\x1b[0m"),37 ({"bg": "bright_green"}, "\x1b[102mx y\x1b[0m"),38 ({"bg": "bright_yellow"}, "\x1b[103mx y\x1b[0m"),39 ({"bg": "bright_blue"}, "\x1b[104mx y\x1b[0m"),40 ({"bg": "bright_magenta"}, "\x1b[105mx y\x1b[0m"),41 ({"bg": "bright_cyan"}, "\x1b[106mx y\x1b[0m"),42 ({"bg": "bright_white"}, "\x1b[107mx y\x1b[0m"),43 ({"bg": "reset"}, "\x1b[49mx y\x1b[0m"),44 ({"fg": 91}, "\x1b[38;5;91mx y\x1b[0m"),45 ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"),46 ({"fg": 255}, "\x1b[38;5;255mx y\x1b[0m"),47 ({"bg": 255}, "\x1b[48;5;255mx y\x1b[0m"),48 ({"fg": (135, 0, 175)}, "\x1b[38;2;135;0;175mx y\x1b[0m"),49 ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"),50 ({"bg": [135, 0, 175]}, "\x1b[48;2;135;0;175mx y\x1b[0m"),51 ({"fg": (0, 0, 0)}, "\x1b[38;2;0;0;0mx y\x1b[0m"),52 ({"fg": (255, 255, 255)}, "\x1b[38;2;255;255;255mx y\x1b[0m"),53 # 256-color index 0 (black) is valid and must not be dropped by a54 # truthiness check on fg/bg.55 ({"fg": 0}, "\x1b[38;5;0mx y\x1b[0m"),56 ({"bg": 0}, "\x1b[48;5;0mx y\x1b[0m"),57 ({"bold": True}, "\x1b[1mx y\x1b[0m"),58 ({"dim": True}, "\x1b[2mx y\x1b[0m"),59 ({"underline": True}, "\x1b[4mx y\x1b[0m"),60 ({"overline": True}, "\x1b[53mx y\x1b[0m"),
16 unmodified lines
77 assert click.style("x y", **styles) == ref78 assert click.unstyle(ref) == "x y"798081@pytest.mark.parametrize("param", ["fg", "bg"])82@pytest.mark.parametrize(83 "value",84 [85 "",86 "banana",87 "BLACK",88 b"red",89 True,90 False,91 -1,92 256,93 0.0,94 (),95 [],96 (0, 0),97 (0, 0, 0, 0),98 ("0", "0", "0"),99 (True, False, True),100 (-1, 0, 0),101 (0, 256, 0),102 (0.0, 0.0, 0.0),103 ],104)105def test_styling_invalid_color(param, value):106 with pytest.raises(ValueError, match="Unknown color"):107 click.style("x y", **{param: value})108109110@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])111def test_unstyle_other_ansi(text, expect):112 assert click.unstyle(text) == expect
modified:CHANGES.md+2 added
13 unmodified lines
14- Add {func}`custom_version_option`, a `--version` option whose output is15 produced by a callback, covering cases {func}`version_option` intentionally16 does not. The feature set of {func}`version_option` is now frozen; see17 [discussion #3527](https://github.com/pallets/click/discussions/3527). {pr}`3581`18- `style()` and `secho()` no longer silently drop the 256-color index `0`19 (black) passed as `fg` or `bg`, and now validate color arguments. {pr}`3677`2021## Version 8.4.22223Released 2026-06-24
1561 unmodified lines