cdiff.py 16KB

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