Skip to content
Myr

remove old upgrade script

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent bce8ec7 · Browse files · 1 file+0 added−298 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+0 added−298 removed

  • other:+0 added−298 removed

1 file+0 added−298 removed

deleted:scripts/flask-07-upgrade.py-298 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3"""4 flask-07-upgrade5 ~~~~~~~~~~~~~~~~67 This command line script scans a whole application tree and attempts to8 output a unified diff with all the changes that are necessary to easily9 upgrade the application to 0.7 and to not yield deprecation warnings.1011 This will also attempt to find `after_request` functions that don't modify12 the response and appear to be better suited for `teardown_request`.1314 This application is indeed an incredible hack, but because what it15 attempts to accomplish is impossible to do statically it tries to support16 the most common patterns at least. The diff it generates should be17 hand reviewed and not applied blindly without making backups.1819 :copyright: (c) Copyright 2015 by Armin Ronacher.20 :license: see LICENSE for more details.21"""22from __future__ import print_function23import re24import os25import inspect26import difflib27import posixpath28from optparse import OptionParser2930try:31 import ast32except ImportError:33 ast = None343536TEMPLATE_LOOKAHEAD = 40963738_app_re_part = r'((?:[a-zA-Z_][a-zA-Z0-9_]*app)|app|application)'39_string_re_part = r"('([^'\\]*(?:\\.[^'\\]*)*)'" \40 r'|"([^"\\]*(?:\\.[^"\\]*)*)")'4142_from_import_re = re.compile(r'^\s*from flask import\s+')43_url_for_re = re.compile(r'\b(url_for\()(%s)' % _string_re_part)44_render_template_re = re.compile(r'\b(render_template\()(%s)' % _string_re_part)45_after_request_re = re.compile(r'((?:@\S+\.(?:app_)?))(after_request)(\b\s*$)(?m)')46_module_constructor_re = re.compile(r'([a-zA-Z0-9_][a-zA-Z0-9_]*)\s*=\s*Module'47 r'\(__name__\s*(?:,\s*(?:name\s*=\s*)?(%s))?' %48 _string_re_part)49_error_handler_re = re.compile(r'%s\.error_handlers\[\s*(\d+)\s*\]' % _app_re_part)50_mod_route_re = re.compile(r'@([a-zA-Z0-9_][a-zA-Z0-9_]*)\.route')51_blueprint_related = [52 (re.compile(r'request\.module'), 'request.blueprint'),53 (re.compile(r'register_module'), 'register_blueprint'),54 (re.compile(r'%s\.modules' % _app_re_part), '\\1.blueprints')55]565758def make_diff(filename, old, new):59 for line in difflib.unified_diff(old.splitlines(), new.splitlines(),60 posixpath.normpath(posixpath.join('a', filename)),61 posixpath.normpath(posixpath.join('b', filename)),62 lineterm=''):63 print(line)646566def looks_like_teardown_function(node):67 returns = [x for x in ast.walk(node) if isinstance(x, ast.Return)]68 if len(returns) != 1:69 return70 return_def = returns[0]71 resp_name = node.args.args[0]72 if not isinstance(return_def.value, ast.Name) or \73 return_def.value.id != resp_name.id:74 return7576 for body_node in node.body:77 for child in ast.walk(body_node):78 if isinstance(child, ast.Name) and \79 child.id == resp_name.id:80 if child is not return_def.value:81 return8283 return resp_name.id848586def fix_url_for(contents, module_declarations=None):87 if module_declarations is None:88 skip_module_test = True89 else:90 skip_module_test = False91 mapping = dict(module_declarations)92 annotated_lines = []9394 def make_line_annotations():95 if not annotated_lines:96 last_index = 097 for line in contents.splitlines(True):98 last_index += len(line)99 annotated_lines.append((last_index, line))100101 def backtrack_module_name(call_start):102 make_line_annotations()103 for idx, (line_end, line) in enumerate(annotated_lines):104 if line_end > call_start:105 for _, line in reversed(annotated_lines[:idx]):106 match = _mod_route_re.search(line)107 if match is not None:108 shortname = match.group(1)109 return mapping.get(shortname)110111 def handle_match(match):112 if not skip_module_test:113 modname = backtrack_module_name(match.start())114 if modname is None:115 return match.group(0)116 prefix = match.group(1)117 endpoint = ast.literal_eval(match.group(2))118 if endpoint.startswith('.'):119 endpoint = endpoint[1:]120 elif '.' not in endpoint:121 endpoint = '.' + endpoint122 else:123 return match.group(0)124 return prefix + repr(endpoint)125 return _url_for_re.sub(handle_match, contents)126127128def fix_teardown_funcs(contents):129130 def is_return_line(line):131 args = line.strip().split()132 return args and args[0] == 'return'133134 def fix_single(match, lines, lineno):135 if not lines[lineno + 1].startswith('def'):136 return137 block_lines = inspect.getblock(lines[lineno + 1:])138 func_code = ''.join(block_lines)139 if func_code[0].isspace():140 node = ast.parse('if 1:\n' + func_code).body[0].body141 else:142 node = ast.parse(func_code).body[0]143 response_param_name = looks_like_teardown_function(node)144 if response_param_name is None:145 return146 before = lines[:lineno]147 decorator = [match.group(1) +148 match.group(2).replace('after_', 'teardown_') +149 match.group(3)]150 body = [line.replace(response_param_name, 'exception')151 for line in block_lines if152 not is_return_line(line)]153 after = lines[lineno + len(block_lines) + 1:]154 return before + decorator + body + after155156 content_lines = contents.splitlines(True)157 while 1:158 found_one = False159 for idx, line in enumerate(content_lines):160 match = _after_request_re.match(line)161 if match is None:162 continue163 new_content_lines = fix_single(match, content_lines, idx)164 if new_content_lines is not None:165 content_lines = new_content_lines166 break167 else:168 break169170 return ''.join(content_lines)171172173def get_module_autoname(filename):174 directory, filename = os.path.split(filename)175 if filename != '__init__.py':176 return os.path.splitext(filename)[0]177 return os.path.basename(directory)178179180def rewrite_from_imports(prefix, fromlist, lineiter):181 import_block = [prefix, fromlist]182 if fromlist[0] == '(' and fromlist[-1] != ')':183 for line in lineiter:184 import_block.append(line)185 if line.rstrip().endswith(')'):186 break187 elif fromlist[-1] == '\\':188 for line in lineiter:189 import_block.append(line)190 if line.rstrip().endswith('\\'):191 break192193 return ''.join(import_block).replace('Module', 'Blueprint')194195196def rewrite_blueprint_imports(contents):197 new_file = []198 lineiter = iter(contents.splitlines(True))199 for line in lineiter:200 match = _from_import_re.search(line)201 if match is not None:202 new_file.extend(rewrite_from_imports(match.group(),203 line[match.end():],204 lineiter))205 else:206 new_file.append(line)207 return ''.join(new_file)208209210def rewrite_for_blueprints(contents, filename):211 modules_declared = []212 def handle_match(match):213 target = match.group(1)214 name_param = match.group(2)215 if name_param is None:216 modname = get_module_autoname(filename)217 else:218 modname = ast.literal_eval(name_param)219 modules_declared.append((target, modname))220 return '%s = %s' % (target, 'Blueprint(%r, __name__' % modname)221 new_contents = _module_constructor_re.sub(handle_match, contents)222223 if modules_declared:224 new_contents = rewrite_blueprint_imports(new_contents)225226 for pattern, replacement in _blueprint_related:227 new_contents = pattern.sub(replacement, new_contents)228 return new_contents, dict(modules_declared)229230231def upgrade_python_file(filename, contents, teardown):232 new_contents = contents233 if teardown:234 new_contents = fix_teardown_funcs(new_contents)235 new_contents, modules = rewrite_for_blueprints(new_contents, filename)236 new_contents = fix_url_for(new_contents, modules)237 new_contents = _error_handler_re.sub('\\1.error_handler_spec[None][\\2]',238 new_contents)239 make_diff(filename, contents, new_contents)240241242def upgrade_template_file(filename, contents):243 new_contents = fix_url_for(contents, None)244 make_diff(filename, contents, new_contents)245246247def walk_path(path):248 this_file = os.path.realpath(__file__).rstrip('c')249 for dirpath, dirnames, filenames in os.walk(path):250 dirnames[:] = [x for x in dirnames if not x.startswith('.')]251 for filename in filenames:252 filename = os.path.join(dirpath, filename)253 if os.path.realpath(filename) == this_file:254 continue255 if filename.endswith('.py'):256 yield filename, 'python'257 # skip files that are diffs. These might be false positives258 # when run multiple times.259 elif not filename.endswith(('.diff', '.patch', '.udiff')):260 with open(filename) as f:261 contents = f.read(TEMPLATE_LOOKAHEAD)262 if '{% for' or '{% if' or '{{ url_for' in contents:263 yield filename, 'template'264265266def scan_path(path=None, teardown=True):267 for filename, type in walk_path(path):268 with open(filename) as f:269 contents = f.read()270 if type == 'python':271 upgrade_python_file(filename, contents, teardown)272 elif type == 'template':273 upgrade_template_file(filename, contents)274275276def main():277 """Entrypoint"""278 parser = OptionParser(usage='%prog [options] [paths]')279 parser.add_option('-T', '--no-teardown-detection', dest='no_teardown',280 action='store_true', help='Do not attempt to '281 'detect teardown function rewrites.')282 parser.add_option('-b', '--bundled-templates', dest='bundled_tmpl',283 action='store_true', help='Indicate to the system '284 'that templates are bundled with modules. Default '285 'is auto detect.')286 options, args = parser.parse_args()287 if not args:288 args = ['.']289290 if ast is None:291 parser.error('Python 2.6 or later is required to run the upgrade script.')292293 for path in args:294 scan_path(path, teardown=not options.no_teardown)295296297if __name__ == '__main__':298 main()