blob: ecbff613930d5403649014c31212235cbb78bcf9 [file] [log] [blame]
Raymond Hettingera33d1772003-06-08 23:04:17 +00001""" 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
Andrew M. Kuchlinge236b382004-08-09 17:27:55 +000011def main():
Raymond Hettingera33d1772003-06-08 23:04:17 +000012
Andrew M. Kuchlinge236b382004-08-09 17:27:55 +000013 usage = "usage: %prog [options] fromfile tofile"
14 parser = optparse.OptionParser(usage)
15 parser.add_option("-c", action="store_true", default=False, help='Produce a context format diff (default)')
16 parser.add_option("-u", action="store_true", default=False, help='Produce a unified format diff')
17 parser.add_option("-n", action="store_true", default=False, help='Produce a ndiff format diff')
18 parser.add_option("-l", "--lines", type="int", default=3, help='Set number of context lines (default 3)')
19 (options, args) = parser.parse_args()
Raymond Hettingera33d1772003-06-08 23:04:17 +000020
Andrew M. Kuchlinge236b382004-08-09 17:27:55 +000021 if len(args) == 0:
22 parser.print_help()
23 sys.exit(1)
24 if len(args) != 2:
25 parser.error("need to specify both a fromfile and tofile")
Raymond Hettingera33d1772003-06-08 23:04:17 +000026
Andrew M. Kuchlinge236b382004-08-09 17:27:55 +000027 n = options.lines
28 fromfile, tofile = args
Raymond Hettingera33d1772003-06-08 23:04:17 +000029
Andrew M. Kuchlinge236b382004-08-09 17:27:55 +000030 fromdate = time.ctime(os.stat(fromfile).st_mtime)
31 todate = time.ctime(os.stat(tofile).st_mtime)
32 fromlines = open(fromfile).readlines()
33 tolines = open(tofile).readlines()
Raymond Hettingera33d1772003-06-08 23:04:17 +000034
Andrew M. Kuchlinge236b382004-08-09 17:27:55 +000035 if options.u:
36 diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
37 elif options.n:
38 diff = difflib.ndiff(fromlines, tolines)
39 else:
40 diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
41
42 sys.stdout.writelines(diff)
43
44if __name__ == '__main__':
45 main()