summaryrefslogtreecommitdiff
path: root/python
diff options
context:
space:
mode:
authorDouglas Bagnall <douglas.bagnall@catalyst.net.nz>2022-01-20 12:32:48 +1300
committerDouglas Bagnall <dbagnall@samba.org>2022-09-06 21:12:36 +0000
commita45c76b5cd95ada77905ed5cfc979c5523c84160 (patch)
treeca00486a6690650980178ac54d81c5f39e85a7d4 /python
parent37f92c6cc69b220439aef0c687c92a8e6baeb211 (diff)
downloadsamba-a45c76b5cd95ada77905ed5cfc979c5523c84160.tar.gz
samba-a45c76b5cd95ada77905ed5cfc979c5523c84160.tar.bz2
samba-a45c76b5cd95ada77905ed5cfc979c5523c84160.zip
python/colour: helper functions to read all signs
The accepted hints are presumably arguments to --color. We follow the behaviour of `ls` in what we accept. `git` is stricter, accepting only {always,never,auto}. `grep` is looser accepting mixed case variants. historically we have used {yes,no,auto}. Signed-off-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz> Reviewed-by: Andrew Bartlett <abartlet@samba.org> Reviewed-by: Joseph Sutton <josephsutton@catalyst.net.nz>
Diffstat (limited to 'python')
-rw-r--r--python/samba/colour.py38
1 files changed, 38 insertions, 0 deletions
diff --git a/python/samba/colour.py b/python/samba/colour.py
index 92af2fdef80..448b456b465 100644
--- a/python/samba/colour.py
+++ b/python/samba/colour.py
@@ -88,3 +88,41 @@ def xterm_256_colour(n, bg=False, bold=False):
target = '48' if bg else '38'
return "\033[%s%s;5;%dm" % (weight, target, int(n))
+
+
+def is_colour_wanted(stream, hint='auto'):
+ """The hint is presumably a --color argument.
+
+ We follow the behaviour of GNU `ls` in what we accept.
+ * `git` is stricter, accepting only {always,never,auto}.
+ * `grep` is looser, accepting mixed case variants.
+ * historically we have used {yes,no,auto}.
+ * {always,never,auto} appears the commonest convention.
+ * if the caller tries to opt out of choosing and sets hint to None
+ or '', we assume 'auto'.
+ """
+ if hint in ('no', 'never', 'none'):
+ return False
+
+ if hint in ('yes', 'always', 'force'):
+ return True
+
+ if hint not in ('auto', 'tty', 'if-tty', None, ''):
+ raise ValueError("unexpected colour hint: {hint}; "
+ "try always|never|auto")
+
+ from os import environ
+ if environ.get('NO_COLOR'):
+ # Note: per spec, we treat the empty string as if unset.
+ return False
+
+ if (hasattr(stream, 'isatty') and stream.isatty()):
+ return True
+ return False
+
+
+def colour_if_wanted(stream, hint='auto'):
+ if is_colour_wanted(stream, hint):
+ switch_colour_on()
+ else:
+ switch_colour_off()