cdiff.py 19KB

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