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.

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