]> git.ipfire.org Git - thirdparty/samba.git/commitdiff
python/colour: add a colour diff helper
authorDouglas Bagnall <douglas.bagnall@catalyst.net.nz>
Thu, 17 Aug 2023 02:20:12 +0000 (14:20 +1200)
committerAndrew Bartlett <abartlet@samba.org>
Thu, 24 Aug 2023 02:53:31 +0000 (02:53 +0000)
Sometimes colour can help show what is different between two strings.

This is roughly the same as

`git diff --no-index --color-words=. <a> <b>`.

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

index 553e637d3a483cebe32a089aa487dfb4391c7ef1..4a33acc36389263f5615c31cafa5fff41c8b90d8 100644 (file)
@@ -141,3 +141,35 @@ def colour_if_wanted(*streams, hint='auto'):
     else:
         switch_colour_off()
     return wanted
+
+
+def colourdiff(a, b):
+    """Generate a string comparing two strings or byte sequences, with
+    differences coloured to indicate what changed.
+
+    Byte sequences are printed as hex pairs separated by colons.
+    """
+    from difflib import SequenceMatcher
+    out = []
+    if isinstance(a, bytes):
+        a = a.hex(':')
+    if isinstance(b, bytes):
+        b = b.hex(':')
+    a = a.replace(' ', '␠')
+    b = b.replace(' ', '␠')
+
+    s = SequenceMatcher(None, a, b)
+    for op, al, ar, bl, br in s.get_opcodes():
+        if op == 'equal':
+            out.append(a[al: ar])
+        elif op == 'delete':
+            out.append(c_RED(a[al: ar]))
+        elif op == 'insert':
+            out.append(c_GREEN(b[bl: br]))
+        elif op == 'replace':
+            out.append(c_RED(a[al: ar]))
+            out.append(c_GREEN(b[bl: br]))
+        else:
+            out.append(f' --unknown diff op {op}!-- ')
+
+    return ''.join(out)