From: Douglas Bagnall Date: Thu, 17 Aug 2023 02:20:12 +0000 (+1200) Subject: python/colour: add a colour diff helper X-Git-Tag: tevent-0.16.0~812 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=f58372cca5b59a5d4ed653ef53e69ea756940a68;p=thirdparty%2Fsamba.git python/colour: add a colour diff helper Sometimes colour can help show what is different between two strings. This is roughly the same as `git diff --no-index --color-words=. `. Signed-off-by: Douglas Bagnall Reviewed-by: Andrew Bartlett --- diff --git a/python/samba/colour.py b/python/samba/colour.py index 553e637d3a4..4a33acc3638 100644 --- a/python/samba/colour.py +++ b/python/samba/colour.py @@ -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)