cdiff.py 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Term based tool to view **colored**, **incremental** diff in Git/Mercurial/Svn
  5. workspace or from stdin, with **side by side** and **auto pager** support.
  6. Requires 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 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('\t', ' '*8).replace('\n', '').replace('\r', '')
  176. def _fit_with_marker(text, markup_fn, width, pad=False):
  177. """Wrap or pad input pure text, then markup"""
  178. if len(text) > width:
  179. return markup_fn(text[:width-1]) + wrap_char
  180. elif pad:
  181. pad_len = width - len(text)
  182. return '%s%*s' % (markup_fn(text), pad_len, '')
  183. else:
  184. return markup_fn(text)
  185. def _fit_with_marker_mix(text, base_color, width, pad=False):
  186. """Wrap or pad input text which contains mdiff tags, markup at the
  187. meantime, note only left side need to set `pad`
  188. """
  189. out = [COLORS[base_color]]
  190. count = 0
  191. tag_re = re.compile(r'\x00[+^-]|\x01')
  192. while text and count < width:
  193. if text.startswith('\x00-'): # del
  194. out.append(COLORS['reverse'] + COLORS[base_color])
  195. text = text[2:]
  196. elif text.startswith('\x00+'): # add
  197. out.append(COLORS['reverse'] + COLORS[base_color])
  198. text = text[2:]
  199. elif text.startswith('\x00^'): # change
  200. out.append(COLORS['underline'] + COLORS[base_color])
  201. text = text[2:]
  202. elif text.startswith('\x01'): # reset
  203. out.append(COLORS['reset'] + COLORS[base_color])
  204. text = text[1:]
  205. else:
  206. # FIXME: utf-8 wchar might break the rule here, e.g.
  207. # u'\u554a' takes double width of a single letter, also this
  208. # depends on your terminal font. I guess audience of this
  209. # tool never put that kind of symbol in their code :-)
  210. #
  211. out.append(text[0])
  212. count += 1
  213. text = text[1:]
  214. if count == width and tag_re.sub('', text):
  215. # Was stripped: output fulfil and still has normal char in text
  216. out[-1] = COLORS['reset'] + wrap_char
  217. elif count < width and pad:
  218. pad_len = width - count
  219. out.append('%s%*s' % (COLORS['reset'], pad_len, ''))
  220. else:
  221. out.append(COLORS['reset'])
  222. return ''.join(out)
  223. # Set up line width
  224. if width <= 0:
  225. width = 80
  226. # Set up number width, note last hunk might be empty
  227. try:
  228. (start, offset) = self._hunks[-1]._old_addr
  229. max1 = start + offset - 1
  230. (start, offset) = self._hunks[-1]._new_addr
  231. max2 = start + offset - 1
  232. except IndexError:
  233. max1 = max2 = 0
  234. num_width = max(len(str(max1)), len(str(max2)))
  235. # Setup lineno and line format
  236. left_num_fmt = colorize('%%(left_num)%ds' % num_width, 'yellow')
  237. right_num_fmt = colorize('%%(right_num)%ds' % num_width, 'yellow')
  238. line_fmt = left_num_fmt + ' %(left)s ' + COLORS['reset'] + \
  239. right_num_fmt + ' %(right)s\n'
  240. # yield header, old path and new path
  241. for line in self._headers:
  242. yield self._markup_header(line)
  243. yield self._markup_old_path(self._old_path)
  244. yield self._markup_new_path(self._new_path)
  245. # yield hunks
  246. for hunk in self._hunks:
  247. for hunk_header in hunk._hunk_headers:
  248. yield self._markup_hunk_header(hunk_header)
  249. yield self._markup_hunk_meta(hunk._hunk_meta)
  250. for old, new, changed in hunk.mdiff():
  251. if old[0]:
  252. left_num = str(hunk._old_addr[0] + int(old[0]) - 1)
  253. else:
  254. left_num = ' '
  255. if new[0]:
  256. right_num = str(hunk._new_addr[0] + int(new[0]) - 1)
  257. else:
  258. right_num = ' '
  259. left = _normalize(old[1])
  260. right = _normalize(new[1])
  261. if changed:
  262. if not old[0]:
  263. left = '%*s' % (width, ' ')
  264. right = right.lstrip('\x00+').rstrip('\x01')
  265. right = _fit_with_marker(right, self._markup_new, width)
  266. elif not new[0]:
  267. left = left.lstrip('\x00-').rstrip('\x01')
  268. left = _fit_with_marker(left, self._markup_old, width)
  269. right = ''
  270. else:
  271. left = _fit_with_marker_mix(left, 'red', width, 1)
  272. right = _fit_with_marker_mix(right, 'green', width)
  273. else:
  274. left = _fit_with_marker(left, self._markup_common, width, 1)
  275. right = _fit_with_marker(right, self._markup_common, width)
  276. yield line_fmt % {
  277. 'left_num': left_num,
  278. 'left': left,
  279. 'right_num': right_num,
  280. 'right': right
  281. }
  282. def _markup_header(self, line):
  283. return colorize(line, 'cyan')
  284. def _markup_old_path(self, line):
  285. return colorize(line, 'yellow')
  286. def _markup_new_path(self, line):
  287. return colorize(line, 'yellow')
  288. def _markup_hunk_header(self, line):
  289. return colorize(line, 'lightcyan')
  290. def _markup_hunk_meta(self, line):
  291. return colorize(line, 'lightblue')
  292. def _markup_common(self, line):
  293. return colorize(line, 'reset')
  294. def _markup_old(self, line):
  295. return colorize(line, 'lightred')
  296. def _markup_new(self, line):
  297. return colorize(line, 'lightgreen')
  298. def _markup_mix(self, line, base_color):
  299. del_code = COLORS['reverse'] + COLORS[base_color]
  300. add_code = COLORS['reverse'] + COLORS[base_color]
  301. chg_code = COLORS['underline'] + COLORS[base_color]
  302. rst_code = COLORS['reset'] + COLORS[base_color]
  303. line = line.replace('\x00-', del_code)
  304. line = line.replace('\x00+', add_code)
  305. line = line.replace('\x00^', chg_code)
  306. line = line.replace('\x01', rst_code)
  307. return colorize(line, base_color)
  308. class Udiff(Diff):
  309. def is_old_path(self, line):
  310. return line.startswith('--- ')
  311. def is_new_path(self, line):
  312. return line.startswith('+++ ')
  313. def is_hunk_meta(self, line):
  314. """Minimal valid hunk meta is like '@@ -1 +1 @@', note extra chars might
  315. occur after the ending @@, e.g. in git log
  316. """
  317. return (line.startswith('@@ -') and line.find(' @@') >= 8) or \
  318. (line.startswith('## -') and line.find(' ##') >= 8)
  319. def parse_hunk_meta(self, hunk_meta):
  320. # @@ -3,7 +3,6 @@
  321. a = hunk_meta.split()[1].split(',') # -3 7
  322. if len(a) > 1:
  323. old_addr = (int(a[0][1:]), int(a[1]))
  324. else:
  325. # @@ -1 +1,2 @@
  326. old_addr = (int(a[0][1:]), 0)
  327. b = hunk_meta.split()[2].split(',') # +3 6
  328. if len(b) > 1:
  329. new_addr = (int(b[0][1:]), int(b[1]))
  330. else:
  331. # @@ -0,0 +1 @@
  332. new_addr = (int(b[0][1:]), 0)
  333. return (old_addr, new_addr)
  334. def parse_hunk_line(self, line):
  335. return (line[0], line[1:])
  336. def is_old(self, line):
  337. """Exclude old path and header line from svn log --diff output, allow
  338. '----' likely to see in diff from yaml file
  339. """
  340. return line.startswith('-') and not self.is_old_path(line) and \
  341. not re.match(r'^-{5,}$', line.rstrip())
  342. def is_new(self, line):
  343. return line.startswith('+') and not self.is_new_path(line)
  344. def is_common(self, line):
  345. return line.startswith(' ')
  346. def is_eof(self, line):
  347. # \ No newline at end of file
  348. # \ No newline at end of property
  349. return line.startswith(r'\ No newline at end of')
  350. def is_only_in_dir(self, line):
  351. return line.startswith('Only in ')
  352. def is_binary_differ(self, line):
  353. return re.match('^Binary files .* differ$', line.rstrip())
  354. class PatchStream(object):
  355. def __init__(self, diff_hdl):
  356. self._diff_hdl = diff_hdl
  357. self._stream_header_size = 0
  358. self._stream_header = []
  359. # Test whether stream is empty by read 1 line
  360. line = self._diff_hdl.readline()
  361. if not line:
  362. self._is_empty = True
  363. else:
  364. self._stream_header.append(line)
  365. self._stream_header_size += 1
  366. self._is_empty = False
  367. def is_empty(self):
  368. return self._is_empty
  369. def read_stream_header(self, stream_header_size):
  370. """Returns a small chunk for patch type detect, suppose to call once"""
  371. for i in range(1, stream_header_size):
  372. line = self._diff_hdl.readline()
  373. if not line:
  374. break
  375. self._stream_header.append(line)
  376. self._stream_header_size += 1
  377. return self._stream_header
  378. def __iter__(self):
  379. for line in self._stream_header:
  380. yield line
  381. for line in self._diff_hdl:
  382. yield line
  383. class DiffParser(object):
  384. def __init__(self, stream):
  385. """Detect Udiff with 3 conditions, '## ' uaually indicates svn property
  386. changes in output from `svn log --diff`
  387. """
  388. self._stream = stream
  389. flag = 0
  390. for line in self._stream.read_stream_header(100):
  391. line = decode(line)
  392. if line.startswith('--- '):
  393. flag |= 1
  394. elif line.startswith('+++ '):
  395. flag |= 2
  396. elif line.startswith('@@ ') or line.startswith('## '):
  397. flag |= 4
  398. if (flag & 7) == 7:
  399. self._type = 'udiff'
  400. break
  401. else:
  402. raise RuntimeError('unknown diff type')
  403. def get_diff_generator(self):
  404. try:
  405. return self._parse()
  406. except (AssertionError, IndexError):
  407. raise RuntimeError('invalid patch format')
  408. def _parse(self):
  409. """parse all diff lines, construct a list of Diff objects"""
  410. if self._type == 'udiff':
  411. difflet = Udiff(None, None, None, None)
  412. else:
  413. raise RuntimeError('unsupported diff format')
  414. diff = Diff([], None, None, [])
  415. headers = []
  416. for line in self._stream:
  417. line = decode(line)
  418. if difflet.is_old_path(line):
  419. # FIXME: '--- ' breaks here, need to probe next 3 lines,
  420. # reproducible with github raw patch
  421. #
  422. if diff._old_path and diff._new_path and len(diff._hunks) > 0:
  423. # One diff constructed
  424. yield diff
  425. diff = Diff([], None, None, [])
  426. diff = Diff(headers, line, None, [])
  427. headers = []
  428. elif difflet.is_new_path(line):
  429. diff._new_path = line
  430. elif difflet.is_hunk_meta(line):
  431. hunk_meta = line
  432. old_addr, new_addr = difflet.parse_hunk_meta(hunk_meta)
  433. hunk = Hunk(headers, hunk_meta, old_addr, new_addr)
  434. headers = []
  435. diff._hunks.append(hunk)
  436. elif len(diff._hunks) > 0 and (difflet.is_old(line) or \
  437. difflet.is_new(line) or difflet.is_common(line)):
  438. diff._hunks[-1].append(difflet.parse_hunk_line(line))
  439. elif difflet.is_eof(line):
  440. # ignore
  441. pass
  442. elif difflet.is_only_in_dir(line) or difflet.is_binary_differ(line):
  443. # 'Only in foo:' and 'Binary files ... differ' are considered as
  444. # separate diffs, so yield current diff, then this line
  445. #
  446. if diff._old_path and diff._new_path and len(diff._hunks) > 0:
  447. # Current diff is comppletely constructed
  448. yield diff
  449. headers.append(line)
  450. yield Diff(headers, '', '', [])
  451. headers = []
  452. diff = Diff([], None, None, [])
  453. else:
  454. # All other non-recognized lines are considered as headers or
  455. # hunk headers respectively
  456. #
  457. headers.append(line)
  458. if headers:
  459. raise RuntimeError('dangling header(s):\n%s' % ''.join(headers))
  460. # Validate and yield the last patch set if it is not yielded yet
  461. if diff._old_path:
  462. assert diff._new_path is not None
  463. assert len(diff._hunks) > 0
  464. if diff._hunks:
  465. assert len(diff._hunks[-1]._hunk_meta) > 0
  466. assert len(diff._hunks[-1]._hunk_list) > 0
  467. yield diff
  468. class DiffMarkup(object):
  469. def __init__(self, stream):
  470. self._diffs = DiffParser(stream).get_diff_generator()
  471. def markup(self, side_by_side=False, width=0):
  472. """Returns a generator"""
  473. if side_by_side:
  474. return self._markup_side_by_side(width)
  475. else:
  476. return self._markup_traditional()
  477. def _markup_traditional(self):
  478. for diff in self._diffs:
  479. for line in diff.markup_traditional():
  480. yield line
  481. def _markup_side_by_side(self, width):
  482. for diff in self._diffs:
  483. for line in diff.markup_side_by_side(width):
  484. yield line
  485. def markup_to_pager(stream, opts):
  486. markup = DiffMarkup(stream)
  487. color_diff = markup.markup(side_by_side=opts.side_by_side,
  488. width=opts.width)
  489. # Args stolen from git source: github.com/git/git/blob/master/pager.c
  490. pager = subprocess.Popen(['less', '-FRSX'],
  491. stdin=subprocess.PIPE, stdout=sys.stdout)
  492. try:
  493. for line in color_diff:
  494. pager.stdin.write(line.encode('utf-8'))
  495. except KeyboardInterrupt:
  496. pass
  497. pager.stdin.close()
  498. pager.wait()
  499. def check_command_status(arguments):
  500. """Return True if command returns 0."""
  501. try:
  502. return subprocess.call(
  503. arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0
  504. except OSError:
  505. return False
  506. def revision_control_diff(args):
  507. """Return diff from revision control system."""
  508. for _, ops in VCS_INFO.items():
  509. if check_command_status(ops['probe']):
  510. return subprocess.Popen(
  511. ops['diff'] + args, stdout=subprocess.PIPE).stdout
  512. def revision_control_log(args):
  513. """Return log from revision control system."""
  514. for _, ops in VCS_INFO.items():
  515. if check_command_status(ops['probe']):
  516. return subprocess.Popen(
  517. ops['log'] + args, stdout=subprocess.PIPE).stdout
  518. def decode(line):
  519. """Decode UTF-8 if necessary."""
  520. try:
  521. return line.decode('utf-8')
  522. except AttributeError:
  523. return line
  524. def main():
  525. import optparse
  526. supported_vcs = sorted(VCS_INFO.keys())
  527. usage = """%prog [options] [file|dir ...]"""
  528. parser = optparse.OptionParser(usage=usage,
  529. description=META_INFO['description'],
  530. version='%%prog %s' % META_INFO['version'])
  531. parser.add_option('-s', '--side-by-side', action='store_true',
  532. help='enable side-by-side mode')
  533. parser.add_option('-w', '--width', type='int', default=80, metavar='N',
  534. help='set text width (side-by-side mode only), default is 80')
  535. parser.add_option('-l', '--log', action='store_true',
  536. help='show log with changes from revision control')
  537. parser.add_option('-c', '--color', default='auto', metavar='X',
  538. help='colorize mode "auto" (default), "always", or "never"')
  539. opts, args = parser.parse_args()
  540. if opts.log:
  541. diff_hdl = revision_control_log(args)
  542. if not diff_hdl:
  543. sys.stderr.write(('*** Not in a supported workspace, supported '
  544. 'are: %s\n') % ', '.join(supported_vcs))
  545. return 1
  546. elif sys.stdin.isatty():
  547. diff_hdl = revision_control_diff(args)
  548. if not diff_hdl:
  549. sys.stderr.write(('*** Not in a supported workspace, supported '
  550. 'are: %s\n\n') % ', '.join(supported_vcs))
  551. parser.print_help()
  552. return 1
  553. else:
  554. diff_hdl = sys.stdin
  555. stream = PatchStream(diff_hdl)
  556. # Don't let empty diff pass thru
  557. if stream.is_empty():
  558. return 0
  559. if opts.color == 'always' or (opts.color == 'auto' and sys.stdout.isatty()):
  560. try:
  561. markup_to_pager(stream, opts)
  562. except IOError:
  563. e = sys.exc_info()[1]
  564. if e.errno == errno.EPIPE:
  565. pass
  566. else:
  567. # pipe out stream untouched to make sure it is still a patch
  568. for line in stream:
  569. sys.stdout.write(decode(line))
  570. if diff_hdl is not sys.stdin:
  571. diff_hdl.close()
  572. return 0
  573. if __name__ == '__main__':
  574. sys.exit(main())
  575. # vim:set et sts=4 sw=4 tw=80: