cdiff.py 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import sys
  4. import os
  5. import re
  6. import difflib
  7. COLORS = {
  8. 'reset' : '\x1b[0m',
  9. 'underline' : '\x1b[4m',
  10. 'reverse' : '\x1b[7m',
  11. 'red' : '\x1b[31m',
  12. 'green' : '\x1b[32m',
  13. 'yellow' : '\x1b[33m',
  14. 'blue' : '\x1b[34m',
  15. 'magenta' : '\x1b[35m',
  16. 'cyan' : '\x1b[36m',
  17. 'lightred' : '\x1b[1;31m',
  18. 'lightgreen' : '\x1b[1;32m',
  19. 'lightyellow' : '\x1b[1;33m',
  20. 'lightblue' : '\x1b[1;34m',
  21. 'lightmagenta' : '\x1b[1;35m',
  22. 'lightcyan' : '\x1b[1;36m',
  23. }
  24. def ansi_code(color):
  25. return COLORS.get(color, '')
  26. def colorize(text, start_color, end_color='reset'):
  27. return ansi_code(start_color) + text + ansi_code(end_color)
  28. class Hunk(object):
  29. def __init__(self, hunk_header, old_addr, new_addr):
  30. self._hunk_header = hunk_header
  31. self._old_addr = old_addr # tuple (start, offset)
  32. self._new_addr = new_addr # tuple group (start, offset)
  33. self._hunk_list = [] # list of tuple (attr, line)
  34. def get_header(self):
  35. return self._hunk_header
  36. def get_old_addr(self):
  37. return self._old_addr
  38. def get_new_addr(self):
  39. return self._new_addr
  40. def append(self, attr, line):
  41. """attr: '-': old, '+': new, ' ': common"""
  42. self._hunk_list.append((attr, line))
  43. def mdiff(self):
  44. """The difflib._mdiff() function returns an interator which returns a
  45. tuple: (from line tuple, to line tuple, boolean flag)
  46. from/to line tuple -- (line num, line text)
  47. line num -- integer or None (to indicate a context separation)
  48. line text -- original line text with following markers inserted:
  49. '\0+' -- marks start of added text
  50. '\0-' -- marks start of deleted text
  51. '\0^' -- marks start of changed text
  52. '\1' -- marks end of added/deleted/changed text
  53. boolean flag -- None indicates context separation, True indicates
  54. either "from" or "to" line contains a change, otherwise False.
  55. """
  56. return difflib._mdiff(self._get_old_text(), self._get_new_text())
  57. def _get_old_text(self):
  58. out = []
  59. for (attr, line) in self._hunk_list:
  60. if attr != '+':
  61. out.append(line)
  62. return out
  63. def _get_new_text(self):
  64. out = []
  65. for (attr, line) in self._hunk_list:
  66. if attr != '-':
  67. out.append(line)
  68. return out
  69. def __iter__(self):
  70. for hunk_line in self._hunk_list:
  71. yield hunk_line
  72. class Diff(object):
  73. def __init__(self, headers, old_path, new_path, hunks):
  74. self._headers = headers
  75. self._old_path = old_path
  76. self._new_path = new_path
  77. self._hunks = hunks
  78. def markup_traditional(self):
  79. """Returns a generator"""
  80. for line in self._headers:
  81. yield self._markup_header(line)
  82. yield self._markup_old_path(self._old_path)
  83. yield self._markup_new_path(self._new_path)
  84. for hunk in self._hunks:
  85. yield self._markup_hunk_header(hunk.get_header())
  86. for old, new, changed in hunk.mdiff():
  87. if changed:
  88. if not old[0]:
  89. # The '+' char after \x00 is kept
  90. # DEBUG: yield 'NEW: %s %s\n' % (old, new)
  91. line = new[1].strip('\x00\x01')
  92. yield self._markup_new(line)
  93. elif not new[0]:
  94. # The '-' char after \x00 is kept
  95. # DEBUG: yield 'OLD: %s %s\n' % (old, new)
  96. line = old[1].strip('\x00\x01')
  97. yield self._markup_old(line)
  98. else:
  99. # DEBUG: yield 'CHG: %s %s\n' % (old, new)
  100. yield self._markup_old('-') + \
  101. self._markup_old_mix(old[1])
  102. yield self._markup_new('+') + \
  103. self._markup_new_mix(new[1])
  104. else:
  105. yield self._markup_common(' ' + old[1])
  106. def markup_side_by_side(self, width):
  107. """Returns a generator"""
  108. def _normalize(line):
  109. return line.replace('\t', ' '*8).replace('\n', '').replace('\r', '')
  110. def _fit_width(markup, width, pad=False):
  111. """str len does not count correctly if left column contains ansi
  112. color code. Only left side need to set `pad`
  113. """
  114. out = []
  115. count = 0
  116. ansi_color_regex = r'\x1b\[(1;)?\d{1,2}m'
  117. patt = re.compile('^(%s)(.*)' % ansi_color_regex)
  118. repl = re.compile(ansi_color_regex)
  119. while markup and count < width:
  120. if patt.match(markup):
  121. out.append(patt.sub(r'\1', markup))
  122. markup = patt.sub(r'\3', markup)
  123. else:
  124. # FIXME: utf-8 char broken here
  125. out.append(markup[0])
  126. markup = markup[1:]
  127. count += 1
  128. if count == width and repl.sub('', markup):
  129. # stripped: output fulfil and still have ascii in markup
  130. out[-1] = ansi_code('reset') + colorize('>', 'lightmagenta')
  131. elif count < width and pad:
  132. pad_len = width - count
  133. out.append('%*s' % (pad_len, ''))
  134. return ''.join(out)
  135. # Setup line width and number width
  136. if width <= 0:
  137. width = 80
  138. (start, offset) = self._hunks[-1].get_old_addr()
  139. max1 = start + offset - 1
  140. (start, offset) = self._hunks[-1].get_new_addr()
  141. max2 = start + offset - 1
  142. num_width = max(len(str(max1)), len(str(max2)))
  143. left_num_fmt = colorize('%%(left_num)%ds' % num_width, 'yellow')
  144. right_num_fmt = colorize('%%(right_num)%ds' % num_width, 'yellow')
  145. line_fmt = left_num_fmt + ' %(left)s ' + ansi_code('reset') + \
  146. right_num_fmt + ' %(right)s\n'
  147. # yield header, old path and new path
  148. for line in self._headers:
  149. yield self._markup_header(line)
  150. yield self._markup_old_path(self._old_path)
  151. yield self._markup_new_path(self._new_path)
  152. # yield hunks
  153. for hunk in self._hunks:
  154. yield self._markup_hunk_header(hunk.get_header())
  155. for old, new, changed in hunk.mdiff():
  156. if old[0]:
  157. left_num = str(hunk.get_old_addr()[0] + int(old[0]) - 1)
  158. else:
  159. left_num = ' '
  160. if new[0]:
  161. right_num = str(hunk.get_new_addr()[0] + int(new[0]) - 1)
  162. else:
  163. right_num = ' '
  164. left = _normalize(old[1])
  165. right = _normalize(new[1])
  166. if changed:
  167. if not old[0]:
  168. left = '%*s' % (width, ' ')
  169. right = right.lstrip('\x00+').rstrip('\x01')
  170. right = _fit_width(self._markup_new(right), width)
  171. elif not new[0]:
  172. left = left.lstrip('\x00-').rstrip('\x01')
  173. left = _fit_width(self._markup_old(left), width)
  174. right = ''
  175. else:
  176. left = _fit_width(self._markup_old_mix(left), width, 1)
  177. right = _fit_width(self._markup_new_mix(right), width)
  178. else:
  179. left = _fit_width(self._markup_common(left), width, 1)
  180. right = _fit_width(self._markup_common(right), width)
  181. yield line_fmt % {
  182. 'left_num': left_num,
  183. 'left': left,
  184. 'right_num': right_num,
  185. 'right': right
  186. }
  187. def _markup_header(self, line):
  188. return colorize(line, 'cyan')
  189. def _markup_old_path(self, line):
  190. return colorize(line, 'yellow')
  191. def _markup_new_path(self, line):
  192. return colorize(line, 'yellow')
  193. def _markup_hunk_header(self, line):
  194. return colorize(line, 'lightblue')
  195. def _markup_common(self, line):
  196. return colorize(line, 'reset')
  197. def _markup_old(self, line):
  198. return colorize(line, 'lightred')
  199. def _markup_new(self, line):
  200. return colorize(line, 'lightgreen')
  201. def _markup_mix(self, line, base_color):
  202. del_code = ansi_code('reverse') + ansi_code(base_color)
  203. add_code = ansi_code('reverse') + ansi_code(base_color)
  204. chg_code = ansi_code('underline') + ansi_code(base_color)
  205. rst_code = ansi_code('reset') + ansi_code(base_color)
  206. line = line.replace('\x00-', del_code)
  207. line = line.replace('\x00+', add_code)
  208. line = line.replace('\x00^', chg_code)
  209. line = line.replace('\x01', rst_code)
  210. return colorize(line, base_color)
  211. def _markup_old_mix(self, line):
  212. return self._markup_mix(line, 'red')
  213. def _markup_new_mix(self, line):
  214. return self._markup_mix(line, 'green')
  215. class Udiff(Diff):
  216. @staticmethod
  217. def is_old_path(line):
  218. return line.startswith('--- ')
  219. @staticmethod
  220. def is_new_path(line):
  221. return line.startswith('+++ ')
  222. @staticmethod
  223. def is_hunk_header(line):
  224. return line.startswith('@@ -')
  225. @staticmethod
  226. def is_old(line):
  227. return line.startswith('-') and not Udiff.is_old_path(line)
  228. @staticmethod
  229. def is_new(line):
  230. return line.startswith('+') and not Udiff.is_new_path(line)
  231. @staticmethod
  232. def is_common(line):
  233. return line.startswith(' ')
  234. @staticmethod
  235. def is_eof(line):
  236. # \ No newline at end of file
  237. return line.startswith('\\')
  238. @staticmethod
  239. def is_header(line):
  240. return re.match(r'^[^+@\\ -]', line)
  241. class DiffParser(object):
  242. def __init__(self, stream):
  243. for line in stream[:10]:
  244. if line.startswith('+++ '):
  245. self._type = 'udiff'
  246. break
  247. else:
  248. raise RuntimeError('unknown diff type')
  249. try:
  250. self._diffs = self._parse(stream)
  251. except (AssertionError, IndexError):
  252. raise RuntimeError('invalid patch format')
  253. def get_diffs(self):
  254. return self._diffs
  255. def _parse(self, stream):
  256. if self._type == 'udiff':
  257. return self._parse_udiff(stream)
  258. else:
  259. raise RuntimeError('unsupported diff format')
  260. def _parse_udiff(self, stream):
  261. """parse all diff lines here, construct a list of Udiff objects"""
  262. out_diffs = []
  263. headers = []
  264. old_path = None
  265. new_path = None
  266. hunks = []
  267. hunk = None
  268. while stream:
  269. # 'common' line occurs before 'old_path' is considered as header
  270. # too, this happens with `git log -p` and `git show <commit>`
  271. #
  272. if Udiff.is_header(stream[0]) or \
  273. (Udiff.is_common(stream[0]) and old_path is None):
  274. if headers and old_path:
  275. # Encounter a new header
  276. assert new_path is not None
  277. assert hunk is not None
  278. hunks.append(hunk)
  279. out_diffs.append(Diff(headers, old_path, new_path, hunks))
  280. headers = []
  281. old_path = None
  282. new_path = None
  283. hunks = []
  284. hunk = None
  285. else:
  286. headers.append(stream.pop(0))
  287. elif Udiff.is_old_path(stream[0]):
  288. if old_path:
  289. # Encounter a new patch set
  290. assert new_path is not None
  291. assert hunk is not None
  292. hunks.append(hunk)
  293. out_diffs.append(Diff(headers, old_path, new_path, hunks))
  294. headers = []
  295. old_path = None
  296. new_path = None
  297. hunks = []
  298. hunk = None
  299. else:
  300. old_path = stream.pop(0)
  301. elif Udiff.is_new_path(stream[0]):
  302. assert old_path is not None
  303. assert new_path is None
  304. new_path = stream.pop(0)
  305. elif Udiff.is_hunk_header(stream[0]):
  306. assert old_path is not None
  307. assert new_path is not None
  308. if hunk:
  309. # Encounter a new hunk header
  310. hunks.append(hunk)
  311. hunk = None
  312. else:
  313. # @@ -3,7 +3,6 @@
  314. hunk_header = stream.pop(0)
  315. a = hunk_header.split()[1].split(',') # -3 7
  316. old_addr = (int(a[0][1:]), int(a[1]))
  317. b = hunk_header.split()[2].split(',') # +3 6
  318. new_addr = (int(b[0][1:]), int(b[1]))
  319. hunk = Hunk(hunk_header, old_addr, new_addr)
  320. elif Udiff.is_old(stream[0]) or Udiff.is_new(stream[0]) or \
  321. Udiff.is_common(stream[0]):
  322. assert old_path is not None
  323. assert new_path is not None
  324. assert hunk is not None
  325. hunk_line = stream.pop(0)
  326. hunk.append(hunk_line[0], hunk_line[1:])
  327. elif Udiff.is_eof(stream[0]):
  328. # ignore
  329. stream.pop(0)
  330. else:
  331. raise RuntimeError('unknown patch format: %s' % stream[0])
  332. # The last patch
  333. if hunk:
  334. hunks.append(hunk)
  335. if old_path:
  336. if new_path:
  337. out_diffs.append(Diff(headers, old_path, new_path, hunks))
  338. else:
  339. raise RuntimeError('unknown patch format after "%s"' % old_path)
  340. elif headers:
  341. raise RuntimeError('unknown patch format: %s' % \
  342. ('\n'.join(headers)))
  343. return out_diffs
  344. class DiffMarkup(object):
  345. def __init__(self, stream):
  346. self._diffs = DiffParser(stream).get_diffs()
  347. def markup(self, side_by_side=False, width=0):
  348. """Returns a generator"""
  349. if side_by_side:
  350. return self._markup_side_by_side(width)
  351. else:
  352. return self._markup_traditional()
  353. def _markup_traditional(self):
  354. for diff in self._diffs:
  355. for line in diff.markup_traditional():
  356. yield line
  357. def _markup_side_by_side(self, width):
  358. for diff in self._diffs:
  359. for line in diff.markup_side_by_side(width):
  360. yield line
  361. if __name__ == '__main__':
  362. import optparse
  363. import subprocess
  364. usage = '''
  365. %(prog)s [options] [diff]
  366. View diff (patch) file if given, otherwise read stdin''' % \
  367. {'prog': os.path.basename(sys.argv[0])}
  368. parser = optparse.OptionParser(usage)
  369. parser.add_option('-s', '--side-by-side', action='store_true',
  370. help=('show in side-by-side mode'))
  371. parser.add_option('-w', '--width', type='int', default=80,
  372. help='set line width (side-by-side mode only), default is 80')
  373. opts, args = parser.parse_args()
  374. if len(args) >= 1:
  375. diff_hdl = open(args[0], 'r')
  376. elif sys.stdin.isatty():
  377. sys.stderr.write('Try --help option for usage\n')
  378. sys.exit(1)
  379. else:
  380. diff_hdl = sys.stdin
  381. # FIXME: can't use generator for now due to current implementation in parser
  382. stream = diff_hdl.readlines()
  383. # Don't let empty diff pass thru
  384. if not stream:
  385. sys.exit(0)
  386. if diff_hdl is not sys.stdin:
  387. diff_hdl.close()
  388. if sys.stdout.isatty():
  389. markup = DiffMarkup(stream)
  390. color_diff = markup.markup(side_by_side=opts.side_by_side,
  391. width=opts.width)
  392. # args stolen fron git source: github.com/git/git/blob/master/pager.c
  393. pager = subprocess.Popen(['less', '-FRSXK'],
  394. stdin=subprocess.PIPE, stdout=sys.stdout)
  395. for line in color_diff:
  396. pager.stdin.write(line)
  397. pager.stdin.close()
  398. pager.wait()
  399. else:
  400. # pipe out stream untouched to make sure it is still a patch
  401. sys.stdout.write(''.join(stream))
  402. sys.exit(0)
  403. # vim:set et sts=4 sw=4 tw=80: