cdiff.py 20KB

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