cdiff.py 16KB

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