cdiff.py 26KB

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