Skip to content

Instantly share code, notes, and snippets.

@wh13371
Created February 17, 2015 16:55
Show Gist options
  • Save wh13371/1fe2d68d2202fd3d6bcd to your computer and use it in GitHub Desktop.
Save wh13371/1fe2d68d2202fd3d6bcd to your computer and use it in GitHub Desktop.
python diff util
#! /usr/bin/python
import sys, os, time, difflib, optparse
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
CYAN = '\033[96m'
WHITE = '\033[97m'
DGREEN = '\033[98m'
GREY = '\033[90m'
END = '\033[0m'
BOLD = "\033[1m"
def colorize(text, color=RED):
return BOLD + color + text + END
def main():
usage = "usage: %prog [options] file1 file2"
parser = optparse.OptionParser(usage)
parser.add_option("-c", action="store_true", default=False, help='context')
parser.add_option("-u", action="store_true", default=False, help='unified (DEFAULT)')
parser.add_option("-m", action="store_true", default=False, help='HTML')
parser.add_option("-n", action="store_true", default=False, help='ndiff')
parser.add_option("-l", "--lines", type="int", default = 0, help='# of context lines')
parser.add_option("-v", "--verbose", action="store_true")
(options, args) = parser.parse_args()
if len(args) != 2: parser.print_help(); sys.exit(58)
n = options.lines
_v = options.verbose
fromfile, tofile = args
if _v: print colorize("--- %s:%s" % (fromfile, os.path.getsize(fromfile)), RED)
if _v: print colorize("+++ %s:%s" % (tofile, os.path.getsize(tofile)), BLUE)
fromdate = time.ctime(os.stat(fromfile).st_mtime)
todate = time.ctime(os.stat(tofile).st_mtime)
fromlines = open(fromfile, 'U').readlines()
tolines = open(tofile, 'U').readlines()
if options.n:
diff = difflib.ndiff(fromlines, tolines)
elif options.m:
diff = difflib.HtmlDiff().make_file(fromlines, tolines, fromfile, tofile, context=options.c, numlines=n) # HTML
elif options.c:
diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
else:
diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n) # DEFAULT
if options.m:
sys.stdout.writelines(diff) # HTML output i.e. "./diff.py -mc 1.cfg 2.cfg > fizz.html"
else:
for l in diff:
l = l.strip()
if l.startswith("?") or l.startswith("*****"):
print colorize(l, YELLOW)
elif l.startswith("-"):
print colorize(l, RED)
elif l.startswith("@@ ") or l.startswith("*** "):
print colorize(l, DGREEN)
elif l.startswith("+") or l.startswith("!"):
print colorize(l, CYAN)
elif l.startswith("/"):
print colorize(l, WHITE)
else:
print l
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment