Better control over template rendering calls
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 479e242 · Browse files · 1 file·+100 added−17 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+100 added−17 removed
- other:+100 added−17 removed
Provenance
- Commit
6d072f0- Tree
b26b7dd- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
479e242
1 file changed+100 added−17 removed
modified:scripts/flask-07-upgrade.py+100 added-17 removed
30 unmodified lines31 _from_import_re = re.compile(r'^\s*from flask import\s+')32 _string_re_part = r"('([^'\\]*(?:\\.[^'\\]*)*)'" \33 r'|"([^"\\]*(?:\\.[^"\\]*)*)")'34 _url_for_re = re.compile(r'\b(url_for\()(%s)' % _string_re_part)35+_render_template_re = re.compile(r'\b(render_template\()(%s)' % _string_re_part)36 _after_request_re = re.compile(r'((?:@\S+\.(?:app_)?))(after_request)(\b\s*$)(?m)')36-_module_constructor_re = re.compile(r'Module\(__name__\s*(?:,\s*(%s))?' %37+_module_constructor_re = re.compile(r'([a-zA-Z0-9_][a-zA-Z0-9_]*)\s*=\s*Module'38+ r'\(__name__\s*(?:,\s*(%s))?' %39 _string_re_part)40+_mod_route_re = re.compile(r'([a-zA-Z0-9_][a-zA-Z0-9_]*)\.route')41 _blueprint_related = [42 (re.compile(r'request\.module'), 'request.blueprint'),43 (re.compile(r'register_module'), 'register_blueprint')44 ]125 unmodified lines170 new_file.append(line)171 return ''.join(new_file)172 173 171-def rewrite_for_blueprints(contents, filename):172- found_constructor = []174+def rewrite_render_template_calls(contents, module_declarations):175+ mapping = dict(module_declarations)176+ annotated_lines = []177+178+ def make_line_annotations():179+ if not annotated_lines:180+ last_index = 0181+ for line in contents.splitlines(True):182+ last_index += len(line)183+ annotated_lines.append((last_index, line))184+185+ def backtrack_module_name(call_start):186+ make_line_annotations()187+ for idx, (line_end, line) in enumerate(annotated_lines):188+ if line_end > call_start:189+ for _, line in reversed(annotated_lines[:idx]):190+ match = _mod_route_re.search(line)191+ if match is not None:192+ shortname = match.group(1)193+ return mapping.get(shortname)194+195 def handle_match(match):174- found_constructor[:] = [True]175- name_param = match.group(1)196+ template_name = ast.literal_eval(match.group(2))197+ modname = backtrack_module_name(match.start())198+ if modname is not None and template_name.startswith(modname + '/'):199+ template_name = modname + ':' + template_name[len(modname) + 1:]200+ return match.group(1) + repr(template_name)201+ return _render_template_re.sub(handle_match, contents)202+203+204+def rewrite_for_blueprints(contents, filename, template_bundles=False):205+ modules_declared = []206+ def handle_match(match):207+ target = match.group(1)208+ name_param = match.group(2)209 if name_param is None:177- return 'Blueprint(%r, __name__' % get_module_autoname(filename)178- return 'Blueprint(%s, __name__' % name_param210+ modname = get_module_autoname(filename)211+ else:212+ modname = ast.literal_eval(name_param)213+ modules_declared.append((target, modname))214+ return '%s = %s' % (target, 'Blueprint(%r, __name__' % modname)215 new_contents = _module_constructor_re.sub(handle_match, contents)216 181- if found_constructor:217+ if modules_declared:218 new_contents = rewrite_blueprint_imports(new_contents)219+ if template_bundles:220+ new_contents = rewrite_render_template_calls(new_contents,221+ modules_declared)222 223 for pattern, replacement in _blueprint_related:224 new_contents = pattern.sub(replacement, new_contents)225 return new_contents226 227 189-def upgrade_python_file(filename, contents, teardown):228+def upgrade_python_file(filename, contents, teardown, template_bundles):229 new_contents = fix_url_for(contents)230 if teardown:231 new_contents = fix_teardown_funcs(new_contents)193- new_contents = rewrite_for_blueprints(new_contents, filename)232+ new_contents = rewrite_for_blueprints(new_contents, filename,233+ template_bundles)234 make_diff(filename, contents, new_contents)235 236 237 def upgrade_template_file(filename, contents):238 new_contents = fix_url_for(contents)239 make_diff(filename, contents, new_contents)240 241 202-def scan_path(path=None, teardown=True):242+def walk_path(path):243 for dirpath, dirnames, filenames in os.walk(path):244 for filename in filenames:245 filename = os.path.join(dirpath, filename)206- with open(filename) as f:207- contents = f.read()246 if filename.endswith('.py'):209- upgrade_python_file(filename, contents, teardown)210- elif '{% for' or '{% if' or '{{ url_for' in contents:211- upgrade_template_file(filename, contents)247+ yield filename, 'python'248+ else:249+ with open(filename) as f:250+ contents = f.read()251+ if '{% for' or '{% if' or '{{ url_for' in contents:252+ yield filename, 'template'253 254 255+def scan_path(path=None, teardown=True, template_bundles=True):256+ for filename, type in walk_path(path):257+ with open(filename) as f:258+ contents = f.read()259+ if type == 'python':260+ upgrade_python_file(filename, contents, teardown,261+ template_bundles)262+ elif type == 'template':263+ upgrade_template_file(filename, contents)264+265+266+def autodetect_template_bundles(paths):267+ folders_with_templates = set()268+ for path in paths:269+ for filename, type in walk_path(path):270+ if type == 'template':271+ fullpath = filename.replace(os.path.sep, '/')272+ index = fullpath.find('/templates/')273+ if index >= 0:274+ folder = fullpath[:index]275+ else:276+ folder = posixpath.dirname(fullpath)277+ folders_with_templates.add(folder)278+ return len(folders_with_templates) > 1279+280+281 def main():282 """Entrypoint"""283 if ast is None:284 error('Python 2.6 or later is required to run the upgrade script.\n'3 unmodified lines288 parser = OptionParser()289 parser.add_option('-T', '--no-teardown-detection', dest='no_teardown',290 action='store_true', help='Do not attempt to '291 'detect teardown function rewrites.')292+ parser.add_option('-b', '--bundled-templates', dest='bundled_tmpl',293+ action='store_true', help='Indicate to the system '294+ 'that templates are bundled with modules. Default '295+ 'is auto detect.')296+ parser.add_option('-B', '--no-bundled-templates', dest='no_bundled_tmpl',297+ action='store_true', help='Indicate to the system '298+ 'that templates are not bundled with modules. '299+ 'Default is auto detect')300 options, args = parser.parse_args()301 if not args:302 args = ['.']303 304+ if options.no_bundled_tmpl:305+ template_bundles = False306+ elif options.bundled_tmpl:307+ template_bundles = True308+ else:309+ template_bundles = autodetect_template_bundles(args)310+311 for path in args:230- scan_path(path, teardown=not options.no_teardown)312+ scan_path(path, teardown=not options.no_teardown,313+ template_bundles=template_bundles)314 315 316 if __name__ == '__main__':317 main()