cdiff.py 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  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. # XXX: close() does not notify select() for EOF event in python
  207. # 2.x, one of these two interface must be buggy
  208. #
  209. # Sending EOF manually does not work either
  210. #
  211. #print('StopIteration, closing (sending EOF)')
  212. #self._in.write('\x1a'.encode('utf-8'))
  213. self._in.close()
  214. def __iter__(self):
  215. while True:
  216. if self._can_read():
  217. line = self._out.readline()
  218. if line:
  219. yield line
  220. else:
  221. #print('got EOF')
  222. return
  223. elif not self._in.closed:
  224. self._forward_line()
  225. else:
  226. #print('no data to read and istream closed')
  227. # XXX: `close` or `select` seems buggy in python 2.x, select
  228. # does not tell ready event on _translator.stdout anymore once
  229. # the stdin is closed. Just add a timeout here to detect, when
  230. # that happen the remaining in output stream will be discarded
  231. #
  232. if not self._can_read(0.5):
  233. return
  234. class DiffParser(object):
  235. def __init__(self, stream):
  236. header = [decode(line) for line in stream.read_stream_header(100)]
  237. size = len(header)
  238. if size >= 4 and (header[0].startswith('*** ') and
  239. header[1].startswith('--- ') and
  240. header[2].rstrip() == '***************' and
  241. header[3].startswith('*** ') and
  242. header[3].rstrip().endswith(' ****')):
  243. # For context diff, try use `filterdiff` to translate it to unified
  244. # format and provide a new stream
  245. #
  246. self._type = 'context'
  247. try:
  248. # Use line buffered mode so that to readline() in block mode
  249. self._translator = subprocess.Popen(
  250. ['filterdiff', '--format=unified'], stdin=subprocess.PIPE,
  251. stdout=subprocess.PIPE, bufsize=1)
  252. except OSError:
  253. raise SystemExit('*** Context diff support depends on '
  254. 'filterdiff')
  255. self._stream = PatchStreamForwarder(stream, self._translator)
  256. return
  257. for n in range(size):
  258. if header[n].startswith('--- ') and (n < size - 1) and \
  259. header[n+1].startswith('+++ '):
  260. self._type = 'unified'
  261. self._stream = stream
  262. break
  263. else:
  264. # `filterdiff` translates unknown diff to nothing, fall through to
  265. # unified diff give cdiff a chance to show everything as headers
  266. #
  267. sys.stderr.write("*** unknown format, fall through to 'unified'\n")
  268. self._type = 'unified'
  269. self._stream = stream
  270. def get_diff_generator(self):
  271. """parse all diff lines, construct a list of UnifiedDiff objects"""
  272. diff = UnifiedDiff([], None, None, [])
  273. headers = []
  274. for line in self._stream:
  275. line = decode(line)
  276. if diff.is_old_path(line):
  277. # FIXME: '--- ' breaks here, better to probe next line
  278. if diff._old_path and diff._new_path and diff._hunks:
  279. # See a new diff, yield previous diff if exists
  280. yield diff
  281. diff = UnifiedDiff(headers, line, None, [])
  282. headers = []
  283. elif diff.is_new_path(line) and diff._old_path:
  284. diff._new_path = line
  285. elif diff.is_hunk_meta(line):
  286. hunk_meta = line
  287. try:
  288. old_addr, new_addr = diff.parse_hunk_meta(hunk_meta)
  289. except (IndexError, ValueError):
  290. raise RuntimeError('invalid hunk meta: %s' % hunk_meta)
  291. hunk = Hunk(headers, hunk_meta, old_addr, new_addr)
  292. headers = []
  293. diff._hunks.append(hunk)
  294. elif diff._hunks and not headers and (diff.is_old(line) or
  295. diff.is_new(line) or
  296. diff.is_common(line)):
  297. diff._hunks[-1].append(diff.parse_hunk_line(line))
  298. elif diff.is_eof(line):
  299. # ignore
  300. pass
  301. elif diff.is_only_in_dir(line) or \
  302. diff.is_binary_differ(line):
  303. # 'Only in foo:' and 'Binary files ... differ' are considered
  304. # as separate diffs, so yield current diff, then this line
  305. #
  306. if diff._old_path and diff._new_path and diff._hunks:
  307. # Current diff is comppletely constructed
  308. yield diff
  309. headers.append(line)
  310. yield UnifiedDiff(headers, '', '', [])
  311. headers = []
  312. diff = UnifiedDiff([], None, None, [])
  313. else:
  314. # All other non-recognized lines are considered as headers or
  315. # hunk headers respectively
  316. #
  317. headers.append(line)
  318. # Validate and yield the last patch set if it is not yielded yet
  319. if diff._old_path:
  320. assert diff._new_path is not None
  321. if diff._hunks:
  322. assert len(diff._hunks[-1]._hunk_meta) > 0
  323. assert len(diff._hunks[-1]._hunk_list) > 0
  324. yield diff
  325. if headers:
  326. # Tolerate dangling headers, just yield a UnifiedDiff object with
  327. # only header lines
  328. #
  329. yield UnifiedDiff(headers, '', '', [])
  330. class DiffMarker(object):
  331. def markup(self, diffs, side_by_side=False, width=0):
  332. """Returns a generator"""
  333. if side_by_side:
  334. for diff in diffs:
  335. for line in self._markup_side_by_side(diff, width):
  336. yield line
  337. else:
  338. for diff in diffs:
  339. for line in self._markup_traditional(diff):
  340. yield line
  341. def _markup_traditional(self, diff):
  342. """Returns a generator"""
  343. for line in diff._headers:
  344. yield self._markup_header(line)
  345. yield self._markup_old_path(diff._old_path)
  346. yield self._markup_new_path(diff._new_path)
  347. for hunk in diff._hunks:
  348. for hunk_header in hunk._hunk_headers:
  349. yield self._markup_hunk_header(hunk_header)
  350. yield self._markup_hunk_meta(hunk._hunk_meta)
  351. for old, new, changed in hunk.mdiff():
  352. if changed:
  353. if not old[0]:
  354. # The '+' char after \x00 is kept
  355. # DEBUG: yield 'NEW: %s %s\n' % (old, new)
  356. line = new[1].strip('\x00\x01')
  357. yield self._markup_new(line)
  358. elif not new[0]:
  359. # The '-' char after \x00 is kept
  360. # DEBUG: yield 'OLD: %s %s\n' % (old, new)
  361. line = old[1].strip('\x00\x01')
  362. yield self._markup_old(line)
  363. else:
  364. # DEBUG: yield 'CHG: %s %s\n' % (old, new)
  365. yield self._markup_old('-') + \
  366. self._markup_mix(old[1], 'red')
  367. yield self._markup_new('+') + \
  368. self._markup_mix(new[1], 'green')
  369. else:
  370. yield self._markup_common(' ' + old[1])
  371. def _markup_side_by_side(self, diff, width):
  372. """Returns a generator"""
  373. wrap_char = colorize('>', 'lightmagenta')
  374. def _normalize(line):
  375. return line.replace(
  376. '\t', ' ' * 8).replace('\n', '').replace('\r', '')
  377. def _fit_with_marker(text, markup_fn, width, pad=False):
  378. """Wrap or pad input pure text, then markup"""
  379. if len(text) > width:
  380. return markup_fn(text[:(width - 1)]) + wrap_char
  381. elif pad:
  382. pad_len = width - len(text)
  383. return '%s%*s' % (markup_fn(text), pad_len, '')
  384. else:
  385. return markup_fn(text)
  386. def _fit_with_marker_mix(text, base_color, width, pad=False):
  387. """Wrap or pad input text which contains mdiff tags, markup at the
  388. meantime, note only left side need to set `pad`
  389. """
  390. out = [COLORS[base_color]]
  391. count = 0
  392. tag_re = re.compile(r'\x00[+^-]|\x01')
  393. while text and count < width:
  394. if text.startswith('\x00-'): # del
  395. out.append(COLORS['reverse'] + COLORS[base_color])
  396. text = text[2:]
  397. elif text.startswith('\x00+'): # add
  398. out.append(COLORS['reverse'] + COLORS[base_color])
  399. text = text[2:]
  400. elif text.startswith('\x00^'): # change
  401. out.append(COLORS['underline'] + COLORS[base_color])
  402. text = text[2:]
  403. elif text.startswith('\x01'): # reset
  404. out.append(COLORS['reset'] + COLORS[base_color])
  405. text = text[1:]
  406. else:
  407. # FIXME: utf-8 wchar might break the rule here, e.g.
  408. # u'\u554a' takes double width of a single letter, also
  409. # this depends on your terminal font. I guess audience of
  410. # this tool never put that kind of symbol in their code :-)
  411. #
  412. out.append(text[0])
  413. count += 1
  414. text = text[1:]
  415. if count == width and tag_re.sub('', text):
  416. # Was stripped: output fulfil and still has normal char in text
  417. out[-1] = COLORS['reset'] + wrap_char
  418. elif count < width and pad:
  419. pad_len = width - count
  420. out.append('%s%*s' % (COLORS['reset'], pad_len, ''))
  421. else:
  422. out.append(COLORS['reset'])
  423. return ''.join(out)
  424. # Set up line width
  425. if width <= 0:
  426. width = 80
  427. # Set up number width, note last hunk might be empty
  428. try:
  429. (start, offset) = diff._hunks[-1]._old_addr
  430. max1 = start + offset - 1
  431. (start, offset) = diff._hunks[-1]._new_addr
  432. max2 = start + offset - 1
  433. except IndexError:
  434. max1 = max2 = 0
  435. num_width = max(len(str(max1)), len(str(max2)))
  436. # Setup lineno and line format
  437. left_num_fmt = colorize('%%(left_num)%ds' % num_width, 'yellow')
  438. right_num_fmt = colorize('%%(right_num)%ds' % num_width, 'yellow')
  439. line_fmt = left_num_fmt + ' %(left)s ' + COLORS['reset'] + \
  440. right_num_fmt + ' %(right)s\n'
  441. # yield header, old path and new path
  442. for line in diff._headers:
  443. yield self._markup_header(line)
  444. yield self._markup_old_path(diff._old_path)
  445. yield self._markup_new_path(diff._new_path)
  446. # yield hunks
  447. for hunk in diff._hunks:
  448. for hunk_header in hunk._hunk_headers:
  449. yield self._markup_hunk_header(hunk_header)
  450. yield self._markup_hunk_meta(hunk._hunk_meta)
  451. for old, new, changed in hunk.mdiff():
  452. if old[0]:
  453. left_num = str(hunk._old_addr[0] + int(old[0]) - 1)
  454. else:
  455. left_num = ' '
  456. if new[0]:
  457. right_num = str(hunk._new_addr[0] + int(new[0]) - 1)
  458. else:
  459. right_num = ' '
  460. left = _normalize(old[1])
  461. right = _normalize(new[1])
  462. if changed:
  463. if not old[0]:
  464. left = '%*s' % (width, ' ')
  465. right = right.lstrip('\x00+').rstrip('\x01')
  466. right = _fit_with_marker(
  467. right, self._markup_new, width)
  468. elif not new[0]:
  469. left = left.lstrip('\x00-').rstrip('\x01')
  470. left = _fit_with_marker(left, self._markup_old, width)
  471. right = ''
  472. else:
  473. left = _fit_with_marker_mix(left, 'red', width, 1)
  474. right = _fit_with_marker_mix(right, 'green', width)
  475. else:
  476. left = _fit_with_marker(
  477. left, self._markup_common, width, 1)
  478. right = _fit_with_marker(right, self._markup_common, width)
  479. yield line_fmt % {
  480. 'left_num': left_num,
  481. 'left': left,
  482. 'right_num': right_num,
  483. 'right': right
  484. }
  485. def _markup_header(self, line):
  486. return colorize(line, 'cyan')
  487. def _markup_old_path(self, line):
  488. return colorize(line, 'yellow')
  489. def _markup_new_path(self, line):
  490. return colorize(line, 'yellow')
  491. def _markup_hunk_header(self, line):
  492. return colorize(line, 'lightcyan')
  493. def _markup_hunk_meta(self, line):
  494. return colorize(line, 'lightblue')
  495. def _markup_common(self, line):
  496. return colorize(line, 'reset')
  497. def _markup_old(self, line):
  498. return colorize(line, 'lightred')
  499. def _markup_new(self, line):
  500. return colorize(line, 'lightgreen')
  501. def _markup_mix(self, line, base_color):
  502. del_code = COLORS['reverse'] + COLORS[base_color]
  503. add_code = COLORS['reverse'] + COLORS[base_color]
  504. chg_code = COLORS['underline'] + COLORS[base_color]
  505. rst_code = COLORS['reset'] + COLORS[base_color]
  506. line = line.replace('\x00-', del_code)
  507. line = line.replace('\x00+', add_code)
  508. line = line.replace('\x00^', chg_code)
  509. line = line.replace('\x01', rst_code)
  510. return colorize(line, base_color)
  511. def markup_to_pager(stream, opts):
  512. diffs = DiffParser(stream).get_diff_generator()
  513. marker = DiffMarker()
  514. color_diff = marker.markup(diffs, side_by_side=opts.side_by_side,
  515. width=opts.width)
  516. # Args stolen from git source: github.com/git/git/blob/master/pager.c
  517. pager = subprocess.Popen(
  518. ['less', '-FRSX'], stdin=subprocess.PIPE, stdout=sys.stdout)
  519. for line in color_diff:
  520. pager.stdin.write(line.encode('utf-8'))
  521. pager.stdin.close()
  522. pager.wait()
  523. def check_command_status(arguments):
  524. """Return True if command returns 0."""
  525. try:
  526. return subprocess.call(
  527. arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0
  528. except OSError:
  529. return False
  530. def revision_control_diff(args):
  531. """Return diff from revision control system."""
  532. for _, ops in VCS_INFO.items():
  533. if check_command_status(ops['probe']):
  534. return subprocess.Popen(
  535. ops['diff'] + args, stdout=subprocess.PIPE).stdout
  536. def revision_control_log(args):
  537. """Return log from revision control system."""
  538. for _, ops in VCS_INFO.items():
  539. if check_command_status(ops['probe']):
  540. return subprocess.Popen(
  541. ops['log'] + args, stdout=subprocess.PIPE).stdout
  542. def decode(line):
  543. """Decode UTF-8 if necessary."""
  544. try:
  545. return line.decode('utf-8')
  546. except (AttributeError, UnicodeDecodeError):
  547. return line
  548. def main():
  549. signal.signal(signal.SIGPIPE, signal.SIG_DFL)
  550. signal.signal(signal.SIGINT, signal.SIG_DFL)
  551. from optparse import (OptionParser, BadOptionError, AmbiguousOptionError,
  552. OptionGroup)
  553. class PassThroughOptionParser(OptionParser):
  554. """Stop parsing on first unknown option (e.g. --cached, -U10) and pass
  555. them down. Note the `opt_str` in exception object does not give us
  556. chance to take the full option back, e.g. for '-U10' it will only
  557. contain '-U' and the '10' part will be lost. Ref: http://goo.gl/IqY4A
  558. (on stackoverflow). My hack is to try parse and insert a '--' in place
  559. and parse again. Let me know if someone has better solution.
  560. """
  561. def _process_args(self, largs, rargs, values):
  562. left = largs[:]
  563. right = rargs[:]
  564. try:
  565. OptionParser._process_args(self, left, right, values)
  566. except (BadOptionError, AmbiguousOptionError):
  567. parsed_num = len(rargs) - len(right) - 1
  568. rargs.insert(parsed_num, '--')
  569. OptionParser._process_args(self, largs, rargs, values)
  570. supported_vcs = sorted(VCS_INFO.keys())
  571. usage = """%prog [options] [file|dir ...]"""
  572. parser = PassThroughOptionParser(
  573. usage=usage, description=META_INFO['description'],
  574. version='%%prog %s' % META_INFO['version'])
  575. parser.add_option(
  576. '-s', '--side-by-side', action='store_true',
  577. help='enable side-by-side mode')
  578. parser.add_option(
  579. '-w', '--width', type='int', default=80, metavar='N',
  580. help='set text width for side-by-side mode, default is 80')
  581. parser.add_option(
  582. '-l', '--log', action='store_true',
  583. help='show log with changes from revision control')
  584. parser.add_option(
  585. '-c', '--color', default='auto', metavar='M',
  586. help="""colorize mode 'auto' (default), 'always', or 'never'""")
  587. # Hack: use OptionGroup text for extra help message after option list
  588. option_group = OptionGroup(
  589. parser, "Note", ("Option parser will stop on first unknown option "
  590. "and pass them down to underneath revision control"))
  591. parser.add_option_group(option_group)
  592. opts, args = parser.parse_args()
  593. if opts.log:
  594. diff_hdl = revision_control_log(args)
  595. if not diff_hdl:
  596. sys.stderr.write(('*** Not in a supported workspace, supported '
  597. 'are: %s\n') % ', '.join(supported_vcs))
  598. return 1
  599. elif sys.stdin.isatty():
  600. diff_hdl = revision_control_diff(args)
  601. if not diff_hdl:
  602. sys.stderr.write(('*** Not in a supported workspace, supported '
  603. 'are: %s\n\n') % ', '.join(supported_vcs))
  604. parser.print_help()
  605. return 1
  606. else:
  607. diff_hdl = sys.stdin
  608. stream = PatchStream(diff_hdl)
  609. # Don't let empty diff pass thru
  610. if stream.is_empty():
  611. return 0
  612. if opts.color == 'always' or \
  613. (opts.color == 'auto' and sys.stdout.isatty()):
  614. markup_to_pager(stream, opts)
  615. else:
  616. # pipe out stream untouched to make sure it is still a patch
  617. if sys.hexversion < 0x03000000:
  618. reload(sys).setdefaultencoding('utf8')
  619. for line in stream:
  620. sys.stdout.write(decode(line))
  621. if diff_hdl is not sys.stdin:
  622. diff_hdl.close()
  623. return 0
  624. if __name__ == '__main__':
  625. sys.exit(main())
  626. # vim:set et sts=4 sw=4 tw=79: