~ubuntu-branches/ubuntu/trusty/python-amqp/trusty-updates

« back to all changes in this revision

Viewing changes to docs/_ext/literals_to_xrefs.py

  • Committer: Package Import Robot
  • Author(s): Michael Fladischer
  • Date: 2013-06-27 15:12:51 UTC
  • Revision ID: package-import@ubuntu.com-20130627151251-e6zyq2p4lakfws9g
Tags: upstream-1.0.12
ImportĀ upstreamĀ versionĀ 1.0.12

Show diffs side-by-side

added added

removed removed

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