123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Term based tool to view *colored*, *incremental* diff in a *Git/Mercurial/Svn*
  5. workspace or from stdin, with *side by side* and *auto pager* support. Requires
  6. python (>= 2.5.0) and ``less``.
  7. """
  8. META_INFO = {
  9. 'version' : '0.7.1',
  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 a workspace or from '
  16. 'stdin, with side by side and auto pager support')
  17. }
  18. import sys
  19. if sys.hexversion < 0x02050000:
  20. raise SystemExit("*** Requires python >= 2.5.0")
  21. import re
  22. import subprocess
  23. import errno
  24. import difflib
  25. COLORS = {
  26. 'reset' : '\x1b[0m',
  27. 'underline' : '\x1b[4m',
  28. 'reverse' : '\x1b[7m',
  29. 'red' : '\x1b[31m',
  30. 'green' : '\x1b[32m',
  31. 'yellow' : '\x1b[33m',
  32. 'blue' : '\x1b[34m',
  33. 'magenta' : '\x1b[35m',
  34. 'cyan' : '\x1b[36m',
  35. 'lightred' : '\x1b[1;31m',
  36. 'lightgreen' : '\x1b[1;32m',
  37. 'lightyellow' : '\x1b[1;33m',
  38. 'lightblue' : '\x1b[1;34m',
  39. 'lightmagenta' : '\x1b[1;35m',
  40. 'lightcyan' : '\x1b[1;36m',
  41. }
  42. # Keys for revision control probe, diff and log with diff
  43. VCS_INFO = {
  44. 'Git': {
  45. 'probe' : ['git', 'rev-parse'],
  46. 'diff' : ['git', 'diff'],
  47. 'log' : ['git', 'log', '--patch'],
  48. },
  49. 'Mercurial': {
  50. 'probe' : ['hg', 'summary'],
  51. 'diff' : ['hg', 'diff'],
  52. 'log' : ['hg', 'log', '--patch'],
  53. },
  54. 'Svn': {
  55. 'probe' : ['svn', 'info'],
  56. 'diff' : ['svn', 'diff'],
  57. 'log' : ['svn', 'log', '--diff', '--use-merge-history'],
  58. },
  59. }
  60. def colorize(text, start_color, end_color='reset'):
  61. return COLORS[start_color] + text + COLORS[end_color]
  62. class Hunk(object):
  63. def __init__(self, hunk_headers, hunk_meta, old_addr, new_addr):
  64. self._hunk_headers = hunk_headers
  65. self._hunk_meta = hunk_meta
  66. self._old_addr = old_addr # tuple (start, offset)
  67. self._new_addr = new_addr # tuple (start, offset)
  68. self._hunk_list = [] # list of tuple (attr, line)
  69. def append(self, hunk_line):
  70. """hunk_line is a 2-element tuple: (attr, text), where attr is:
  71. '-': old, '+': new, ' ': common
  72. """
  73. self._hunk_list.append(hunk_line)
  74. def mdiff(self):
  75. r"""The difflib._mdiff() function returns an interator which returns a
  76. tuple: (from line tuple, to line tuple, boolean flag)
  77. from/to line tuple -- (line num, line text)
  78. line num -- integer or None (to indicate a context separation)
  79. line text -- original line text with following markers inserted:
  80. '\0+' -- marks start of added text
  81. '\0-' -- marks start of deleted text
  82. '\0^' -- marks start of changed text
  83. '\1' -- marks end of added/deleted/changed text
  84. boolean flag -- None indicates context separation, True indicates
  85. either "from" or "to" line contains a change, otherwise False.
  86. """
  87. return difflib._mdiff(self._get_old_text(), self._get_new_text())
  88. def _get_old_text(self):
  89. out = []
  90. for (attr, line) in self._hunk_list:
  91. if attr != '+':
  92. out.append(line)
  93. return out
  94. def _get_new_text(self):
  95. out = []
  96. for (attr, line) in self._hunk_list:
  97. if attr != '-':
  98. out.append(line)
  99. return out
  100. def __iter__(self):
  101. for hunk_line in self._hunk_list:
  102. yield hunk_line
  103. class Diff(object):
  104. def __init__(self, headers, old_path, new_path, hunks):
  105. self._headers = headers
  106. self._old_path = old_path
  107. self._new_path = new_path
  108. self._hunks = hunks
  109. # Following detectors, parse_hunk_meta() and parse_hunk_line() are suppose
  110. # to be overwritten by derived class. No is_header() anymore, all
  111. # non-recognized lines are considered as headers
  112. #
  113. def is_old_path(self, line):
  114. return False
  115. def is_new_path(self, line):
  116. return False
  117. def is_hunk_meta(self, line):
  118. return False
  119. def parse_hunk_meta(self, line):
  120. """Returns a 2-element tuple, each is a tuple of (start, offset)"""
  121. return None
  122. def parse_hunk_line(self, line):
  123. """Returns a 2-element tuple: (attr, text), where attr is:
  124. '-': old, '+': new, ' ': common
  125. """
  126. return None
  127. def is_old(self, line):
  128. return False
  129. def is_new(self, line):
  130. return False
  131. def is_common(self, line):
  132. return False
  133. def is_eof(self, line):
  134. return False
  135. def is_only_in_dir(self, line):
  136. return False
  137. def is_binary_differ(self, line):
  138. return False
  139. # Followings are not suppose to override
  140. #
  141. def markup_traditional(self):
  142. """Returns a generator"""
  143. for line in self._headers:
  144. yield self._markup_header(line)
  145. yield self._markup_old_path(self._old_path)
  146. yield self._markup_new_path(self._new_path)
  147. for hunk in self._hunks:
  148. for hunk_header in hunk._hunk_headers:
  149. yield self._markup_hunk_header(hunk_header)
  150. yield self._markup_hunk_meta(hunk._hunk_meta)
  151. for old, new, changed in hunk.mdiff():
  152. if changed:
  153. if not old[0]:
  154. # The '+' char after \x00 is kept
  155. # DEBUG: yield 'NEW: %s %s\n' % (old, new)
  156. line = new[1].strip('\x00\x01')
  157. yield self._markup_new(line)
  158. elif not new[0]:
  159. # The '-' char after \x00 is kept
  160. # DEBUG: yield 'OLD: %s %s\n' % (old, new)
  161. line = old[1].strip('\x00\x01')
  162. yield self._markup_old(line)
  163. else:
  164. # DEBUG: yield 'CHG: %s %s\n' % (old, new)
  165. yield self._markup_old('-') + \
  166. self._markup_mix(old[1], 'red')
  167. yield self._markup_new('+') + \
  168. self._markup_mix(new[1], 'green')
  169. else:
  170. yield self._markup_common(' ' + old[1])
  171. def markup_side_by_side(self, width):
  172. """Returns a generator"""
  173. wrap_char = colorize('>', 'lightmagenta')
  174. def _normalize(line):
  175. return line.replace(
  176. '\t', ' ' * 8).replace('\n', '').replace('\r', '')
  177. def _fit_with_marker(text, markup_fn, width, pad=False):
  178. """Wrap or pad input pure text, then markup"""
  179. if len(text) > width:
  180. return markup_fn(text[:(width - 1)]) + wrap_char
  181. elif pad:
  182. pad_len = width - len(text)
  183. return '%s%*s' % (markup_fn(text), pad_len, '')
  184. else:
  185. return markup_fn(text)
  186. def _fit_with_marker_mix(text, base_color, width, pad=False):
  187. """Wrap or pad input text which contains mdiff tags, markup at the
  188. meantime, note only left side need to set `pad`
  189. """
  190. out = [COLORS[base_color]]
  191. count = 0
  192. tag_re = re.compile(r'\x00[+^-]|\x01')
  193. while text and count < width:
  194. if text.startswith('\x00-'): # del
  195. out.append(COLORS['reverse'] + COLORS[base_color])
  196. text = text[2:]
  197. elif text.startswith('\x00+'): # add
  198. out.append(COLORS['reverse'] + COLORS[base_color])
  199. text = text[2:]
  200. elif text.startswith('\x00^'): # change
  201. out.append(COLORS['underline'] + COLORS[base_color])
  202. text = text[2:]
  203. elif text.startswith('\x01'): # reset
  204. out.append(COLORS['reset'] + COLORS[base_color])
  205. text = text[1:]
  206. else:
  207. # FIXME: utf-8 wchar might break the rule here, e.g.
  208. # u'\u554a' takes double width of a single letter, also
  209. # this depends on your terminal font. I guess audience of
  210. # this tool never put that kind of symbol in their code :-)
  211. #
  212. out.append(text[0])
  213. count += 1
  214. text = text[1:]
  215. if count == width and tag_re.sub('', text):
  216. # Was stripped: output fulfil and still has normal char in text
  217. out[-1] = COLORS['reset'] + wrap_char
  218. elif count < width and pad:
  219. pad_len = width - count
  220. out.append('%s%*s' % (COLORS['reset'], pad_len, ''))
  221. else:
  222. out.append(COLORS['reset'])
  223. return ''.join(out)
  224. # Set up line width
  225. if width <= 0:
  226. width = 80
  227. # Set up number width, note last hunk might be empty
  228. try:
  229. (start, offset) = self._hunks[-1]._old_addr
  230. max1 = start + offset - 1
  231. (start, offset) = self._hunks[-1]._new_addr
  232. max2 = start + offset - 1
  233. except IndexError:
  234. max1 = max2 = 0
  235. num_width = max(len(str(max1)), len(str(max2)))
  236. # Setup lineno and line format
  237. left_num_fmt = colorize('%%(left_num)%ds' % num_width, 'yellow')
  238. right_num_fmt = colorize('%%(right_num)%ds' % num_width, 'yellow')
  239. line_fmt = left_num_fmt + ' %(left)s ' + COLORS['reset'] + \
  240. right_num_fmt + ' %(right)s\n'
  241. # yield header, old path and new path
  242. for line in self._headers:
  243. yield self._markup_header(line)
  244. yield self._markup_old_path(self._old_path)
  245. yield self._markup_new_path(self._new_path)
  246. # yield hunks
  247. for hunk in self._hunks:
  248. for hunk_header in hunk._hunk_headers:
  249. yield self._markup_hunk_header(hunk_header)
  250. yield self._markup_hunk_meta(hunk._hunk_meta)
  251. for old, new, changed in hunk.mdiff():
  252. if old[0]:
  253. left_num = str(hunk._old_addr[0] + int(old[0]) - 1)
  254. else:
  255. left_num = ' '
  256. if new[0]:
  257. right_num = str(hunk._new_addr[0] + int(new[0]) - 1)
  258. else:
  259. right_num = ' '
  260. left = _normalize(old[1])
  261. right = _normalize(new[1])
  262. if changed:
  263. if not old[0]:
  264. left = '%*s' % (width, ' ')
  265. right = right.lstrip('\x00+').rstrip('\x01')
  266. right = _fit_with_marker(
  267. right, self._markup_new, width)
  268. elif not new[0]:
  269. left = left.lstrip('\x00-').rstrip('\x01')
  270. left = _fit_with_marker(left, self._markup_old, width)
  271. right = ''
  272. else:
  273. left = _fit_with_marker_mix(left, 'red', width, 1)
  274. right = _fit_with_marker_mix(right, 'green', width)
  275. else:
  276. left = _fit_with_marker(
  277. left, self._markup_common, width, 1)
  278. right = _fit_with_marker(right, self._markup_common, width)
  279. yield line_fmt % {
  280. 'left_num': left_num,
  281. 'left': left,
  282. 'right_num': right_num,
  283. 'right': right
  284. }
  285. def _markup_header(self, line):
  286. return colorize(line, 'cyan')
  287. def _markup_old_path(self, line):
  288. return colorize(line, 'yellow')
  289. def _markup_new_path(self, line):
  290. return colorize(line, 'yellow')
  291. def _markup_hunk_header(self, line):
  292. return colorize(line, 'lightcyan')
  293. def _markup_hunk_meta(self, line):
  294. return colorize(line, 'lightblue')
  295. def _markup_common(self, line):
  296. return colorize(line, 'reset')
  297. def _markup_old(self, line):
  298. return colorize(line, 'lightred')
  299. def _markup_new(self, line):
  300. return colorize(line, 'lightgreen')
  301. def _markup_mix(self, line, base_color):
  302. del_code = COLORS['reverse'] + COLORS[base_color]
  303. add_code = COLORS['reverse'] + COLORS[base_color]
  304. chg_code = COLORS['underline'] + COLORS[base_color]
  305. rst_code = COLORS['reset'] + COLORS[base_color]
  306. line = line.replace('\x00-', del_code)
  307. line = line.replace('\x00+', add_code)
  308. line = line.replace('\x00^', chg_code)
  309. line = line.replace('\x01', rst_code)
  310. return colorize(line, base_color)
  311. class Udiff(Diff):
  312. def is_old_path(self, line):
  313. return line.startswith('--- ')
  314. def is_new_path(self, line):
  315. return line.startswith('+++ ')
  316. def is_hunk_meta(self, line):
  317. """Minimal valid hunk meta is like '@@ -1 +1 @@', note extra chars
  318. might occur after the ending @@, e.g. in git log
  319. """
  320. return (line.startswith('@@ -') and line.find(' @@') >= 8) or \
  321. (line.startswith('## -') and line.find(' ##') >= 8)
  322. def parse_hunk_meta(self, hunk_meta):
  323. # @@ -3,7 +3,6 @@
  324. a = hunk_meta.split()[1].split(',') # -3 7
  325. if len(a) > 1:
  326. old_addr = (int(a[0][1:]), int(a[1]))
  327. else:
  328. # @@ -1 +1,2 @@
  329. old_addr = (int(a[0][1:]), 0)
  330. b = hunk_meta.split()[2].split(',') # +3 6
  331. if len(b) > 1:
  332. new_addr = (int(b[0][1:]), int(b[1]))
  333. else:
  334. # @@ -0,0 +1 @@
  335. new_addr = (int(b[0][1:]), 0)
  336. return (old_addr, new_addr)
  337. def parse_hunk_line(self, line):
  338. return (line[0], line[1:])
  339. def is_old(self, line):
  340. """Exclude old path and header line from svn log --diff output, allow
  341. '----' likely to see in diff from yaml file
  342. """
  343. return line.startswith('-') and not self.is_old_path(line) and \
  344. not re.match(r'^-{5,}$', line.rstrip())
  345. def is_new(self, line):
  346. return line.startswith('+') and not self.is_new_path(line)
  347. def is_common(self, line):
  348. return line.startswith(' ')
  349. def is_eof(self, line):
  350. # \ No newline at end of file
  351. # \ No newline at end of property
  352. return line.startswith(r'\ No newline at end of')
  353. def is_only_in_dir(self, line):
  354. return line.startswith('Only in ')
  355. def is_binary_differ(self, line):
  356. return re.match('^Binary files .* differ$', line.rstrip())
  357. class PatchStream(object):
  358. def __init__(self, diff_hdl):
  359. self._diff_hdl = diff_hdl
  360. self._stream_header_size = 0
  361. self._stream_header = []
  362. # Test whether stream is empty by read 1 line
  363. line = self._diff_hdl.readline()
  364. if not line:
  365. self._is_empty = True
  366. else:
  367. self._stream_header.append(line)
  368. self._stream_header_size += 1
  369. self._is_empty = False
  370. def is_empty(self):
  371. return self._is_empty
  372. def read_stream_header(self, stream_header_size):
  373. """Returns a small chunk for patch type detect, suppose to call once"""
  374. for i in range(1, stream_header_size):
  375. line = self._diff_hdl.readline()
  376. if not line:
  377. break
  378. self._stream_header.append(line)
  379. self._stream_header_size += 1
  380. return self._stream_header
  381. def __iter__(self):
  382. for line in self._stream_header:
  383. yield line
  384. for line in self._diff_hdl:
  385. yield line
  386. class DiffParser(object):
  387. def __init__(self, stream):
  388. """Detect Udiff with 3 conditions, '## ' uaually indicates svn property
  389. changes in output from `svn log --diff`
  390. """
  391. self._stream = stream
  392. flag = 0
  393. for line in self._stream.read_stream_header(100):
  394. line = decode(line)
  395. if line.startswith('--- '):
  396. flag |= 1
  397. elif line.startswith('+++ '):
  398. flag |= 2
  399. elif line.startswith('@@ ') or line.startswith('## '):
  400. flag |= 4
  401. if (flag & 7) == 7:
  402. self._type = 'udiff'
  403. break
  404. else:
  405. raise RuntimeError('unknown diff type')
  406. def get_diff_generator(self):
  407. try:
  408. return self._parse()
  409. except (AssertionError, IndexError):
  410. raise RuntimeError('invalid patch format')
  411. def _parse(self):
  412. """parse all diff lines, construct a list of Diff objects"""
  413. if self._type == 'udiff':
  414. difflet = Udiff(None, None, None, None)
  415. else:
  416. raise RuntimeError('unsupported diff format')
  417. diff = Diff([], None, None, [])
  418. headers = []
  419. for line in self._stream:
  420. line = decode(line)
  421. if difflet.is_old_path(line):
  422. # FIXME: '--- ' breaks here, need to probe next 3 lines,
  423. # reproducible with github raw patch
  424. #
  425. if diff._old_path and diff._new_path and len(diff._hunks) > 0:
  426. # One diff constructed
  427. yield diff
  428. diff = Diff([], None, None, [])
  429. diff = Diff(headers, line, None, [])
  430. headers = []
  431. elif difflet.is_new_path(line):
  432. diff._new_path = line
  433. elif difflet.is_hunk_meta(line):
  434. hunk_meta = line
  435. old_addr, new_addr = difflet.parse_hunk_meta(hunk_meta)
  436. hunk = Hunk(headers, hunk_meta, old_addr, new_addr)
  437. headers = []
  438. diff._hunks.append(hunk)
  439. elif len(diff._hunks) > 0 and (difflet.is_old(line) or
  440. difflet.is_new(line) or
  441. difflet.is_common(line)):
  442. diff._hunks[-1].append(difflet.parse_hunk_line(line))
  443. elif difflet.is_eof(line):
  444. # ignore
  445. pass
  446. elif difflet.is_only_in_dir(line) or \
  447. difflet.is_binary_differ(line):
  448. # 'Only in foo:' and 'Binary files ... differ' are considered
  449. # as separate diffs, so yield current diff, then this line
  450. #
  451. if diff._old_path and diff._new_path and len(diff._hunks) > 0:
  452. # Current diff is comppletely constructed
  453. yield diff
  454. headers.append(line)
  455. yield Diff(headers, '', '', [])
  456. headers = []
  457. diff = Diff([], None, None, [])
  458. else:
  459. # All other non-recognized lines are considered as headers or
  460. # hunk headers respectively
  461. #
  462. headers.append(line)
  463. if headers:
  464. raise RuntimeError('dangling header(s):\n%s' % ''.join(headers))
  465. # Validate and yield the last patch set if it is not yielded yet
  466. if diff._old_path:
  467. assert diff._new_path is not None
  468. assert len(diff._hunks) > 0
  469. if diff._hunks:
  470. assert len(diff._hunks[-1]._hunk_meta) > 0
  471. assert len(diff._hunks[-1]._hunk_list) > 0
  472. yield diff
  473. class DiffMarkup(object):
  474. def __init__(self, stream):
  475. self._diffs = DiffParser(stream).get_diff_generator()
  476. def markup(self, side_by_side=False, width=0):
  477. """Returns a generator"""
  478. if side_by_side:
  479. return self._markup_side_by_side(width)
  480. else:
  481. return self._markup_traditional()
  482. def _markup_traditional(self):
  483. for diff in self._diffs:
  484. for line in diff.markup_traditional():
  485. yield line
  486. def _markup_side_by_side(self, width):
  487. for diff in self._diffs:
  488. for line in diff.markup_side_by_side(width):
  489. yield line
  490. def markup_to_pager(stream, opts):
  491. markup = DiffMarkup(stream)
  492. color_diff = markup.markup(side_by_side=opts.side_by_side,
  493. width=opts.width)
  494. # Args stolen from git source: github.com/git/git/blob/master/pager.c
  495. pager = subprocess.Popen(
  496. ['less', '-FRSX'], stdin=subprocess.PIPE, stdout=sys.stdout)
  497. try:
  498. for line in color_diff:
  499. pager.stdin.write(line.encode('utf-8'))
  500. except KeyboardInterrupt:
  501. pass
  502. pager.stdin.close()
  503. pager.wait()
  504. def check_command_status(arguments):
  505. """Return True if command returns 0."""
  506. try:
  507. return subprocess.call(
  508. arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0
  509. except OSError:
  510. return False
  511. def revision_control_diff(args):
  512. """Return diff from revision control system."""
  513. for _, ops in VCS_INFO.items():
  514. if check_command_status(ops['probe']):
  515. return subprocess.Popen(
  516. ops['diff'] + args, stdout=subprocess.PIPE).stdout
  517. def revision_control_log(args):
  518. """Return log from revision control system."""
  519. for _, ops in VCS_INFO.items():
  520. if check_command_status(ops['probe']):
  521. return subprocess.Popen(
  522. ops['log'] + args, stdout=subprocess.PIPE).stdout
  523. def decode(line):
  524. """Decode UTF-8 if necessary."""
  525. try:
  526. return line.decode('utf-8')
  527. except AttributeError:
  528. return line
  529. def main():
  530. import optparse
  531. supported_vcs = sorted(VCS_INFO.keys())
  532. usage = """%prog [options] [file|dir ...]"""
  533. parser = optparse.OptionParser(
  534. usage=usage, description=META_INFO['description'],
  535. version='%%prog %s' % META_INFO['version'])
  536. parser.add_option(
  537. '-s', '--side-by-side', action='store_true',
  538. help='enable side-by-side mode')
  539. parser.add_option(
  540. '-w', '--width', type='int', default=80, metavar='N',
  541. help='set text width for side-by-side mode, default is 80')
  542. parser.add_option(
  543. '-l', '--log', action='store_true',
  544. help='show log with changes from revision control')
  545. parser.add_option(
  546. '-c', '--color', default='auto', metavar='X',
  547. help="""colorize mode 'auto' (default), 'always', or 'never'""")
  548. opts, args = parser.parse_args()
  549. if opts.log:
  550. diff_hdl = revision_control_log(args)
  551. if not diff_hdl:
  552. sys.stderr.write(('*** Not in a supported workspace, supported '
  553. 'are: %s\n') % ', '.join(supported_vcs))
  554. return 1
  555. elif sys.stdin.isatty():
  556. diff_hdl = revision_control_diff(args)
  557. if not diff_hdl:
  558. sys.stderr.write(('*** Not in a supported workspace, supported '
  559. 'are: %s\n\n') % ', '.join(supported_vcs))
  560. parser.print_help()
  561. return 1
  562. else:
  563. diff_hdl = sys.stdin
  564. stream = PatchStream(diff_hdl)
  565. # Don't let empty diff pass thru
  566. if stream.is_empty():
  567. return 0
  568. if opts.color == 'always' or \
  569. (opts.color == 'auto' and sys.stdout.isatty()):
  570. try:
  571. markup_to_pager(stream, opts)
  572. except IOError:
  573. e = sys.exc_info()[1]
  574. if e.errno == errno.EPIPE:
  575. pass
  576. else:
  577. # pipe out stream untouched to make sure it is still a patch
  578. for line in stream:
  579. sys.stdout.write(decode(line))
  580. if diff_hdl is not sys.stdin:
  581. diff_hdl.close()
  582. return 0
  583. if __name__ == '__main__':
  584. sys.exit(main())
  585. # vim:set et sts=4 sw=4 tw=79: