Skip to content
Myr

flaskext_migrate.py

This file

Path

scripts/flaskext_migrate.py

162 lines · 4.9 KiB · Python

Last changed by

Merge branch 'master' of github.com:mitsuhiko/flaskMarkus Unterwaditzerbefore adoptione527c17

History of this file

Take it

1# Script which modifies source code away from the deprecated "flask.ext"2# format.3#4# Run in the terminal by typing: `python flaskext_migrate.py <source_file.py>`5#6# Author: Keyan Pishdadian 201578from redbaron import RedBaron9import sys101112def read_source(input_file):13    """Parses the input_file into a RedBaron FST."""14    with open(input_file, "r") as source_code:15        red = RedBaron(source_code.read())16    return red171819def write_source(red, input_file):20    """Overwrites the input_file once the FST has been modified."""21    with open(input_file, "w") as source_code:22        source_code.write(red.dumps())232425def fix_imports(red):26    """Wrapper which fixes "from" style imports and then "import" style."""27    red = fix_standard_imports(red)28    red = fix_from_imports(red)29    return red303132def fix_from_imports(red):33    """34    Converts "from" style imports to not use "flask.ext".3536    Handles:37    Case 1: from flask.ext.foo import bam --> from flask_foo import bam38    Case 2: from flask.ext import foo --> import flask_foo as foo39    """40    from_imports = red.find_all("FromImport")41    for x, node in enumerate(from_imports):42        values = node.value43        if len(values) < 2:44            continue45        if (values[0].value == 'flask') and (values[1].value == 'ext'):46            # Case 147            if len(node.value) == 3:48                package = values[2].value49                modules = node.modules()50                module_string = _get_modules(modules)51                if len(modules) > 1:52                    node.replace("from flask_%s import %s"53                                 % (package, module_string))54                else:55                    name = node.names()[0]56                    node.replace("from flask_%s import %s as %s"57                                 % (package, module_string, name))58            # Case 259            else:60                module = node.modules()[0]61                node.replace("import flask_%s as %s"62                             % (module, module))63    return red646566def fix_standard_imports(red):67    """68    Handles import modification in the form:69    import flask.ext.foo" --> import flask_foo70    """71    imports = red.find_all("ImportNode")72    for x, node in enumerate(imports):73        try:74            if (node.value[0].value[0].value == 'flask' and75               node.value[0].value[1].value == 'ext'):76                package = node.value[0].value[2].value77                name = node.names()[0].split('.')[-1]78                if name == package:79                    node.replace("import flask_%s" % (package))80                else:81                    node.replace("import flask_%s as %s" % (package, name))82        except IndexError:83            pass8485    return red868788def _get_modules(module):89    """90    Takes a list of modules and converts into a string.9192    The module list can include parens, this function checks each element in93    the list, if there is a paren then it does not add a comma before the next94    element. Otherwise a comma and space is added. This is to preserve module95    imports which are multi-line and/or occur within parens. While also not96    affecting imports which are not enclosed.97    """98    modules_string = [cur + ', ' if cur.isalnum() and next.isalnum()99                      else cur100                      for (cur, next) in zip(module, module[1:]+[''])]101102    return ''.join(modules_string)103104105def fix_function_calls(red):106    """107    Modifies function calls in the source to reflect import changes.108109    Searches the AST for AtomtrailerNodes and replaces them.110    """111    atoms = red.find_all("Atomtrailers")112    for x, node in enumerate(atoms):113        try:114            if (node.value[0].value == 'flask' and115               node.value[1].value == 'ext'):116                params = _form_function_call(node)117                node.replace("flask_%s%s" % (node.value[2], params))118        except IndexError:119            pass120121    return red122123124def _form_function_call(node):125    """126    Reconstructs function call strings when making attribute access calls.127    """128    node_vals = node.value129    output = "."130    for x, param in enumerate(node_vals[3::]):131        if param.dumps()[0] == "(":132            output = output[0:-1] + param.dumps()133            return output134        else:135            output += param.dumps() + "."136137138def check_user_input():139    """Exits and gives error message if no argument is passed in the shell."""140    if len(sys.argv) < 2:141        sys.exit("No filename was included, please try again.")142143144def fix_tester(ast):145    """Wrapper which allows for testing when not running from shell."""146    ast = fix_imports(ast)147    ast = fix_function_calls(ast)148    return ast.dumps()149150151def fix():152    """Wrapper for user argument checking and import fixing."""153    check_user_input()154    input_file = sys.argv[1]155    ast = read_source(input_file)156    ast = fix_imports(ast)157    ast = fix_function_calls(ast)158    write_source(ast, input_file)159160161if __name__ == "__main__":162    fix()