diff.py 2.2 KB

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