/Tools/scripts/diff.py

http://unladen-swallow.googlecode.com/ · Python · 49 lines · 32 code · 9 blank · 8 comment · 7 complexity · 6938cf1d2faa3c341502d133ea068b64 MD5 · raw file

  1. """ Command line interface to difflib.py providing diffs in four formats:
  2. * ndiff: lists every line and highlights interline changes.
  3. * context: highlights clusters of changes in a before/after format.
  4. * unified: highlights clusters of changes in an inline format.
  5. * html: generates side by side comparison with change highlights.
  6. """
  7. import sys, os, time, difflib, optparse
  8. def main():
  9. usage = "usage: %prog [options] fromfile tofile"
  10. parser = optparse.OptionParser(usage)
  11. parser.add_option("-c", action="store_true", default=False, help='Produce a context format diff (default)')
  12. parser.add_option("-u", action="store_true", default=False, help='Produce a unified format diff')
  13. parser.add_option("-m", action="store_true", default=False, help='Produce HTML side by side diff (can use -c and -l in conjunction)')
  14. parser.add_option("-n", action="store_true", default=False, help='Produce a ndiff format diff')
  15. parser.add_option("-l", "--lines", type="int", default=3, help='Set number of context lines (default 3)')
  16. (options, args) = parser.parse_args()
  17. if len(args) == 0:
  18. parser.print_help()
  19. sys.exit(1)
  20. if len(args) != 2:
  21. parser.error("need to specify both a fromfile and tofile")
  22. n = options.lines
  23. fromfile, tofile = args
  24. fromdate = time.ctime(os.stat(fromfile).st_mtime)
  25. todate = time.ctime(os.stat(tofile).st_mtime)
  26. fromlines = open(fromfile, 'U').readlines()
  27. tolines = open(tofile, 'U').readlines()
  28. if options.u:
  29. diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
  30. elif options.n:
  31. diff = difflib.ndiff(fromlines, tolines)
  32. elif options.m:
  33. diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile,tofile,context=options.c,numlines=n)
  34. else:
  35. diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
  36. sys.stdout.writelines(diff)
  37. if __name__ == '__main__':
  38. main()