literals_to_xrefs.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. """
  2. Runs through a reST file looking for old-style literals, and helps replace them
  3. with new-style references.
  4. """
  5. import re
  6. import sys
  7. import shelve
  8. try:
  9. input = input
  10. except NameError:
  11. input = raw_input # noqa
  12. refre = re.compile(r'``([^`\s]+?)``')
  13. ROLES = (
  14. 'attr',
  15. 'class',
  16. 'djadmin',
  17. 'data',
  18. 'exc',
  19. 'file',
  20. 'func',
  21. 'lookup',
  22. 'meth',
  23. 'mod',
  24. 'djadminopt',
  25. 'ref',
  26. 'setting',
  27. 'term',
  28. 'tfilter',
  29. 'ttag',
  30. # special
  31. 'skip',
  32. )
  33. ALWAYS_SKIP = [
  34. 'NULL',
  35. 'True',
  36. 'False',
  37. ]
  38. def fixliterals(fname):
  39. data = open(fname).read()
  40. last = 0
  41. new = []
  42. storage = shelve.open('/tmp/literals_to_xref.shelve')
  43. lastvalues = storage.get('lastvalues', {})
  44. for m in refre.finditer(data):
  45. new.append(data[last:m.start()])
  46. last = m.end()
  47. line_start = data.rfind('\n', 0, m.start())
  48. line_end = data.find('\n', m.end())
  49. prev_start = data.rfind('\n', 0, line_start)
  50. next_end = data.find('\n', line_end + 1)
  51. # Skip always-skip stuff
  52. if m.group(1) in ALWAYS_SKIP:
  53. new.append(m.group(0))
  54. continue
  55. # skip when the next line is a title
  56. next_line = data[m.end():next_end].strip()
  57. if next_line[0] in '!-/:-@[-`{-~' and \
  58. all(c == next_line[0] for c in next_line):
  59. new.append(m.group(0))
  60. continue
  61. sys.stdout.write('\n' + '-' * 80 + '\n')
  62. sys.stdout.write(data[prev_start + 1:m.start()])
  63. sys.stdout.write(colorize(m.group(0), fg='red'))
  64. sys.stdout.write(data[m.end():next_end])
  65. sys.stdout.write('\n\n')
  66. replace_type = None
  67. while replace_type is None:
  68. replace_type = input(
  69. colorize('Replace role: ', fg='yellow')).strip().lower()
  70. if replace_type and replace_type not in ROLES:
  71. replace_type = None
  72. if replace_type == '':
  73. new.append(m.group(0))
  74. continue
  75. if replace_type == 'skip':
  76. new.append(m.group(0))
  77. ALWAYS_SKIP.append(m.group(1))
  78. continue
  79. default = lastvalues.get(m.group(1), m.group(1))
  80. if default.endswith('()') and \
  81. replace_type in ('class', 'func', 'meth'):
  82. default = default[:-2]
  83. replace_value = input(
  84. colorize('Text <target> [', fg='yellow') +
  85. default + colorize(']: ', fg='yellow'),
  86. ).strip()
  87. if not replace_value:
  88. replace_value = default
  89. new.append(':%s:`%s`' % (replace_type, replace_value))
  90. lastvalues[m.group(1)] = replace_value
  91. new.append(data[last:])
  92. open(fname, 'w').write(''.join(new))
  93. storage['lastvalues'] = lastvalues
  94. storage.close()
  95. def colorize(text='', opts=(), **kwargs):
  96. """
  97. Returns your text, enclosed in ANSI graphics codes.
  98. Depends on the keyword arguments 'fg' and 'bg', and the contents of
  99. the opts tuple/list.
  100. Returns the RESET code if no parameters are given.
  101. Valid colors:
  102. 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
  103. Valid options:
  104. 'bold'
  105. 'underscore'
  106. 'blink'
  107. 'reverse'
  108. 'conceal'
  109. 'noreset' - string will not be auto-terminated with the RESET code
  110. Examples:
  111. colorize('hello', fg='red', bg='blue', opts=('blink',))
  112. colorize()
  113. colorize('goodbye', opts=('underscore',))
  114. print colorize('first line', fg='red', opts=('noreset',))
  115. print 'this should be red too'
  116. print colorize('and so should this')
  117. print 'this should not be red'
  118. """
  119. color_names = ('black', 'red', 'green', 'yellow',
  120. 'blue', 'magenta', 'cyan', 'white')
  121. foreground = {color_names[x]: '3%s' % x for x in range(8)}
  122. background = {color_names[x]: '4%s' % x for x in range(8)}
  123. RESET = '0'
  124. opt_dict = {'bold': '1',
  125. 'underscore': '4',
  126. 'blink': '5',
  127. 'reverse': '7',
  128. 'conceal': '8'}
  129. text = str(text)
  130. code_list = []
  131. if text == '' and len(opts) == 1 and opts[0] == 'reset':
  132. return '\x1b[%sm' % RESET
  133. for k, v in kwargs.items():
  134. if k == 'fg':
  135. code_list.append(foreground[v])
  136. elif k == 'bg':
  137. code_list.append(background[v])
  138. for o in opts:
  139. if o in opt_dict:
  140. code_list.append(opt_dict[o])
  141. if 'noreset' not in opts:
  142. text = text + '\x1b[%sm' % RESET
  143. return ('\x1b[%sm' % ';'.join(code_list)) + text
  144. if __name__ == '__main__':
  145. try:
  146. fixliterals(sys.argv[1])
  147. except (KeyboardInterrupt, SystemExit):
  148. print