literals_to_xrefs.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. refre = re.compile(r'``([^`\s]+?)``')
  9. ROLES = (
  10. 'attr',
  11. 'class',
  12. "djadmin",
  13. 'data',
  14. 'exc',
  15. 'file',
  16. 'func',
  17. 'lookup',
  18. 'meth',
  19. 'mod' ,
  20. "djadminopt",
  21. "ref",
  22. "setting",
  23. "term",
  24. "tfilter",
  25. "ttag",
  26. # special
  27. "skip"
  28. )
  29. ALWAYS_SKIP = [
  30. "NULL",
  31. "True",
  32. "False",
  33. ]
  34. def fixliterals(fname):
  35. with open(fname) as fp:
  36. data = fp.read()
  37. last = 0
  38. new = []
  39. storage = shelve.open("/tmp/literals_to_xref.shelve")
  40. lastvalues = storage.get("lastvalues", {})
  41. for m in refre.finditer(data):
  42. new.append(data[last:m.start()])
  43. last = m.end()
  44. line_start = data.rfind("\n", 0, m.start())
  45. line_end = data.find("\n", m.end())
  46. prev_start = data.rfind("\n", 0, line_start)
  47. next_end = data.find("\n", line_end + 1)
  48. # Skip always-skip stuff
  49. if m.group(1) in ALWAYS_SKIP:
  50. new.append(m.group(0))
  51. continue
  52. # skip when the next line is a title
  53. next_line = data[m.end():next_end].strip()
  54. if next_line[0] in "!-/:-@[-`{-~" and all(c == next_line[0] for c in next_line):
  55. new.append(m.group(0))
  56. continue
  57. sys.stdout.write("\n"+"-"*80+"\n")
  58. sys.stdout.write(data[prev_start+1:m.start()])
  59. sys.stdout.write(colorize(m.group(0), fg="red"))
  60. sys.stdout.write(data[m.end():next_end])
  61. sys.stdout.write("\n\n")
  62. replace_type = None
  63. while replace_type is None:
  64. replace_type = raw_input(
  65. colorize("Replace role: ", fg="yellow")
  66. ).strip().lower()
  67. if replace_type and replace_type not in ROLES:
  68. replace_type = None
  69. if replace_type == "":
  70. new.append(m.group(0))
  71. continue
  72. if replace_type == "skip":
  73. new.append(m.group(0))
  74. ALWAYS_SKIP.append(m.group(1))
  75. continue
  76. default = lastvalues.get(m.group(1), m.group(1))
  77. if default.endswith("()") and replace_type in ("class", "func", "meth"):
  78. default = default[:-2]
  79. replace_value = raw_input(
  80. colorize("Text <target> [", fg="yellow") + default + colorize("]: ", fg="yellow")
  81. ).strip()
  82. if not replace_value:
  83. replace_value = default
  84. new.append(":%s:`%s`" % (replace_type, replace_value))
  85. lastvalues[m.group(1)] = replace_value
  86. new.append(data[last:])
  87. with open(fname, "w") as fp:
  88. fp.write("".join(new))
  89. storage["lastvalues"] = lastvalues
  90. storage.close()
  91. #
  92. # The following is taken from django.utils.termcolors and is copied here to
  93. # avoid the dependancy.
  94. #
  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', 'blue', 'magenta', 'cyan', 'white')
  120. foreground = dict([(color_names[x], '3%s' % x) for x in range(8)])
  121. background = dict([(color_names[x], '4%s' % x) for x in range(8)])
  122. RESET = '0'
  123. opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'}
  124. text = str(text)
  125. code_list = []
  126. if text == '' and len(opts) == 1 and opts[0] == 'reset':
  127. return '\x1b[%sm' % RESET
  128. for k, v in kwargs.iteritems():
  129. if k == 'fg':
  130. code_list.append(foreground[v])
  131. elif k == 'bg':
  132. code_list.append(background[v])
  133. for o in opts:
  134. if o in opt_dict:
  135. code_list.append(opt_dict[o])
  136. if 'noreset' not in opts:
  137. text = text + '\x1b[%sm' % RESET
  138. return ('\x1b[%sm' % ';'.join(code_list)) + text
  139. if __name__ == '__main__':
  140. try:
  141. fixliterals(sys.argv[1])
  142. except (KeyboardInterrupt, SystemExit):
  143. print('')