cdiff.py 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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.3',
  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 difflib
  31. COLORS = {
  32. 'reset' : '\x1b[0m',
  33. 'underline' : '\x1b[4m',
  34. 'reverse' : '\x1b[7m',
  35. 'red' : '\x1b[31m',
  36. 'green' : '\x1b[32m',
  37. 'yellow' : '\x1b[33m',
  38. 'blue' : '\x1b[34m',
  39. 'magenta' : '\x1b[35m',
  40. 'cyan' : '\x1b[36m',
  41. 'lightred' : '\x1b[1;31m',
  42. 'lightgreen' : '\x1b[1;32m',
  43. 'lightyellow' : '\x1b[1;33m',
  44. 'lightblue' : '\x1b[1;34m',
  45. 'lightmagenta' : '\x1b[1;35m',
  46. 'lightcyan' : '\x1b[1;36m',
  47. }
  48. # Keys for revision control probe, diff and log with diff
  49. VCS_INFO = {
  50. 'Git': {
  51. 'probe' : ['git', 'rev-parse'],
  52. 'diff' : ['git', 'diff', '--no-ext-diff'],
  53. 'log' : ['git', 'log', '--patch'],
  54. },
  55. 'Mercurial': {
  56. 'probe' : ['hg', 'summary'],
  57. 'diff' : ['hg', 'diff'],
  58. 'log' : ['hg', 'log', '--patch'],
  59. },
  60. 'Svn': {
  61. 'probe' : ['svn', 'info'],
  62. 'diff' : ['svn', 'diff'],
  63. 'log' : ['svn', 'log', '--diff', '--use-merge-history'],
  64. },
  65. }
  66. def colorize(text, start_color, end_color='reset'):
  67. return COLORS[start_color] + text + COLORS[end_color]
  68. class Hunk(object):
  69. def __init__(self, hunk_headers, hunk_meta, old_addr, new_addr):
  70. self._hunk_headers = hunk_headers
  71. self._hunk_meta = hunk_meta
  72. self._old_addr = old_addr # tuple (start, offset)
  73. self._new_addr = new_addr # tuple (start, offset)
  74. self._hunk_list = [] # list of tuple (attr, line)
  75. def append(self, hunk_line):
  76. """hunk_line is a 2-element tuple: (attr, text), where attr is:
  77. '-': old, '+': new, ' ': common
  78. """
  79. self._hunk_list.append(hunk_line)
  80. def mdiff(self):
  81. r"""The difflib._mdiff() function returns an interator which returns a
  82. tuple: (from line tuple, to line tuple, boolean flag)
  83. from/to line tuple -- (line num, line text)
  84. line num -- integer or None (to indicate a context separation)
  85. line text -- original line text with following markers inserted:
  86. '\0+' -- marks start of added text
  87. '\0-' -- marks start of deleted text
  88. '\0^' -- marks start of changed text
  89. '\1' -- marks end of added/deleted/changed text
  90. boolean flag -- None indicates context separation, True indicates
  91. either "from" or "to" line contains a change, otherwise False.
  92. """
  93. return difflib._mdiff(self._get_old_text(), self._get_new_text())
  94. def _get_old_text(self):
  95. out = []
  96. for (attr, line) in self._hunk_list:
  97. if attr != '+':
  98. out.append(line)
  99. return out
  100. def _get_new_text(self):
  101. out = []
  102. for (attr, line) in self._hunk_list:
  103. if attr != '-':
  104. out.append(line)
  105. return out
  106. class UnifiedDiff(object):
  107. def __init__(self, headers, old_path, new_path, hunks):
  108. self._headers = headers
  109. self._old_path = old_path
  110. self._new_path = new_path
  111. self._hunks = hunks
  112. def is_old_path(self, line):
  113. return line.startswith('--- ')
  114. def is_new_path(self, line):
  115. return line.startswith('+++ ')
  116. def is_hunk_meta(self, line):
  117. """Minimal valid hunk meta is like '@@ -1 +1 @@', note extra chars
  118. might occur after the ending @@, e.g. in git log. '## ' usually
  119. indicates svn property changes in output from `svn log --diff`
  120. """
  121. return (line.startswith('@@ -') and line.find(' @@') >= 8) or \
  122. (line.startswith('## -') and line.find(' ##') >= 8)
  123. def parse_hunk_meta(self, hunk_meta):
  124. # @@ -3,7 +3,6 @@
  125. a = hunk_meta.split()[1].split(',') # -3 7
  126. if len(a) > 1:
  127. old_addr = (int(a[0][1:]), int(a[1]))
  128. else:
  129. # @@ -1 +1,2 @@
  130. old_addr = (int(a[0][1:]), 0)
  131. b = hunk_meta.split()[2].split(',') # +3 6
  132. if len(b) > 1:
  133. new_addr = (int(b[0][1:]), int(b[1]))
  134. else:
  135. # @@ -0,0 +1 @@
  136. new_addr = (int(b[0][1:]), 0)
  137. return (old_addr, new_addr)
  138. def parse_hunk_line(self, line):
  139. return (line[0], line[1:])
  140. def is_old(self, line):
  141. """Exclude old path and header line from svn log --diff output, allow
  142. '----' likely to see in diff from yaml file
  143. """
  144. return line.startswith('-') and not self.is_old_path(line) and \
  145. not re.match(r'^-{72}$', line.rstrip())
  146. def is_new(self, line):
  147. return line.startswith('+') and not self.is_new_path(line)
  148. def is_common(self, line):
  149. return line.startswith(' ')
  150. def is_eof(self, line):
  151. # \ No newline at end of file
  152. # \ No newline at end of property
  153. return line.startswith(r'\ No newline at end of')
  154. def is_only_in_dir(self, line):
  155. return line.startswith('Only in ')
  156. def is_binary_differ(self, line):
  157. return re.match('^Binary files .* differ$', line.rstrip())
  158. class PatchStream(object):
  159. def __init__(self, diff_hdl):
  160. self._diff_hdl = diff_hdl
  161. self._stream_header_size = 0
  162. self._stream_header = []
  163. # Test whether stream is empty by read 1 line
  164. line = self._diff_hdl.readline()
  165. if not line:
  166. self._is_empty = True
  167. else:
  168. self._stream_header.append(line)
  169. self._stream_header_size += 1
  170. self._is_empty = False
  171. def is_empty(self):
  172. return self._is_empty
  173. def read_stream_header(self, stream_header_size):
  174. """Returns a small chunk for patch type detect, suppose to call once"""
  175. for i in range(1, stream_header_size):
  176. line = self._diff_hdl.readline()
  177. if not line:
  178. break
  179. self._stream_header.append(line)
  180. self._stream_header_size += 1
  181. return self._stream_header
  182. def __iter__(self):
  183. for line in self._stream_header:
  184. yield line
  185. for line in self._diff_hdl:
  186. yield line
  187. class PatchStreamForwarder(object):
  188. """A blocking stream forwarder use `select` and line buffered mode. Feed
  189. input stream to a diff format translator and read output stream from it.
  190. Note input stream is non-seekable, and upstream has eaten some lines.
  191. """
  192. def __init__(self, istream, translator):
  193. assert isinstance(istream, PatchStream)
  194. assert isinstance(translator, subprocess.Popen)
  195. self._istream = iter(istream)
  196. self._in = translator.stdin
  197. self._out = translator.stdout
  198. def _can_read(self, timeout=0):
  199. return select.select([self._out.fileno()], [], [], timeout)[0]
  200. def _forward_line(self):
  201. try:
  202. line = next(self._istream)
  203. self._in.write(line.encode('utf-8'))
  204. except StopIteration:
  205. self._in.close()
  206. def __iter__(self):
  207. while True:
  208. if self._can_read():
  209. line = self._out.readline()
  210. if line:
  211. yield line
  212. else:
  213. return
  214. elif not self._in.closed:
  215. self._forward_line()
  216. class DiffParser(object):
  217. def __init__(self, stream):
  218. header = [decode(line) for line in stream.read_stream_header(100)]
  219. size = len(header)
  220. if size >= 4 and (header[0].startswith('*** ') and
  221. header[1].startswith('--- ') and
  222. header[2].rstrip() == '***************' and
  223. header[3].startswith('*** ') and
  224. header[3].rstrip().endswith(' ****')):
  225. # For context diff, try use `filterdiff` to translate it to unified
  226. # format and provide a new stream
  227. #
  228. self._type = 'context'
  229. try:
  230. # Use line buffered mode so that to readline() in block mode
  231. self._translator = subprocess.Popen(
  232. ['filterdiff', '--format=unified'], stdin=subprocess.PIPE,
  233. stdout=subprocess.PIPE, bufsize=1)
  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. """Pipe unified diff stream to pager (less).
  495. Note: have to create pager Popen object before the translator Popen object
  496. in PatchStreamForwarder, otherwise the `stdin=subprocess.PIPE` would cause
  497. trouble to the translator pipe (select() never see EOF after input stream
  498. ended), most likely python bug 12607 (http://bugs.python.org/issue12607)
  499. which was fixed in python 2.7.3.
  500. See issue #30 (https://github.com/ymattw/cdiff/issues/30) for more
  501. information.
  502. """
  503. # Args stolen from git source: github.com/git/git/blob/master/pager.c
  504. pager = subprocess.Popen(
  505. ['less', '-FRSX'], stdin=subprocess.PIPE, stdout=sys.stdout)
  506. diffs = DiffParser(stream).get_diff_generator()
  507. marker = DiffMarker()
  508. color_diff = marker.markup(diffs, side_by_side=opts.side_by_side,
  509. width=opts.width)
  510. for line in color_diff:
  511. pager.stdin.write(line.encode('utf-8'))
  512. pager.stdin.close()
  513. pager.wait()
  514. def check_command_status(arguments):
  515. """Return True if command returns 0."""
  516. try:
  517. return subprocess.call(
  518. arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0
  519. except OSError:
  520. return False
  521. def revision_control_diff(args):
  522. """Return diff from revision control system."""
  523. for _, ops in VCS_INFO.items():
  524. if check_command_status(ops['probe']):
  525. return subprocess.Popen(
  526. ops['diff'] + args, stdout=subprocess.PIPE).stdout
  527. def revision_control_log(args):
  528. """Return log from revision control system."""
  529. for _, ops in VCS_INFO.items():
  530. if check_command_status(ops['probe']):
  531. return subprocess.Popen(
  532. ops['log'] + args, stdout=subprocess.PIPE).stdout
  533. def decode(line):
  534. """Decode UTF-8 if necessary."""
  535. try:
  536. return line.decode('utf-8')
  537. except (AttributeError, UnicodeDecodeError):
  538. return line
  539. def main():
  540. signal.signal(signal.SIGPIPE, signal.SIG_DFL)
  541. signal.signal(signal.SIGINT, signal.SIG_DFL)
  542. from optparse import (OptionParser, BadOptionError, AmbiguousOptionError,
  543. OptionGroup)
  544. class PassThroughOptionParser(OptionParser):
  545. """Stop parsing on first unknown option (e.g. --cached, -U10) and pass
  546. them down. Note the `opt_str` in exception object does not give us
  547. chance to take the full option back, e.g. for '-U10' it will only
  548. contain '-U' and the '10' part will be lost. Ref: http://goo.gl/IqY4A
  549. (on stackoverflow). My hack is to try parse and insert a '--' in place
  550. and parse again. Let me know if someone has better solution.
  551. """
  552. def _process_args(self, largs, rargs, values):
  553. left = largs[:]
  554. right = rargs[:]
  555. try:
  556. OptionParser._process_args(self, left, right, values)
  557. except (BadOptionError, AmbiguousOptionError):
  558. parsed_num = len(rargs) - len(right) - 1
  559. rargs.insert(parsed_num, '--')
  560. OptionParser._process_args(self, largs, rargs, values)
  561. supported_vcs = sorted(VCS_INFO.keys())
  562. usage = """%prog [options] [file|dir ...]"""
  563. parser = PassThroughOptionParser(
  564. usage=usage, description=META_INFO['description'],
  565. version='%%prog %s' % META_INFO['version'])
  566. parser.add_option(
  567. '-s', '--side-by-side', action='store_true',
  568. help='enable side-by-side mode')
  569. parser.add_option(
  570. '-w', '--width', type='int', default=80, metavar='N',
  571. help='set text width for side-by-side mode, default is 80')
  572. parser.add_option(
  573. '-l', '--log', action='store_true',
  574. help='show log with changes from revision control')
  575. parser.add_option(
  576. '-c', '--color', default='auto', metavar='M',
  577. help="""colorize mode 'auto' (default), 'always', or 'never'""")
  578. # Hack: use OptionGroup text for extra help message after option list
  579. option_group = OptionGroup(
  580. parser, "Note", ("Option parser will stop on first unknown option "
  581. "and pass them down to underneath revision control"))
  582. parser.add_option_group(option_group)
  583. opts, args = parser.parse_args()
  584. if opts.log:
  585. diff_hdl = revision_control_log(args)
  586. if not diff_hdl:
  587. sys.stderr.write(('*** Not in a supported workspace, supported '
  588. 'are: %s\n') % ', '.join(supported_vcs))
  589. return 1
  590. elif sys.stdin.isatty():
  591. diff_hdl = revision_control_diff(args)
  592. if not diff_hdl:
  593. sys.stderr.write(('*** Not in a supported workspace, supported '
  594. 'are: %s\n\n') % ', '.join(supported_vcs))
  595. parser.print_help()
  596. return 1
  597. else:
  598. diff_hdl = sys.stdin
  599. stream = PatchStream(diff_hdl)
  600. # Don't let empty diff pass thru
  601. if stream.is_empty():
  602. return 0
  603. if opts.color == 'always' or \
  604. (opts.color == 'auto' and sys.stdout.isatty()):
  605. markup_to_pager(stream, opts)
  606. else:
  607. # pipe out stream untouched to make sure it is still a patch
  608. if sys.hexversion < 0x03000000:
  609. reload(sys).setdefaultencoding('utf8')
  610. for line in stream:
  611. sys.stdout.write(decode(line))
  612. if diff_hdl is not sys.stdin:
  613. diff_hdl.close()
  614. return 0
  615. if __name__ == '__main__':
  616. sys.exit(main())
  617. # vim:set et sts=4 sw=4 tw=79: