_diffcommand.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import optparse
  2. import sys
  3. import re
  4. import os
  5. from .diff import htmldiff
  6. description = """\
  7. """
  8. parser = optparse.OptionParser(
  9. usage="%prog [OPTIONS] FILE1 FILE2\n"
  10. "%prog --annotate [OPTIONS] INFO1 FILE1 INFO2 FILE2 ...",
  11. description=description,
  12. )
  13. parser.add_option(
  14. '-o', '--output',
  15. metavar="FILE",
  16. dest="output",
  17. default="-",
  18. help="File to write the difference to",
  19. )
  20. parser.add_option(
  21. '-a', '--annotation',
  22. action="store_true",
  23. dest="annotation",
  24. help="Do an annotation")
  25. def main(args=None):
  26. if args is None:
  27. args = sys.argv[1:]
  28. options, args = parser.parse_args(args)
  29. if options.annotation:
  30. return annotate(options, args)
  31. if len(args) != 2:
  32. print('Error: you must give two files')
  33. parser.print_help()
  34. sys.exit(1)
  35. file1, file2 = args
  36. input1 = read_file(file1)
  37. input2 = read_file(file2)
  38. body1 = split_body(input1)[1]
  39. pre, body2, post = split_body(input2)
  40. result = htmldiff(body1, body2)
  41. result = pre + result + post
  42. if options.output == '-':
  43. if not result.endswith('\n'):
  44. result += '\n'
  45. sys.stdout.write(result)
  46. else:
  47. with open(options.output, 'wb') as f:
  48. f.write(result)
  49. def read_file(filename):
  50. if filename == '-':
  51. c = sys.stdin.read()
  52. elif not os.path.exists(filename):
  53. raise OSError(
  54. "Input file %s does not exist" % filename)
  55. else:
  56. with open(filename, 'rb') as f:
  57. c = f.read()
  58. return c
  59. body_start_re = re.compile(
  60. r"<body.*?>", re.I|re.S)
  61. body_end_re = re.compile(
  62. r"</body.*?>", re.I|re.S)
  63. def split_body(html):
  64. pre = post = ''
  65. match = body_start_re.search(html)
  66. if match:
  67. pre = html[:match.end()]
  68. html = html[match.end():]
  69. match = body_end_re.search(html)
  70. if match:
  71. post = html[match.start():]
  72. html = html[:match.start()]
  73. return pre, html, post
  74. def annotate(options, args):
  75. print("Not yet implemented")
  76. sys.exit(1)