Skip to content

Instantly share code, notes, and snippets.

@fjkz
Created October 8, 2016 04:26
Show Gist options
  • Save fjkz/ed43cce267be6788e7e36e992fe0397a to your computer and use it in GitHub Desktop.
Save fjkz/ed43cce267be6788e7e36e992fe0397a to your computer and use it in GitHub Desktop.
Git interface to Python difflib module
#!/usr/bin/env python3
"""
Git interface to difflib.py
"""
import sys
import os
import time
import difflib
import re
_, path, oldfile, oldhex, oldmode, newfile, newhex, newmode = sys.argv
oldname = 'a/' + path
newname = 'b/' + path
if oldmode == '.':
oldname = '/dev/null'
if newmode == '.':
newname = '/dev/null'
with open(oldfile) as ff:
oldlines = ff.readlines()
with open(newfile) as tf:
newlines = tf.readlines()
diff_lines = difflib.unified_diff(oldlines, newlines, oldname, newname)
rerange = re.compile('^@@ -.* \+.* @@')
redel = re.compile(r'^-')
readd = re.compile(r'^\+')
reold = re.compile(r'^--- ')
renew = re.compile(r'^\+\+\+ ')
red ='\033[91m'
green = '\033[92m'
yellow = '\033[93m'
blue = '\033[94m'
end = '\033[0m'
def color_lines():
for line in diff_lines:
line = line.rstrip('\r\n')
if redel.match(line) and not reold.match(line):
yield red + line + end + '\n'
elif readd.match(line) and not renew.match(line):
yield green + line + end + '\n'
elif rerange.match(line):
yield blue + line + end + '\n'
else:
yield line + '\n'
# Always color output
sys.stdout.writelines(color_lines())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment