]> git.ipfire.org Git - thirdparty/samba.git/commitdiff
python/colour: helper functions to read all signs
authorDouglas Bagnall <douglas.bagnall@catalyst.net.nz>
Wed, 19 Jan 2022 23:32:48 +0000 (12:32 +1300)
committerDouglas Bagnall <dbagnall@samba.org>
Tue, 6 Sep 2022 21:12:36 +0000 (21:12 +0000)
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>
python/samba/colour.py

index 92af2fdef80a5e63bcd5512593fb5f9ed510b764..448b456b4656c7e4e10d4b5155e8af436b72fb50 100644 (file)
@@ -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()