You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
2.2 KiB

  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, time, difflib, optparse
  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. usage = "usage: %prog [options] fromfile tofile"
  16. parser = optparse.OptionParser(usage)
  17. parser.add_option("-c", action="store_true", default=False, help='Produce a context format diff (default)')
  18. parser.add_option("-u", action="store_true", default=False, help='Produce a unified format diff')
  19. parser.add_option("-m", action="store_true", default=False, help='Produce HTML side by side diff (can use -c and -l in conjunction)')
  20. parser.add_option("-n", action="store_true", default=False, help='Produce a ndiff format diff')
  21. parser.add_option("-l", "--lines", type="int", default=3, help='Set number of context lines (default 3)')
  22. (options, args) = parser.parse_args()
  23. if len(args) == 0:
  24. parser.print_help()
  25. sys.exit(1)
  26. if len(args) != 2:
  27. parser.error("need to specify both a fromfile and tofile")
  28. n = options.lines
  29. fromfile, tofile = args
  30. fromdate = file_mtime(fromfile)
  31. todate = file_mtime(tofile)
  32. with open(fromfile, 'U') as ff:
  33. fromlines = ff.readlines()
  34. with open(tofile, 'U') as tf:
  35. tolines = tf.readlines()
  36. if options.u:
  37. diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
  38. elif options.n:
  39. diff = difflib.ndiff(fromlines, tolines)
  40. elif options.m:
  41. diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile,tofile,context=options.c,numlines=n)
  42. else:
  43. diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
  44. sys.stdout.writelines(diff)
  45. if __name__ == '__main__':
  46. main()