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