cdiff.py 27KB

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