| 1 |
""" Command-line interface to difflib.py providing diffs in four 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 |
* html: generates side by side comparison with change highlights. |
| 7 |
|
| 8 |
""" |
| 9 |
|
| 10 |
import sys, os, difflib, argparse |
| 11 |
import datetime as dt |
| 12 |
|
| 13 |
def file_mtime(path): |
| 14 |
t = dt.datetime.fromtimestamp(os.stat(path).st_mtime, |
| 15 |
dt.timezone.utc) |
| 16 |
return t.astimezone().isoformat() |
| 17 |
|
| 18 |
def main(): |
| 19 |
|
| 20 |
parser = argparse.ArgumentParser() |
| 21 |
parser.add_argument('-c', action='store_true', default=False, |
| 22 |
help='Produce a context format diff (default)') |
| 23 |
parser.add_argument('-u', action='store_true', default=False, |
| 24 |
help='Produce a unified format diff') |
| 25 |
parser.add_argument('-m', action='store_true', default=False, |
| 26 |
help='Produce HTML side by side diff ' |
| 27 |
'(can use -c and -l in conjunction)') |
| 28 |
parser.add_argument('-n', action='store_true', default=False, |
| 29 |
help='Produce a ndiff format diff') |
| 30 |
parser.add_argument('-l', '--lines', type=int, default=3, |
| 31 |
help='Set number of context lines (default 3)') |
| 32 |
parser.add_argument('fromfile') |
| 33 |
parser.add_argument('tofile') |
| 34 |
options = parser.parse_args() |
| 35 |
|
| 36 |
n = options.lines |
| 37 |
fromfile = options.fromfile |
| 38 |
tofile = options.tofile |
| 39 |
|
| 40 |
fromdate = file_mtime(fromfile) |
| 41 |
todate = file_mtime(tofile) |
| 42 |
with open(fromfile) as ff: |
| 43 |
fromlines = ff.readlines() |
| 44 |
with open(tofile) as tf: |
| 45 |
tolines = tf.readlines() |
| 46 |
|
| 47 |
if options.u: |
| 48 |
diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n) |
| 49 |
elif options.n: |
| 50 |
diff = difflib.ndiff(fromlines, tolines) |
| 51 |
elif options.m: |
| 52 |
diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile,tofile,context=options.c,numlines=n) |
| 53 |
else: |
| 54 |
diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n) |
| 55 |
|
| 56 |
sys.stdout.writelines(diff) |
| 57 |
|
| 58 |
if __name__ == '__main__': |
| 59 |
main() |