This is a snapshot of Indico's old Trac site. Any information contained herein is most probably outdated. Access our new GitHub site here.

Ticket #630: convert-templates.py

File convert-templates.py, 1.9 KB (added by jmonnich, 5 years ago)

Script to convert old-style templates to new-style templates

Line 
1import hashlib
2import os
3import re
4import stat
5import sys
6
7MATCH_PYTHON_BLOCK = re.compile('<%.*?%>', re.DOTALL)
8MATCH_FORMAT = re.compile('%\(([^)]+)\)s')
9MATCH_DECLARE_NEW = re.compile('<%\s*declareTemplate\(newTemplateStyle\s*=\s*True\)\s*%>\n*')
10
11def sha1(data):
12    h = hashlib.sha1()
13    h.update(data)
14    return h.hexdigest()
15
16def fix_template(path):
17    print "Fixing %s..." % path,
18    f = open(path, 'rb')
19    template = '\n'.join(line.rstrip() for line in f)
20    f.close()
21
22    stored_blocks = {}
23    def replace_blocks(m):
24        block = m.group(0)
25        block_hash = sha1(block)
26        stored_blocks[block_hash] = block
27        return '{{{%s}}}' % block_hash
28
29    num_converted = [0] # list so we can modify it from inside the callback
30    def convert_variables(m):
31        name = m.group(1)
32        num_converted[0] += 1
33        return '<%%= %s %%>' % name
34
35    fixed = MATCH_DECLARE_NEW.sub('', template)
36    fixed = MATCH_PYTHON_BLOCK.sub(replace_blocks, fixed)
37    fixed = MATCH_FORMAT.sub(convert_variables, fixed)
38    if num_converted[0]:
39        fixed = fixed.replace('%%', '%')
40    for key, block in stored_blocks.iteritems():
41        fixed = fixed.replace('{{{%s}}}' % key, block)
42
43    if fixed == template:
44        print ' nothing to do'
45    else:
46        print ' done [%d]' % num_converted[0]
47        f = open(path, 'wb')
48        f.write(fixed)
49        f.close()
50
51
52def walktree(top='.'):
53    names = os.listdir(top)
54    yield top, names
55    for name in names:
56        try:
57            st = os.lstat(os.path.join(top, name))
58        except os.error:
59            continue
60        if stat.S_ISDIR(st.st_mode):
61            for newtop, children in walktree(os.path.join(top, name)):
62                yield newtop, children
63
64for basepath, children in walktree('cds-indico'):
65    for child in children:
66        if child.endswith('.tpl'):
67            fix_template(os.path.join(basepath, child))