From 36d6768f6a54d290e71fbee78293210322b78d3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 7 Feb 2022 10:37:12 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Fix=20clean=5Fansi's=20unicode?= =?UTF-8?q?=20compatibility?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #4392 --- src/octoprint/util/commandline.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/octoprint/util/commandline.py b/src/octoprint/util/commandline.py index 24e17bd9d..729d2ff1d 100644 --- a/src/octoprint/util/commandline.py +++ b/src/octoprint/util/commandline.py @@ -31,7 +31,12 @@ _ANSI_CSI_PATTERN = ( b"\001?\033\\[(\\??(?:\\d|;)*)([a-zA-Z])\002?" # Control Sequence Introducer ) _ANSI_OSC_PATTERN = b"\001?\033\\]((?:.|;)*?)(\x07)\002?" # Operating System Command -_ANSI_REGEX = re.compile(b"|".join([_ANSI_CSI_PATTERN, _ANSI_OSC_PATTERN])) +_ANSI_PATTERN = b"|".join([_ANSI_CSI_PATTERN, _ANSI_OSC_PATTERN]) + +_ANSI_REGEX = { + "bytes": re.compile(_ANSI_PATTERN), + "unicode": re.compile(_ANSI_PATTERN.decode("utf-8")), +} def clean_ansi(line): @@ -52,10 +57,13 @@ def clean_ansi(line): >>> text = b"We \x1b[?25lhide the cursor here and then \x1b[?25hshow it again here" >>> clean_ansi(text) # doctest: +ALLOW_BYTES 'We hide the cursor here and then show it again here' + >>> text = "We \x1b[?25lhide the cursor here and then \x1b[?25hshow it again here in unicode" + >>> clean_ansi(text) # doctest: +ALLOW_BYTES + 'We hide the cursor here and then show it again here in unicode' """ if isinstance(line, unicode): - return _ANSI_REGEX.sub(b"", line.encode("latin1")).decode("latin1") - return _ANSI_REGEX.sub(b"", line) + return _ANSI_REGEX["unicode"].sub("", line) + return _ANSI_REGEX["bytes"].sub(b"", line) class CommandlineError(Exception):