diff.py revision a33d17758974e0d150cc07a22c0c60b1485d0ab4
1""" Command line interface to difflib.py providing diffs in three formats: 2 3* ndiff: lists every line and highlights interline changes. 4* context: highlights clusters of changes in a before/after format 5* unified: highlights clusters of changes in an inline format. 6 7""" 8 9import sys, os, time, difflib, optparse 10 11usage = "usage: %prog [options] fromfile tofile" 12parser = optparse.OptionParser(usage) 13parser.add_option("-c", action="store_true", default=False, help='Produce a context format diff (default)') 14parser.add_option("-u", action="store_true", default=False, help='Produce a unified format diff') 15parser.add_option("-n", action="store_true", default=False, help='Produce a ndiff format diff') 16parser.add_option("-l", "--lines", type="int", default=3, help='Set number of context lines (default 3)') 17(options, args) = parser.parse_args() 18 19if len(args) == 0: 20 parser.print_help() 21 sys.exit(1) 22if len(args) != 2: 23 parser.error("need to specify both a fromfile and tofile") 24 25n = options.lines 26fromfile, tofile = args 27 28fromdate = time.ctime(os.stat(fromfile).st_mtime) 29todate = time.ctime(os.stat(tofile).st_mtime) 30fromlines = open(fromfile).readlines() 31tolines = open(tofile).readlines() 32 33if options.u: 34 diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n) 35elif options.n: 36 diff = difflib.ndiff(fromlines, tolines) 37else: 38 diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n) 39 40sys.stdout.writelines(diff) 41 42