summaryrefslogtreecommitdiffstats
path: root/src/ansiblelint/text.py
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-13 12:06:49 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-13 12:06:49 +0000
commit2fe34b6444502079dc0b84365ce82dbc92de308e (patch)
tree8fedcab52bbbc3db6c5aa909a88a7a7b81685018 /src/ansiblelint/text.py
parentInitial commit. (diff)
downloadansible-lint-2fe34b6444502079dc0b84365ce82dbc92de308e.tar.xz
ansible-lint-2fe34b6444502079dc0b84365ce82dbc92de308e.zip
Adding upstream version 6.17.2.upstream/6.17.2
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/ansiblelint/text.py')
-rw-r--r--src/ansiblelint/text.py49
1 files changed, 49 insertions, 0 deletions
diff --git a/src/ansiblelint/text.py b/src/ansiblelint/text.py
new file mode 100644
index 0000000..038fde1
--- /dev/null
+++ b/src/ansiblelint/text.py
@@ -0,0 +1,49 @@
+"""Text utils."""
+from __future__ import annotations
+
+import re
+from functools import cache
+
+RE_HAS_JINJA = re.compile(r"{[{%#].*[%#}]}", re.DOTALL)
+RE_HAS_GLOB = re.compile("[][*?]")
+
+
+def strip_ansi_escape(data: str | bytes) -> str:
+ """Remove all ANSI escapes from string or bytes.
+
+ If bytes is passed instead of string, it will be converted to string
+ using UTF-8.
+ """
+ if isinstance(data, bytes): # pragma: no branch
+ data = data.decode("utf-8")
+
+ return re.sub(r"\x1b[^m]*m", "", data)
+
+
+def toidentifier(text: str) -> str:
+ """Convert unsafe chars to ones allowed in variables."""
+ result = re.sub(r"[\s-]+", "_", text)
+ if not result.isidentifier():
+ msg = f"Unable to convert role name '{text}' to valid variable name."
+ raise RuntimeError(msg)
+ return result
+
+
+# https://www.python.org/dev/peps/pep-0616/
+def removeprefix(self: str, prefix: str) -> str:
+ """Remove prefix from string."""
+ if self.startswith(prefix):
+ return self[len(prefix) :]
+ return self[:]
+
+
+@cache
+def has_jinja(value: str) -> bool:
+ """Return true if a string seems to contain jinja templating."""
+ return bool(isinstance(value, str) and RE_HAS_JINJA.search(value))
+
+
+@cache
+def has_glob(value: str) -> bool:
+ """Return true if a string looks like having a glob pattern."""
+ return bool(isinstance(value, str) and RE_HAS_GLOB.search(value))