cdiff.py 23KB

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