cdiff.py 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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.7',
  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 os
  27. import re
  28. import signal
  29. import subprocess
  30. import select
  31. import difflib
  32. try:
  33. unicode
  34. except NameError:
  35. unicode = str
  36. COLORS = {
  37. 'reset' : '\x1b[0m',
  38. 'underline' : '\x1b[4m',
  39. 'reverse' : '\x1b[7m',
  40. 'red' : '\x1b[31m',
  41. 'green' : '\x1b[32m',
  42. 'yellow' : '\x1b[33m',
  43. 'blue' : '\x1b[34m',
  44. 'magenta' : '\x1b[35m',
  45. 'cyan' : '\x1b[36m',
  46. 'lightred' : '\x1b[1;31m',
  47. 'lightgreen' : '\x1b[1;32m',
  48. 'lightyellow' : '\x1b[1;33m',
  49. 'lightblue' : '\x1b[1;34m',
  50. 'lightmagenta' : '\x1b[1;35m',
  51. 'lightcyan' : '\x1b[1;36m',
  52. }
  53. # Keys for revision control probe, diff and log with diff
  54. VCS_INFO = {
  55. 'Git': {
  56. 'probe' : ['git', 'rev-parse'],
  57. 'diff' : ['git', 'diff', '--no-ext-diff'],
  58. 'log' : ['git', 'log', '--patch'],
  59. },
  60. 'Mercurial': {
  61. 'probe' : ['hg', 'summary'],
  62. 'diff' : ['hg', 'diff'],
  63. 'log' : ['hg', 'log', '--patch'],
  64. },
  65. 'Svn': {
  66. 'probe' : ['svn', 'info'],
  67. 'diff' : ['svn', 'diff'],
  68. 'log' : ['svn', 'log', '--diff', '--use-merge-history'],
  69. },
  70. }
  71. def colorize(text, start_color, end_color='reset'):
  72. return COLORS[start_color] + text + COLORS[end_color]
  73. class Hunk(object):
  74. def __init__(self, hunk_headers, hunk_meta, old_addr, new_addr):
  75. self._hunk_headers = hunk_headers
  76. self._hunk_meta = hunk_meta
  77. self._old_addr = old_addr # tuple (start, offset)
  78. self._new_addr = new_addr # tuple (start, offset)
  79. self._hunk_list = [] # list of tuple (attr, line)
  80. def append(self, hunk_line):
  81. """hunk_line is a 2-element tuple: (attr, text), where attr is:
  82. '-': old, '+': new, ' ': common
  83. """
  84. self._hunk_list.append(hunk_line)
  85. def mdiff(self):
  86. r"""The difflib._mdiff() function returns an interator which returns a
  87. tuple: (from line tuple, to line tuple, boolean flag)
  88. from/to line tuple -- (line num, line text)
  89. line num -- integer or None (to indicate a context separation)
  90. line text -- original line text with following markers inserted:
  91. '\0+' -- marks start of added text
  92. '\0-' -- marks start of deleted text
  93. '\0^' -- marks start of changed text
  94. '\1' -- marks end of added/deleted/changed text
  95. boolean flag -- None indicates context separation, True indicates
  96. either "from" or "to" line contains a change, otherwise False.
  97. """
  98. return difflib._mdiff(self._get_old_text(), self._get_new_text())
  99. def _get_old_text(self):
  100. out = []
  101. for (attr, line) in self._hunk_list:
  102. if attr != '+':
  103. out.append(line)
  104. return out
  105. def _get_new_text(self):
  106. out = []
  107. for (attr, line) in self._hunk_list:
  108. if attr != '-':
  109. out.append(line)
  110. return out
  111. def is_completed(self):
  112. old_completed = self._old_addr[1] == len(self._get_old_text())
  113. new_completed = self._new_addr[1] == len(self._get_new_text())
  114. return old_completed and new_completed
  115. class UnifiedDiff(object):
  116. def __init__(self, headers, old_path, new_path, hunks):
  117. self._headers = headers
  118. self._old_path = old_path
  119. self._new_path = new_path
  120. self._hunks = hunks
  121. def is_old_path(self, line):
  122. return line.startswith('--- ')
  123. def is_new_path(self, line):
  124. return line.startswith('+++ ')
  125. def is_hunk_meta(self, line):
  126. """Minimal valid hunk meta is like '@@ -1 +1 @@', note extra chars
  127. might occur after the ending @@, e.g. in git log. '## ' usually
  128. indicates svn property changes in output from `svn log --diff`
  129. """
  130. return (line.startswith('@@ -') and line.find(' @@') >= 8) or \
  131. (line.startswith('## -') and line.find(' ##') >= 8)
  132. def parse_hunk_meta(self, hunk_meta):
  133. # @@ -3,7 +3,6 @@
  134. a = hunk_meta.split()[1].split(',') # -3 7
  135. if len(a) > 1:
  136. old_addr = (int(a[0][1:]), int(a[1]))
  137. else:
  138. # @@ -1 +1,2 @@
  139. old_addr = (int(a[0][1:]), 1)
  140. b = hunk_meta.split()[2].split(',') # +3 6
  141. if len(b) > 1:
  142. new_addr = (int(b[0][1:]), int(b[1]))
  143. else:
  144. # @@ -0,0 +1 @@
  145. new_addr = (int(b[0][1:]), 1)
  146. return (old_addr, new_addr)
  147. def parse_hunk_line(self, line):
  148. return (line[0], line[1:])
  149. def is_old(self, line):
  150. """Exclude old path and header line from svn log --diff output, allow
  151. '----' likely to see in diff from yaml file
  152. """
  153. return line.startswith('-') and not self.is_old_path(line) and \
  154. not re.match(r'^-{72}$', line.rstrip())
  155. def is_new(self, line):
  156. return line.startswith('+') and not self.is_new_path(line)
  157. def is_common(self, line):
  158. return line.startswith(' ')
  159. def is_eof(self, line):
  160. # \ No newline at end of file
  161. # \ No newline at end of property
  162. return line.startswith(r'\ No newline at end of')
  163. def is_only_in_dir(self, line):
  164. return line.startswith('Only in ')
  165. def is_binary_differ(self, line):
  166. return re.match('^Binary files .* differ$', line.rstrip())
  167. class PatchStream(object):
  168. def __init__(self, diff_hdl):
  169. self._diff_hdl = diff_hdl
  170. self._stream_header_size = 0
  171. self._stream_header = []
  172. # Test whether stream is empty by read 1 line
  173. line = self._diff_hdl.readline()
  174. if not line:
  175. self._is_empty = True
  176. else:
  177. self._stream_header.append(line)
  178. self._stream_header_size += 1
  179. self._is_empty = False
  180. def is_empty(self):
  181. return self._is_empty
  182. def read_stream_header(self, stream_header_size):
  183. """Returns a small chunk for patch type detect, suppose to call once"""
  184. for i in range(1, stream_header_size):
  185. line = self._diff_hdl.readline()
  186. if not line:
  187. break
  188. self._stream_header.append(line)
  189. self._stream_header_size += 1
  190. return self._stream_header
  191. def __iter__(self):
  192. for line in self._stream_header:
  193. yield line
  194. for line in self._diff_hdl:
  195. yield line
  196. class PatchStreamForwarder(object):
  197. """A blocking stream forwarder use `select` and line buffered mode. Feed
  198. input stream to a diff format translator and read output stream from it.
  199. Note input stream is non-seekable, and upstream has eaten some lines.
  200. """
  201. def __init__(self, istream, translator):
  202. assert isinstance(istream, PatchStream)
  203. assert isinstance(translator, subprocess.Popen)
  204. self._istream = iter(istream)
  205. self._in = translator.stdin
  206. self._out = translator.stdout
  207. def _can_read(self, timeout=0):
  208. return select.select([self._out.fileno()], [], [], timeout)[0]
  209. def _forward_line(self):
  210. try:
  211. line = next(self._istream)
  212. self._in.write(line)
  213. except StopIteration:
  214. self._in.close()
  215. def __iter__(self):
  216. while True:
  217. if self._can_read():
  218. line = self._out.readline()
  219. if line:
  220. yield line
  221. else:
  222. return
  223. elif not self._in.closed:
  224. self._forward_line()
  225. class DiffParser(object):
  226. def __init__(self, stream):
  227. header = [decode(line) for line in stream.read_stream_header(100)]
  228. size = len(header)
  229. if size >= 4 and (header[0].startswith('*** ') and
  230. header[1].startswith('--- ') and
  231. header[2].rstrip() == '***************' and
  232. header[3].startswith('*** ') and
  233. header[3].rstrip().endswith(' ****')):
  234. # For context diff, try use `filterdiff` to translate it to unified
  235. # format and provide a new stream
  236. #
  237. self._type = 'context'
  238. try:
  239. # Use line buffered mode so that to readline() in block mode
  240. self._translator = subprocess.Popen(
  241. ['filterdiff', '--format=unified'], stdin=subprocess.PIPE,
  242. stdout=subprocess.PIPE, bufsize=1)
  243. except OSError:
  244. raise SystemExit('*** Context diff support depends on '
  245. 'filterdiff')
  246. self._stream = PatchStreamForwarder(stream, self._translator)
  247. return
  248. for n in range(size):
  249. if header[n].startswith('--- ') and (n < size - 1) and \
  250. header[n+1].startswith('+++ '):
  251. self._type = 'unified'
  252. self._stream = stream
  253. break
  254. else:
  255. # `filterdiff` translates unknown diff to nothing, fall through to
  256. # unified diff give cdiff a chance to show everything as headers
  257. #
  258. sys.stderr.write("*** unknown format, fall through to 'unified'\n")
  259. self._type = 'unified'
  260. self._stream = stream
  261. def get_diff_generator(self):
  262. """parse all diff lines, construct a list of UnifiedDiff objects"""
  263. diff = UnifiedDiff([], None, None, [])
  264. headers = []
  265. for line in self._stream:
  266. line = decode(line)
  267. if diff.is_old_path(line):
  268. # This is a new diff when current hunk is not yet genreated or
  269. # is completed. We yield previous diff if exists and construct
  270. # a new one for this case. Otherwise it's acutally an 'old'
  271. # line starts with '--- '.
  272. #
  273. if (not diff._hunks or diff._hunks[-1].is_completed()):
  274. if diff._old_path and diff._new_path and diff._hunks:
  275. yield diff
  276. diff = UnifiedDiff(headers, line, None, [])
  277. headers = []
  278. else:
  279. diff._hunks[-1].append(diff.parse_hunk_line(line))
  280. elif diff.is_new_path(line) and diff._old_path:
  281. if not diff._new_path:
  282. diff._new_path = line
  283. else:
  284. diff._hunks[-1].append(diff.parse_hunk_line(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 number width, note last hunk might be empty
  425. try:
  426. (start, offset) = diff._hunks[-1]._old_addr
  427. max1 = start + offset - 1
  428. (start, offset) = diff._hunks[-1]._new_addr
  429. max2 = start + offset - 1
  430. except IndexError:
  431. max1 = max2 = 0
  432. num_width = max(len(str(max1)), len(str(max2)))
  433. # Set up line width
  434. if width <= 0:
  435. # Autodetection of text width according to terminal size
  436. try:
  437. # Each line is like "nnn TEXT nnn TEXT\n", so width is half of
  438. # [terminal size minus the line number columns and 3 separating
  439. # spaces
  440. #
  441. width = (terminal_size()[0] - num_width * 2 - 3) // 2
  442. except Exception:
  443. # If terminal detection failed, set back to default
  444. width = 80
  445. # Setup lineno and line format
  446. left_num_fmt = colorize('%%(left_num)%ds' % num_width, 'yellow')
  447. right_num_fmt = colorize('%%(right_num)%ds' % num_width, 'yellow')
  448. line_fmt = left_num_fmt + ' %(left)s ' + COLORS['reset'] + \
  449. right_num_fmt + ' %(right)s\n'
  450. # yield header, old path and new path
  451. for line in diff._headers:
  452. yield self._markup_header(line)
  453. yield self._markup_old_path(diff._old_path)
  454. yield self._markup_new_path(diff._new_path)
  455. # yield hunks
  456. for hunk in diff._hunks:
  457. for hunk_header in hunk._hunk_headers:
  458. yield self._markup_hunk_header(hunk_header)
  459. yield self._markup_hunk_meta(hunk._hunk_meta)
  460. for old, new, changed in hunk.mdiff():
  461. if old[0]:
  462. left_num = str(hunk._old_addr[0] + int(old[0]) - 1)
  463. else:
  464. left_num = ' '
  465. if new[0]:
  466. right_num = str(hunk._new_addr[0] + int(new[0]) - 1)
  467. else:
  468. right_num = ' '
  469. left = _normalize(old[1])
  470. right = _normalize(new[1])
  471. if changed:
  472. if not old[0]:
  473. left = '%*s' % (width, ' ')
  474. right = right.rstrip('\x01')
  475. if right.startswith('\x00+'):
  476. right = right[2:]
  477. right = _fit_with_marker(
  478. right, self._markup_new, width)
  479. elif not new[0]:
  480. left = left.rstrip('\x01')
  481. if left.startswith('\x00-'):
  482. left = left[2:]
  483. left = _fit_with_marker(left, self._markup_old, width)
  484. right = ''
  485. else:
  486. left = _fit_with_marker_mix(left, 'red', width, 1)
  487. right = _fit_with_marker_mix(right, 'green', width)
  488. else:
  489. left = _fit_with_marker(
  490. left, self._markup_common, width, 1)
  491. right = _fit_with_marker(right, self._markup_common, width)
  492. yield line_fmt % {
  493. 'left_num': left_num,
  494. 'left': left,
  495. 'right_num': right_num,
  496. 'right': right
  497. }
  498. def _markup_header(self, line):
  499. return colorize(line, 'cyan')
  500. def _markup_old_path(self, line):
  501. return colorize(line, 'yellow')
  502. def _markup_new_path(self, line):
  503. return colorize(line, 'yellow')
  504. def _markup_hunk_header(self, line):
  505. return colorize(line, 'lightcyan')
  506. def _markup_hunk_meta(self, line):
  507. return colorize(line, 'lightblue')
  508. def _markup_common(self, line):
  509. return colorize(line, 'reset')
  510. def _markup_old(self, line):
  511. return colorize(line, 'lightred')
  512. def _markup_new(self, line):
  513. return colorize(line, 'green')
  514. def _markup_mix(self, line, base_color):
  515. del_code = COLORS['reverse'] + COLORS[base_color]
  516. add_code = COLORS['reverse'] + COLORS[base_color]
  517. chg_code = COLORS['underline'] + COLORS[base_color]
  518. rst_code = COLORS['reset'] + COLORS[base_color]
  519. line = line.replace('\x00-', del_code)
  520. line = line.replace('\x00+', add_code)
  521. line = line.replace('\x00^', chg_code)
  522. line = line.replace('\x01', rst_code)
  523. return colorize(line, base_color)
  524. def markup_to_pager(stream, opts):
  525. """Pipe unified diff stream to pager (less).
  526. Note: have to create pager Popen object before the translator Popen object
  527. in PatchStreamForwarder, otherwise the `stdin=subprocess.PIPE` would cause
  528. trouble to the translator pipe (select() never see EOF after input stream
  529. ended), most likely python bug 12607 (http://bugs.python.org/issue12607)
  530. which was fixed in python 2.7.3.
  531. See issue #30 (https://github.com/ymattw/cdiff/issues/30) for more
  532. information.
  533. """
  534. pager_cmd = ['less']
  535. if not os.getenv('LESS'):
  536. # Args stolen from git source: github.com/git/git/blob/master/pager.c
  537. pager_cmd.extend(['-FRSX', '--shift 1'])
  538. pager = subprocess.Popen(
  539. pager_cmd, stdin=subprocess.PIPE, stdout=sys.stdout)
  540. diffs = DiffParser(stream).get_diff_generator()
  541. marker = DiffMarker()
  542. color_diff = marker.markup(diffs, side_by_side=opts.side_by_side,
  543. width=opts.width)
  544. for line in color_diff:
  545. pager.stdin.write(line.encode('utf-8'))
  546. pager.stdin.close()
  547. pager.wait()
  548. def check_command_status(arguments):
  549. """Return True if command returns 0."""
  550. try:
  551. return subprocess.call(
  552. arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0
  553. except OSError:
  554. return False
  555. def revision_control_diff(args):
  556. """Return diff from revision control system."""
  557. for _, ops in VCS_INFO.items():
  558. if check_command_status(ops['probe']):
  559. return subprocess.Popen(
  560. ops['diff'] + args, stdout=subprocess.PIPE).stdout
  561. def revision_control_log(args):
  562. """Return log from revision control system."""
  563. for _, ops in VCS_INFO.items():
  564. if check_command_status(ops['probe']):
  565. return subprocess.Popen(
  566. ops['log'] + args, stdout=subprocess.PIPE).stdout
  567. def decode(line):
  568. """Decode UTF-8 if necessary."""
  569. if isinstance(line, unicode):
  570. return line
  571. for encoding in ['utf-8', 'latin1']:
  572. try:
  573. return line.decode(encoding)
  574. except UnicodeDecodeError:
  575. pass
  576. return '*** cdiff: undecodable bytes ***\n'
  577. def terminal_size():
  578. """Returns terminal size. Taken from https://gist.github.com/marsam/7268750
  579. but removed win32 support which depends on 3rd party extension.
  580. """
  581. width, height = None, None
  582. try:
  583. import struct, fcntl, termios
  584. s = struct.pack('HHHH', 0, 0, 0, 0)
  585. x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
  586. height, width = struct.unpack('HHHH', x)[0:2]
  587. except (IOError, AttributeError):
  588. pass
  589. return width, height
  590. def main():
  591. signal.signal(signal.SIGPIPE, signal.SIG_DFL)
  592. signal.signal(signal.SIGINT, signal.SIG_DFL)
  593. from optparse import (OptionParser, BadOptionError, AmbiguousOptionError,
  594. OptionGroup)
  595. class PassThroughOptionParser(OptionParser):
  596. """Stop parsing on first unknown option (e.g. --cached, -U10) and pass
  597. them down. Note the `opt_str` in exception object does not give us
  598. chance to take the full option back, e.g. for '-U10' it will only
  599. contain '-U' and the '10' part will be lost. Ref: http://goo.gl/IqY4A
  600. (on stackoverflow). My hack is to try parse and insert a '--' in place
  601. and parse again. Let me know if someone has better solution.
  602. """
  603. def _process_args(self, largs, rargs, values):
  604. left = largs[:]
  605. right = rargs[:]
  606. try:
  607. OptionParser._process_args(self, left, right, values)
  608. except (BadOptionError, AmbiguousOptionError):
  609. parsed_num = len(rargs) - len(right) - 1
  610. rargs.insert(parsed_num, '--')
  611. OptionParser._process_args(self, largs, rargs, values)
  612. supported_vcs = sorted(VCS_INFO.keys())
  613. usage = """%prog [options] [file|dir ...]"""
  614. parser = PassThroughOptionParser(
  615. usage=usage, description=META_INFO['description'],
  616. version='%%prog %s' % META_INFO['version'])
  617. parser.add_option(
  618. '-s', '--side-by-side', action='store_true',
  619. help='enable side-by-side mode')
  620. parser.add_option(
  621. '-w', '--width', type='int', default=80, metavar='N',
  622. help='set text width for side-by-side mode, 0 for auto detection, '
  623. 'default is 80')
  624. parser.add_option(
  625. '-l', '--log', action='store_true',
  626. help='show log with changes from revision control')
  627. parser.add_option(
  628. '-c', '--color', default='auto', metavar='M',
  629. help="""colorize mode 'auto' (default), 'always', or 'never'""")
  630. # Hack: use OptionGroup text for extra help message after option list
  631. option_group = OptionGroup(
  632. parser, "Note", ("Option parser will stop on first unknown option "
  633. "and pass them down to underneath revision control"))
  634. parser.add_option_group(option_group)
  635. opts, args = parser.parse_args()
  636. if opts.log:
  637. diff_hdl = revision_control_log(args)
  638. if not diff_hdl:
  639. sys.stderr.write(('*** Not in a supported workspace, supported '
  640. 'are: %s\n') % ', '.join(supported_vcs))
  641. return 1
  642. elif sys.stdin.isatty():
  643. diff_hdl = revision_control_diff(args)
  644. if not diff_hdl:
  645. sys.stderr.write(('*** Not in a supported workspace, supported '
  646. 'are: %s\n\n') % ', '.join(supported_vcs))
  647. parser.print_help()
  648. return 1
  649. else:
  650. diff_hdl = (sys.stdin.buffer if hasattr(sys.stdin, 'buffer')
  651. else sys.stdin)
  652. stream = PatchStream(diff_hdl)
  653. # Don't let empty diff pass thru
  654. if stream.is_empty():
  655. return 0
  656. if opts.color == 'always' or \
  657. (opts.color == 'auto' and sys.stdout.isatty()):
  658. markup_to_pager(stream, opts)
  659. else:
  660. # pipe out stream untouched to make sure it is still a patch
  661. byte_output = (sys.stdout.buffer if hasattr(sys.stdout, 'buffer')
  662. else sys.stdout)
  663. for line in stream:
  664. byte_output.write(line)
  665. if diff_hdl is not sys.stdin:
  666. diff_hdl.close()
  667. return 0
  668. if __name__ == '__main__':
  669. sys.exit(main())
  670. # vim:set et sts=4 sw=4 tw=79: