Strip all ANSI sequences
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kevin Deldycke · committed by Kevin Deldycke · parent 8a4ce84 · Browse files · 5 files·+254 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+254 added−2 removed
- tests:+247 added−1 removed
- other:+7 added−1 removed
Provenance
- Commit
71f2baf- Tree
b1b1b5a- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
8a4ce84
5 files changed+254 added−2 removed
modified:src/click/_compat.py+5 added-1 removed
10 unmodified lines11 from weakref import WeakKeyDictionary12 13 CYGWIN = sys.platform.startswith("cygwin")14 WIN = sys.platform.startswith("win")15+# One CSI escape sequence per the ECMA-48 grammar: parameter bytes (0x30-0x3F),16+# intermediate bytes (0x20-0x2F), then a final byte (0x40-0x7E). Broader than the17+# SGR codes Click emits, so foreign sequences (colon-delimited true-color, mouse18+# reporting) are stripped too.15-_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")19+_ansi_re = re.compile(r"\033\[[0-?]*[ -/]*[@-~]")20 21 22 def _make_text_stream(23 stream: t.BinaryIO,567 unmodified linesmodified:tests/test_utils/test_style.py+16 added-1 removed
105 unmodified lines106 with pytest.raises(ValueError, match="Unknown color"):107 click.style("x y", **{param: value})108 109 110-@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])110+@pytest.mark.parametrize(111+ ("text", "expect"),112+ [113+ ("\x1b[?25lx y\x1b[?25h", "x y"),114+ # Colon-delimited true-color SGR (ISO 8613-6).115+ ("\x1b[38:2:255:0:0mx y\x1b[0m", "x y"),116+ # 256-color with colon sub-parameters.117+ ("\x1b[38:5:200mx y\x1b[0m", "x y"),118+ # SGR mouse reporting.119+ ("\x1b[<0;1;1Mx y\x1b[<0;1;1m", "x y"),120+ # Intermediate byte before the final byte.121+ ("\x1b[0 qx y", "x y"),122+ # Non-letter final byte.123+ ("x\x1b[3~y", "xy"),124+ ],125+)126 def test_unstyle_other_ansi(text, expect):127 assert click.unstyle(text) == expectmodified:tests/test_compat.py+215 added
1 from __future__ import annotations2 3+import re4 import sys5 6 import pytest7 8 import click9+from click._compat import _ansi_re10+from click._compat import strip_ansi11+from click._compat import term_len12+from click._textwrap import _truncate_visible13 14+ESC = "\033"15 16+# Inventory of every escape sequence Click itself emits. ``strip_ansi`` must17+# keep removing all of them.18+CLICK_EMITTED = [19+ # SGR foreground/background, the basic 16 colors.20+ f"{ESC}[30m",21+ f"{ESC}[37m",22+ f"{ESC}[40m",23+ f"{ESC}[47m",24+ # SGR 256-color and true-color (Click renders these with semicolons).25+ f"{ESC}[38;5;200m",26+ f"{ESC}[48;5;91m",27+ f"{ESC}[38;2;255;12;128m",28+ f"{ESC}[48;2;135;0;175m",29+ # SGR attributes and their resets.30+ f"{ESC}[1m",31+ f"{ESC}[22m",32+ f"{ESC}[4m",33+ f"{ESC}[24m",34+ f"{ESC}[53m",35+ f"{ESC}[55m",36+ f"{ESC}[9m",37+ f"{ESC}[29m",38+ # Reset-all appended by style().39+ f"{ESC}[0m",40+ # Screen clear and cursor home from click.clear().41+ f"{ESC}[2J",42+ f"{ESC}[1;1H",43+ # Cursor hide/show around the progress bar.44+ f"{ESC}[?25l",45+ f"{ESC}[?25h",46+]47+48+# CSI sequences Click never emits but may receive from other tooling.49+CSI_FOREIGN = [50+ # Colon-delimited (ISO 8613-6) true-color and 256-color SGR.51+ f"{ESC}[38:2:255:0:0m",52+ f"{ESC}[38:5:200m",53+ f"{ESC}[1;38:2::255:0:0m", # empty colon field is a valid parameter54+ # SGR mouse reporting (the ``<`` parameter byte is 0x3C).55+ f"{ESC}[<0;30;40M",56+ f"{ESC}[<0;30;40m",57+ # Private-mode set/reset with a multi-digit parameter.58+ f"{ESC}[?1049h",59+ f"{ESC}[?1049l",60+ # Cursor-shape select: an intermediate byte (space, 0x20) before final ``q``.61+ f"{ESC}[0 q",62+ f"{ESC}[2 q",63+ # Set scrolling region: a non-``m`` letter final byte.64+ f"{ESC}[1;24r",65+ # Function-key / bracketed-paste codes ending in ``~`` (0x7E).66+ f"{ESC}[3~",67+ f"{ESC}[200~",68+ # Empty parameter list (``ESC [ m`` is a valid reset).69+ f"{ESC}[m",70+]71+72+# The previous pattern, kept here to prove the new one is a superset.73+_LEGACY_ANSI_RE = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")74+75+76 def test_is_jupyter_kernel_output():77 class JupyterKernelFakeStream:78 pass79 38 unmodified lines118 119 if expected_override is not None:120 expected = expected_override121 assert click._compat.should_strip_ansi(stream=stream, color=color) == expected122+123+124+@pytest.mark.parametrize("seq", CLICK_EMITTED + CSI_FOREIGN)125+def test_strip_ansi_removes_full_sequence(seq):126+ """Every complete CSI sequence is stripped, alone or wrapped in text."""127+ assert strip_ansi(seq) == ""128+ assert strip_ansi(f"a{seq}b") == "ab"129+ assert term_len(f"a{seq}b") == 2130+131+132+@pytest.mark.parametrize("final", ["m", "H", "J", "A", "z"])133+@pytest.mark.parametrize("params", ["", "0", "1;2", ";", "?25", "0;0;0"])134+def test_strip_ansi_is_superset_of_legacy(params, final):135+ """Everything the legacy pattern stripped, the CSI grammar still strips."""136+ seq = f"{ESC}[{params}{final}"137+ assert _LEGACY_ANSI_RE.fullmatch(seq) is not None138+ assert strip_ansi(seq) == ""139+ assert strip_ansi(f"a{seq}b") == "ab"140+141+142+@pytest.mark.parametrize(143+ ("text", "expected"),144+ [145+ (f"{ESC}[31mred{ESC}[0m", "red"),146+ (f"a{ESC}[38:2:1:2:3mb{ESC}[0mc", "abc"),147+ (f"{ESC}[?25l{ESC}[2Jhidden{ESC}[?25h", "hidden"),148+ (f"{ESC}[<0;1;1Mclick{ESC}[<0;1;1m", "click"),149+ # Several adjacent sequences around each visible character.150+ (f"{ESC}[1m{ESC}[31mA{ESC}[0m {ESC}[32mB{ESC}[0m", "A B"),151+ # Real terminal captures ported from the boltons strip_ansi tests.152+ # ANSI art fragment (its doctest example).153+ (f"{ESC}[0m{ESC}[1;36mart{ESC}[46;34m\xdc", "art\xdc"),154+ # `ls` color output, ending on a dangling SGR with no text after it.155+ (156+ f"ls\r\n{ESC}[00m{ESC}[01;31mfile.zip{ESC}[00m\r\n{ESC}[01;31m",157+ "ls\r\nfile.zip\r\n",158+ ),159+ # Tab-separated colorized fields.160+ (f"\t{ESC}[0;35mIP{ESC}[0m\t{ESC}[0;36m192.1.0.2{ESC}[0m", "\tIP\t192.1.0.2"),161+ # A styled cell inside a box-drawing table.162+ (163+ f"╒══════╕\n│ {ESC}[1mCell{ESC}[0m │\n╘══════╛",164+ "╒══════╕\n│ Cell │\n╘══════╛",165+ ),166+ # Kaomoji with a bolded run.167+ (f"(╯°□°)╯︵ {ESC}[1m┻━┻{ESC}[0m", "(╯°□°)╯︵ ┻━┻"),168+ ],169+)170+def test_strip_ansi_mixed_content(text, expected):171+ assert strip_ansi(text) == expected172+ assert term_len(text) == len(expected)173+174+175+def test_strip_ansi_stops_at_final_byte():176+ """The match ends at the first final byte."""177+ assert strip_ansi(f"{ESC}[31mX{ESC}[0mY") == "XY"178+ assert strip_ansi(f"{ESC}[1m{ESC}[31mZ") == "Z"179+ # The final ``m`` ends the sequence; the following ``;1m`` is plain text.180+ assert strip_ansi(f"{ESC}[m;1m") == ";1m"181+182+183+@pytest.mark.parametrize(184+ "text",185+ [186+ "",187+ "plain text",188+ "100% [done]",189+ "array[0] = 1",190+ "a;b;c",191+ # Looks like SGR parameters but lacks the ESC introducer.192+ "[38;5;200m not an escape",193+ "[0m",194+ ],195+)196+def test_strip_ansi_leaves_plain_text(text):197+ """Text that merely resembles an escape sequence is never stripped."""198+ assert strip_ansi(text) == text199+ assert term_len(text) == len(text)200+201+202+@pytest.mark.parametrize(203+ "text",204+ [205+ f"{ESC}", # lone ESC206+ f"{ESC}[", # CSI introducer with no final byte207+ f"{ESC}[31", # parameters but no final byte208+ f"{ESC}[38:2:1", # colon parameters, truncated209+ f"{ESC}[0 ", # intermediate byte but no final byte210+ ],211+)212+def test_strip_ansi_leaves_incomplete_sequences(text):213+ """An unterminated sequence (missing its final byte) is left untouched."""214+ assert strip_ansi(text) == text215+216+217+def test_strip_ansi_is_idempotent():218+ text = f"{ESC}[38:2:1:2:3mhi{ESC}[0m {ESC}[<0;1;1mthere{ESC}[?25h"219+ once = strip_ansi(text)220+ assert once == "hi there"221+ assert strip_ansi(once) == once222+223+224+@pytest.mark.parametrize(225+ ("text", "visible"),226+ [227+ ("", 0),228+ ("plain", 5),229+ (f"{ESC}[31mred{ESC}[0m", 3),230+ (f"{ESC}[38;2;1;2;3mrgb{ESC}[0m", 3),231+ (f"{ESC}[38:2:1:2:3mrgb{ESC}[0m", 3),232+ (f"{ESC}[<0;1;1Mx{ESC}[<0;1;1m", 1),233+ (f"{ESC}[0 qq", 1),234+ (f"{ESC}[?25lvisible{ESC}[?25h", 7),235+ (f"{ESC}[1m{ESC}[4m{ESC}[31mhello{ESC}[0m", 5),236+ ],237+)238+def test_term_len(text, visible):239+ assert term_len(text) == visible240+241+242+@pytest.mark.parametrize("seq", CLICK_EMITTED + CSI_FOREIGN)243+def test_ansi_re_matches_whole_sequence(seq):244+ """``_ansi_re`` matches a complete sequence end to end as one token."""245+ m = _ansi_re.match(seq)246+ assert m is not None247+ assert m.start() == 0248+ assert m.end() == len(seq)249+250+251+@pytest.mark.parametrize(252+ ("text", "n", "expected"),253+ [254+ # No escapes: behaves like a plain prefix slice.255+ ("abcdef", 3, "abc"),256+ ("abc", 10, "abc"),257+ ("abc", 0, ""),258+ ("abc", -1, ""),259+ # A leading escape is kept and does not count toward the budget.260+ (f"{ESC}[31mabcdef{ESC}[0m", 3, f"{ESC}[31mabc"),261+ # A colon true-color escape stays intact; the cut lands after 3 chars.262+ (f"{ESC}[38:2:1:2:3mabcdef", 3, f"{ESC}[38:2:1:2:3mabc"),263+ # A trailing escape past the cut is not pulled in.264+ (f"{ESC}[31mabc{ESC}[0m", 3, f"{ESC}[31mabc"),265+ ],266+)267+def test_truncate_visible(text, n, expected):268+ out = _truncate_visible(text, n)269+ assert out == expected270+ assert term_len(out) <= max(n, 0)modified:tests/test_formatting.py+16 added
464 unmodified lines465 5,466 "",467 id="styled-long-word-breaks-on-visible-width",468 ),469+ # Colon-delimited true-color (ISO 8613-6) escapes are excluded from the470+ # width budget too.471+ pytest.param(472+ "\x1b[38:2:255:0:0malpha\x1b[0m \x1b[38:2:0:255:0mbeta\x1b[0m"473+ " \x1b[38:2:0:0:255mgamma\x1b[0m \x1b[38:2:9:9:9mdelta\x1b[0m",474+ 15,475+ "",476+ id="colon-truecolor-body-wraps-on-visible-width",477+ ),478+ # A mouse-reporting sequence embedded mid-line is zero-width too.479+ pytest.param(480+ "\x1b[<0;1;1malpha beta gamma delta\x1b[<0;1;1m",481+ 15,482+ "",483+ id="mouse-sequence-is-zero-width",484+ ),485 ],486 )487 def test_wrap_text_visible_width(body, width, initial_indent):488 """``wrap_text`` of styled input produces the same line layout as144 unmodified linesmodified:CHANGES.md+2 added
15 unmodified lines16 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`20+- `unstyle` and the ANSI handling behind help-text wrapping now strip the full21+ CSI escape-sequence grammar.22 23 ## Version 8.4.224 25 Released 2026-06-241561 unmodified lines