1"""Text utils.""" 2import re 3from typing import Union 4 5 6def strip_ansi_escape(data: Union[str, bytes]) -> str: 7 """Remove all ANSI escapes from string or bytes. 8 9 If bytes is passed instead of string, it will be converted to string 10 using UTF-8. 11 """ 12 if isinstance(data, bytes): 13 data = data.decode("utf-8") 14 15 return re.sub(r"\x1b[^m]*m", "", data) 16 17 18def toidentifier(text: str) -> str: 19 """Convert unsafe chars to ones allowed in variables.""" 20 result = re.sub(r"[\s-]+", '_', text) 21 if not result.isidentifier: 22 raise RuntimeError( 23 "Unable to convert role name '%s' to valid variable name." % text 24 ) 25 return result 26 27 28# https://www.python.org/dev/peps/pep-0616/ 29def removeprefix(self: str, prefix: str) -> str: 30 """Remove prefix from string.""" 31 if self.startswith(prefix): 32 return self[len(prefix) :] 33 return self[:] 34