cdiff.py 23KB

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