123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  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.9.2',
  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") # pragma: no cover
  21. import re
  22. import signal
  23. import subprocess
  24. import fcntl
  25. import os
  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', '--no-ext-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', '--use-merge-history'],
  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 append(self, hunk_line):
  72. """hunk_line is a 2-element tuple: (attr, text), where attr is:
  73. '-': old, '+': new, ' ': common
  74. """
  75. self._hunk_list.append(hunk_line)
  76. def mdiff(self):
  77. r"""The difflib._mdiff() function returns an interator which returns a
  78. tuple: (from line tuple, to line tuple, boolean flag)
  79. from/to line tuple -- (line num, line text)
  80. line num -- integer or None (to indicate a context separation)
  81. line text -- original line text with following markers inserted:
  82. '\0+' -- marks start of added text
  83. '\0-' -- marks start of deleted text
  84. '\0^' -- marks start of changed text
  85. '\1' -- marks end of added/deleted/changed text
  86. boolean flag -- None indicates context separation, True indicates
  87. either "from" or "to" line contains a change, otherwise False.
  88. """
  89. return difflib._mdiff(self._get_old_text(), self._get_new_text())
  90. def _get_old_text(self):
  91. out = []
  92. for (attr, line) in self._hunk_list:
  93. if attr != '+':
  94. out.append(line)
  95. return out
  96. def _get_new_text(self):
  97. out = []
  98. for (attr, line) in self._hunk_list:
  99. if attr != '-':
  100. out.append(line)
  101. return out
  102. class UnifiedDiff(object):
  103. def __init__(self, headers, old_path, new_path, hunks):
  104. self._headers = headers
  105. self._old_path = old_path
  106. self._new_path = new_path
  107. self._hunks = hunks
  108. def is_old_path(self, line):
  109. return line.startswith('--- ')
  110. def is_new_path(self, line):
  111. return line.startswith('+++ ')
  112. def is_hunk_meta(self, line):
  113. """Minimal valid hunk meta is like '@@ -1 +1 @@', note extra chars
  114. might occur after the ending @@, e.g. in git log. '## ' usually
  115. indicates svn property changes in output from `svn log --diff`
  116. """
  117. return (line.startswith('@@ -') and line.find(' @@') >= 8) or \
  118. (line.startswith('## -') and line.find(' ##') >= 8)
  119. def parse_hunk_meta(self, hunk_meta):
  120. # @@ -3,7 +3,6 @@
  121. a = hunk_meta.split()[1].split(',') # -3 7
  122. if len(a) > 1:
  123. old_addr = (int(a[0][1:]), int(a[1]))
  124. else:
  125. # @@ -1 +1,2 @@
  126. old_addr = (int(a[0][1:]), 0)
  127. b = hunk_meta.split()[2].split(',') # +3 6
  128. if len(b) > 1:
  129. new_addr = (int(b[0][1:]), int(b[1]))
  130. else:
  131. # @@ -0,0 +1 @@
  132. new_addr = (int(b[0][1:]), 0)
  133. return (old_addr, new_addr)
  134. def parse_hunk_line(self, line):
  135. return (line[0], line[1:])
  136. def is_old(self, line):
  137. """Exclude old path and header line from svn log --diff output, allow
  138. '----' likely to see in diff from yaml file
  139. """
  140. return line.startswith('-') and not self.is_old_path(line) and \
  141. not re.match(r'^-{72}$', line.rstrip())
  142. def is_new(self, line):
  143. return line.startswith('+') and not self.is_new_path(line)
  144. def is_common(self, line):
  145. return line.startswith(' ')
  146. def is_eof(self, line):
  147. # \ No newline at end of file
  148. # \ No newline at end of property
  149. return line.startswith(r'\ No newline at end of')
  150. def is_only_in_dir(self, line):
  151. return line.startswith('Only in ')
  152. def is_binary_differ(self, line):
  153. return re.match('^Binary files .* differ$', line.rstrip())
  154. class PatchStream(object):
  155. def __init__(self, diff_hdl):
  156. self._diff_hdl = diff_hdl
  157. self._stream_header_size = 0
  158. self._stream_header = []
  159. # Test whether stream is empty by read 1 line
  160. line = self._diff_hdl.readline()
  161. if not line:
  162. self._is_empty = True
  163. else:
  164. self._stream_header.append(line)
  165. self._stream_header_size += 1
  166. self._is_empty = False
  167. def is_empty(self):
  168. return self._is_empty
  169. def read_stream_header(self, stream_header_size):
  170. """Returns a small chunk for patch type detect, suppose to call once"""
  171. for i in range(1, stream_header_size):
  172. line = self._diff_hdl.readline()
  173. if not line:
  174. break
  175. self._stream_header.append(line)
  176. self._stream_header_size += 1
  177. return self._stream_header
  178. def __iter__(self):
  179. for line in self._stream_header:
  180. yield line
  181. for line in self._diff_hdl:
  182. yield line
  183. class PatchStreamForwarder(object):
  184. """A non-block stream forwarder. Note input stream is non-seekable, and
  185. upstream has eaten some lines.
  186. """
  187. def __init__(self, istream, translator):
  188. assert isinstance(istream, PatchStream)
  189. self._istream = istream
  190. self._translator = translator
  191. self._set_non_block(self._translator.stdin)
  192. self._set_non_block(self._translator.stdout)
  193. self._forward_until_block()
  194. def _set_non_block(self, hdl):
  195. fd = hdl.fileno()
  196. fl = fcntl.fcntl(fd, fcntl.F_GETFL)
  197. fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
  198. def _forward_until_block(self):
  199. for line in self._istream:
  200. try:
  201. self._translator.stdin.write(line.encode('utf-8'))
  202. except IOError:
  203. break # EAGAIN
  204. else:
  205. self._translator.stdin.close()
  206. def __iter__(self):
  207. while True:
  208. try:
  209. line = self._translator.stdout.readline()
  210. if not line:
  211. return
  212. yield line
  213. except IOError:
  214. if not self._translator.stdin.closed:
  215. self._forward_until_block()
  216. continue # EAGAIN
  217. class DiffParser(object):
  218. def __init__(self, stream):
  219. header = [decode(line) for line in stream.read_stream_header(100)]
  220. size = len(header)
  221. if size >= 4 and (header[0].startswith('*** ') and
  222. header[1].startswith('--- ') and
  223. header[2].rstrip() == '***************' and
  224. header[3].startswith('*** ') and
  225. header[3].rstrip().endswith(' ****')):
  226. # For context diff, try use `filterdiff` to translate it to unified
  227. # format and provide a new stream
  228. #
  229. self._type = 'context'
  230. try:
  231. self._translator = subprocess.Popen(
  232. ['filterdiff', '--format=unified'], stdin=subprocess.PIPE,
  233. stdout=subprocess.PIPE)
  234. except OSError:
  235. raise SystemExit('*** Context diff support depends on '
  236. 'filterdiff')
  237. self._stream = PatchStreamForwarder(stream, self._translator)
  238. return
  239. for n in range(size):
  240. if header[n].startswith('--- ') and (n < size - 1) and \
  241. header[n+1].startswith('+++ '):
  242. self._type = 'unified'
  243. self._stream = stream
  244. break
  245. else:
  246. # `filterdiff` translates unknown diff to nothing, fall through to
  247. # unified diff give cdiff a chance to show everything as headers
  248. #
  249. sys.stderr.write("*** unknown format, fall through to 'unified'\n")
  250. self._type = 'unified'
  251. self._stream = stream
  252. def get_diff_generator(self):
  253. """parse all diff lines, construct a list of UnifiedDiff objects"""
  254. diff = UnifiedDiff([], None, None, [])
  255. headers = []
  256. for line in self._stream:
  257. line = decode(line)
  258. if diff.is_old_path(line):
  259. # FIXME: '--- ' breaks here, better to probe next line
  260. if diff._old_path and diff._new_path and diff._hunks:
  261. # See a new diff, yield previous diff if exists
  262. yield diff
  263. diff = UnifiedDiff(headers, line, None, [])
  264. headers = []
  265. elif diff.is_new_path(line) and diff._old_path:
  266. diff._new_path = line
  267. elif diff.is_hunk_meta(line):
  268. hunk_meta = line
  269. try:
  270. old_addr, new_addr = diff.parse_hunk_meta(hunk_meta)
  271. except (IndexError, ValueError):
  272. raise RuntimeError('invalid hunk meta: %s' % hunk_meta)
  273. hunk = Hunk(headers, hunk_meta, old_addr, new_addr)
  274. headers = []
  275. diff._hunks.append(hunk)
  276. elif diff._hunks and not headers and (diff.is_old(line) or
  277. diff.is_new(line) or
  278. diff.is_common(line)):
  279. diff._hunks[-1].append(diff.parse_hunk_line(line))
  280. elif diff.is_eof(line):
  281. # ignore
  282. pass
  283. elif diff.is_only_in_dir(line) or \
  284. diff.is_binary_differ(line):
  285. # 'Only in foo:' and 'Binary files ... differ' are considered
  286. # as separate diffs, so yield current diff, then this line
  287. #
  288. if diff._old_path and diff._new_path and diff._hunks:
  289. # Current diff is comppletely constructed
  290. yield diff
  291. headers.append(line)
  292. yield UnifiedDiff(headers, '', '', [])
  293. headers = []
  294. diff = UnifiedDiff([], None, None, [])
  295. else:
  296. # All other non-recognized lines are considered as headers or
  297. # hunk headers respectively
  298. #
  299. headers.append(line)
  300. # Validate and yield the last patch set if it is not yielded yet
  301. if diff._old_path:
  302. assert diff._new_path is not None
  303. if diff._hunks:
  304. assert len(diff._hunks[-1]._hunk_meta) > 0
  305. assert len(diff._hunks[-1]._hunk_list) > 0
  306. yield diff
  307. if headers:
  308. # Tolerate dangling headers, just yield a UnifiedDiff object with
  309. # only header lines
  310. #
  311. yield UnifiedDiff(headers, '', '', [])
  312. class DiffMarker(object):
  313. def markup(self, diffs, side_by_side=False, width=0):
  314. """Returns a generator"""
  315. if side_by_side:
  316. for diff in diffs:
  317. for line in self._markup_side_by_side(diff, width):
  318. yield line
  319. else:
  320. for diff in diffs:
  321. for line in self._markup_traditional(diff):
  322. yield line
  323. def _markup_traditional(self, diff):
  324. """Returns a generator"""
  325. for line in diff._headers:
  326. yield self._markup_header(line)
  327. yield self._markup_old_path(diff._old_path)
  328. yield self._markup_new_path(diff._new_path)
  329. for hunk in diff._hunks:
  330. for hunk_header in hunk._hunk_headers:
  331. yield self._markup_hunk_header(hunk_header)
  332. yield self._markup_hunk_meta(hunk._hunk_meta)
  333. for old, new, changed in hunk.mdiff():
  334. if changed:
  335. if not old[0]:
  336. # The '+' char after \x00 is kept
  337. # DEBUG: yield 'NEW: %s %s\n' % (old, new)
  338. line = new[1].strip('\x00\x01')
  339. yield self._markup_new(line)
  340. elif not new[0]:
  341. # The '-' char after \x00 is kept
  342. # DEBUG: yield 'OLD: %s %s\n' % (old, new)
  343. line = old[1].strip('\x00\x01')
  344. yield self._markup_old(line)
  345. else:
  346. # DEBUG: yield 'CHG: %s %s\n' % (old, new)
  347. yield self._markup_old('-') + \
  348. self._markup_mix(old[1], 'red')
  349. yield self._markup_new('+') + \
  350. self._markup_mix(new[1], 'green')
  351. else:
  352. yield self._markup_common(' ' + old[1])
  353. def _markup_side_by_side(self, diff, width):
  354. """Returns a generator"""
  355. wrap_char = colorize('>', 'lightmagenta')
  356. def _normalize(line):
  357. return line.replace(
  358. '\t', ' ' * 8).replace('\n', '').replace('\r', '')
  359. def _fit_with_marker(text, markup_fn, width, pad=False):
  360. """Wrap or pad input pure text, then markup"""
  361. if len(text) > width:
  362. return markup_fn(text[:(width - 1)]) + wrap_char
  363. elif pad:
  364. pad_len = width - len(text)
  365. return '%s%*s' % (markup_fn(text), pad_len, '')
  366. else:
  367. return markup_fn(text)
  368. def _fit_with_marker_mix(text, base_color, width, pad=False):
  369. """Wrap or pad input text which contains mdiff tags, markup at the
  370. meantime, note only left side need to set `pad`
  371. """
  372. out = [COLORS[base_color]]
  373. count = 0
  374. tag_re = re.compile(r'\x00[+^-]|\x01')
  375. while text and count < width:
  376. if text.startswith('\x00-'): # del
  377. out.append(COLORS['reverse'] + COLORS[base_color])
  378. text = text[2:]
  379. elif text.startswith('\x00+'): # add
  380. out.append(COLORS['reverse'] + COLORS[base_color])
  381. text = text[2:]
  382. elif text.startswith('\x00^'): # change
  383. out.append(COLORS['underline'] + COLORS[base_color])
  384. text = text[2:]
  385. elif text.startswith('\x01'): # reset
  386. out.append(COLORS['reset'] + COLORS[base_color])
  387. text = text[1:]
  388. else:
  389. # FIXME: utf-8 wchar might break the rule here, e.g.
  390. # u'\u554a' takes double width of a single letter, also
  391. # this depends on your terminal font. I guess audience of
  392. # this tool never put that kind of symbol in their code :-)
  393. #
  394. out.append(text[0])
  395. count += 1
  396. text = text[1:]
  397. if count == width and tag_re.sub('', text):
  398. # Was stripped: output fulfil and still has normal char in text
  399. out[-1] = COLORS['reset'] + wrap_char
  400. elif count < width and pad:
  401. pad_len = width - count
  402. out.append('%s%*s' % (COLORS['reset'], pad_len, ''))
  403. else:
  404. out.append(COLORS['reset'])
  405. return ''.join(out)
  406. # Set up line width
  407. if width <= 0:
  408. width = 80
  409. # Set up number width, note last hunk might be empty
  410. try:
  411. (start, offset) = diff._hunks[-1]._old_addr
  412. max1 = start + offset - 1
  413. (start, offset) = diff._hunks[-1]._new_addr
  414. max2 = start + offset - 1
  415. except IndexError:
  416. max1 = max2 = 0
  417. num_width = max(len(str(max1)), len(str(max2)))
  418. # Setup lineno and line format
  419. left_num_fmt = colorize('%%(left_num)%ds' % num_width, 'yellow')
  420. right_num_fmt = colorize('%%(right_num)%ds' % num_width, 'yellow')
  421. line_fmt = left_num_fmt + ' %(left)s ' + COLORS['reset'] + \
  422. right_num_fmt + ' %(right)s\n'
  423. # yield header, old path and new path
  424. for line in diff._headers:
  425. yield self._markup_header(line)
  426. yield self._markup_old_path(diff._old_path)
  427. yield self._markup_new_path(diff._new_path)
  428. # yield hunks
  429. for hunk in diff._hunks:
  430. for hunk_header in hunk._hunk_headers:
  431. yield self._markup_hunk_header(hunk_header)
  432. yield self._markup_hunk_meta(hunk._hunk_meta)
  433. for old, new, changed in hunk.mdiff():
  434. if old[0]:
  435. left_num = str(hunk._old_addr[0] + int(old[0]) - 1)
  436. else:
  437. left_num = ' '
  438. if new[0]:
  439. right_num = str(hunk._new_addr[0] + int(new[0]) - 1)
  440. else:
  441. right_num = ' '
  442. left = _normalize(old[1])
  443. right = _normalize(new[1])
  444. if changed:
  445. if not old[0]:
  446. left = '%*s' % (width, ' ')
  447. right = right.lstrip('\x00+').rstrip('\x01')
  448. right = _fit_with_marker(
  449. right, self._markup_new, width)
  450. elif not new[0]:
  451. left = left.lstrip('\x00-').rstrip('\x01')
  452. left = _fit_with_marker(left, self._markup_old, width)
  453. right = ''
  454. else:
  455. left = _fit_with_marker_mix(left, 'red', width, 1)
  456. right = _fit_with_marker_mix(right, 'green', width)
  457. else:
  458. left = _fit_with_marker(
  459. left, self._markup_common, width, 1)
  460. right = _fit_with_marker(right, self._markup_common, width)
  461. yield line_fmt % {
  462. 'left_num': left_num,
  463. 'left': left,
  464. 'right_num': right_num,
  465. 'right': right
  466. }
  467. def _markup_header(self, line):
  468. return colorize(line, 'cyan')
  469. def _markup_old_path(self, line):
  470. return colorize(line, 'yellow')
  471. def _markup_new_path(self, line):
  472. return colorize(line, 'yellow')
  473. def _markup_hunk_header(self, line):
  474. return colorize(line, 'lightcyan')
  475. def _markup_hunk_meta(self, line):
  476. return colorize(line, 'lightblue')
  477. def _markup_common(self, line):
  478. return colorize(line, 'reset')
  479. def _markup_old(self, line):
  480. return colorize(line, 'lightred')
  481. def _markup_new(self, line):
  482. return colorize(line, 'lightgreen')
  483. def _markup_mix(self, line, base_color):
  484. del_code = COLORS['reverse'] + COLORS[base_color]
  485. add_code = COLORS['reverse'] + COLORS[base_color]
  486. chg_code = COLORS['underline'] + COLORS[base_color]
  487. rst_code = COLORS['reset'] + COLORS[base_color]
  488. line = line.replace('\x00-', del_code)
  489. line = line.replace('\x00+', add_code)
  490. line = line.replace('\x00^', chg_code)
  491. line = line.replace('\x01', rst_code)
  492. return colorize(line, base_color)
  493. def markup_to_pager(stream, opts):
  494. diffs = DiffParser(stream).get_diff_generator()
  495. marker = DiffMarker()
  496. color_diff = marker.markup(diffs, side_by_side=opts.side_by_side,
  497. width=opts.width)
  498. # Args stolen from git source: github.com/git/git/blob/master/pager.c
  499. pager = subprocess.Popen(
  500. ['less', '-FRSX'], stdin=subprocess.PIPE, stdout=sys.stdout)
  501. for line in color_diff:
  502. pager.stdin.write(line.encode('utf-8'))
  503. pager.stdin.close()
  504. pager.wait()
  505. def check_command_status(arguments):
  506. """Return True if command returns 0."""
  507. try:
  508. return subprocess.call(
  509. arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0
  510. except OSError:
  511. return False
  512. def revision_control_diff(args):
  513. """Return diff from revision control system."""
  514. for _, ops in VCS_INFO.items():
  515. if check_command_status(ops['probe']):
  516. return subprocess.Popen(
  517. ops['diff'] + args, stdout=subprocess.PIPE).stdout
  518. def revision_control_log(args):
  519. """Return log from revision control system."""
  520. for _, ops in VCS_INFO.items():
  521. if check_command_status(ops['probe']):
  522. return subprocess.Popen(
  523. ops['log'] + args, stdout=subprocess.PIPE).stdout
  524. def decode(line):
  525. """Decode UTF-8 if necessary."""
  526. try:
  527. return line.decode('utf-8')
  528. except (AttributeError, UnicodeDecodeError):
  529. return line
  530. def main():
  531. signal.signal(signal.SIGPIPE, signal.SIG_DFL)
  532. signal.signal(signal.SIGINT, signal.SIG_DFL)
  533. from optparse import (OptionParser, BadOptionError, AmbiguousOptionError,
  534. OptionGroup)
  535. class PassThroughOptionParser(OptionParser):
  536. """Stop parsing on first unknown option (e.g. --cached, -U10) and pass
  537. them down. Note the `opt_str` in exception object does not give us
  538. chance to take the full option back, e.g. for '-U10' it will only
  539. contain '-U' and the '10' part will be lost. Ref: http://goo.gl/IqY4A
  540. (on stackoverflow). My hack is to try parse and insert a '--' in place
  541. and parse again. Let me know if someone has better solution.
  542. """
  543. def _process_args(self, largs, rargs, values):
  544. left = largs[:]
  545. right = rargs[:]
  546. try:
  547. OptionParser._process_args(self, left, right, values)
  548. except (BadOptionError, AmbiguousOptionError):
  549. parsed_num = len(rargs) - len(right) - 1
  550. rargs.insert(parsed_num, '--')
  551. OptionParser._process_args(self, largs, rargs, values)
  552. supported_vcs = sorted(VCS_INFO.keys())
  553. usage = """%prog [options] [file|dir ...]"""
  554. parser = PassThroughOptionParser(
  555. usage=usage, description=META_INFO['description'],
  556. version='%%prog %s' % META_INFO['version'])
  557. parser.add_option(
  558. '-s', '--side-by-side', action='store_true',
  559. help='enable side-by-side mode')
  560. parser.add_option(
  561. '-w', '--width', type='int', default=80, metavar='N',
  562. help='set text width for side-by-side mode, default is 80')
  563. parser.add_option(
  564. '-l', '--log', action='store_true',
  565. help='show log with changes from revision control')
  566. parser.add_option(
  567. '-c', '--color', default='auto', metavar='M',
  568. help="""colorize mode 'auto' (default), 'always', or 'never'""")
  569. # Hack: use OptionGroup text for extra help message after option list
  570. option_group = OptionGroup(
  571. parser, "Note", ("Option parser will stop on first unknown option "
  572. "and pass them down to underneath revision control"))
  573. parser.add_option_group(option_group)
  574. opts, args = parser.parse_args()
  575. if opts.log:
  576. diff_hdl = revision_control_log(args)
  577. if not diff_hdl:
  578. sys.stderr.write(('*** Not in a supported workspace, supported '
  579. 'are: %s\n') % ', '.join(supported_vcs))
  580. return 1
  581. elif sys.stdin.isatty():
  582. diff_hdl = revision_control_diff(args)
  583. if not diff_hdl:
  584. sys.stderr.write(('*** Not in a supported workspace, supported '
  585. 'are: %s\n\n') % ', '.join(supported_vcs))
  586. parser.print_help()
  587. return 1
  588. else:
  589. diff_hdl = sys.stdin
  590. stream = PatchStream(diff_hdl)
  591. # Don't let empty diff pass thru
  592. if stream.is_empty():
  593. return 0
  594. if opts.color == 'always' or \
  595. (opts.color == 'auto' and sys.stdout.isatty()):
  596. markup_to_pager(stream, opts)
  597. else:
  598. # pipe out stream untouched to make sure it is still a patch
  599. if sys.hexversion < 0x03000000:
  600. reload(sys).setdefaultencoding('utf8')
  601. for line in stream:
  602. sys.stdout.write(decode(line))
  603. if diff_hdl is not sys.stdin:
  604. diff_hdl.close()
  605. return 0
  606. if __name__ == '__main__':
  607. sys.exit(main())
  608. # vim:set et sts=4 sw=4 tw=79: