| 1 | import hashlib |
|---|
| 2 | import os |
|---|
| 3 | import re |
|---|
| 4 | import stat |
|---|
| 5 | import sys |
|---|
| 6 | |
|---|
| 7 | MATCH_PYTHON_BLOCK = re.compile('<%.*?%>', re.DOTALL) |
|---|
| 8 | MATCH_FORMAT = re.compile('%\(([^)]+)\)s') |
|---|
| 9 | MATCH_DECLARE_NEW = re.compile('<%\s*declareTemplate\(newTemplateStyle\s*=\s*True\)\s*%>\n*') |
|---|
| 10 | |
|---|
| 11 | def sha1(data): |
|---|
| 12 | h = hashlib.sha1() |
|---|
| 13 | h.update(data) |
|---|
| 14 | return h.hexdigest() |
|---|
| 15 | |
|---|
| 16 | def 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 | |
|---|
| 52 | def 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 | |
|---|
| 64 | for basepath, children in walktree('cds-indico'): |
|---|
| 65 | for child in children: |
|---|
| 66 | if child.endswith('.tpl'): |
|---|
| 67 | fix_template(os.path.join(basepath, child)) |
|---|