samba-tool: write ERROR in red if colour is wanted
authorDouglas Bagnall <douglas.bagnall@catalyst.net.nz>
Fri, 9 Sep 2022 03:08:30 +0000 (15:08 +1200)
committerAndrew Bartlett <abartlet@samba.org>
Fri, 16 Sep 2022 05:46:36 +0000 (05:46 +0000)
Often we'll write something like

   ERROR: Unable to find user "potato"

which can get lost in the jumble of other output. With this patch, we
colour the word "ERROR" red but not the rest of the string, unless it is
determined that colour is not wanted (due to one of --color=never,
NO_COLOR=1, output is not a tty).

We choose to redden the word "ERROR" only to maintain legibility in the
actual message, while hopefully increasing the noticeability of the line.

Signed-off-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz>
Reviewed-by: Andrew Bartlett <abartlet@samba.org>
python/samba/netcmd/__init__.py

index 98ead7c675b62de4fb1ff3c466a8c158915ee07a..31bce8fc1abc52fa65da6ba73852267068d7deb3 100644 (file)
@@ -104,6 +104,15 @@ class Command(object):
         parser, _ = self._create_parser(prog)
         parser.print_usage()
 
+    def _print_error(self, msg, evalue=None, klass=None):
+        err = colour.c_DARK_RED("ERROR")
+        klass = '' if klass is None else f'({klass})'
+
+        if evalue is None:
+            print(f"{err}{klass}: {msg}", file=self.errf)
+        else:
+            print(f"{err}{klass}: {msg} - {evalue}", file=self.errf)
+
     def show_command_error(self, e):
         '''display a command error'''
         if isinstance(e, CommandError):
@@ -131,19 +140,19 @@ class Command(object):
                 print("Could not reach remote server", file=self.errf)
                 force_traceback = False
             else:
-                self.errf.write("ERROR(ldb): %s - %s\n" % (message, ldb_emsg))
+                self._print_error(message, ldb_emsg, 'ldb')
         elif isinstance(inner_exception, AssertionError):
-            self.errf.write("ERROR(assert): %s\n" % message)
+            self._print_error(message, klass='assert')
             force_traceback = True
         elif isinstance(inner_exception, RuntimeError):
-            self.errf.write("ERROR(runtime): %s - %s\n" % (message, evalue))
+            self._print_error(message, evalue, 'runtime')
         elif type(inner_exception) is Exception:
-            self.errf.write("ERROR(exception): %s - %s\n" % (message, evalue))
+            self._print_error(message, evalue, 'exception')
             force_traceback = True
         elif inner_exception is None:
-            self.errf.write("ERROR: %s\n" % (message))
+            self._print_error(message)
         else:
-            self.errf.write("ERROR(%s): %s - %s\n" % (str(etype), message, evalue))
+            self._print_error(message, evalue, str(etype))
 
         if force_traceback or samba.get_debug_level() >= 3:
             traceback.print_tb(etraceback, file=self.errf)