• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""Fix incompatible renames
2
3Fixes:
4  * sys.maxint -> sys.maxsize
5"""
6# Author: Christian Heimes
7# based on Collin Winter's fix_import
8
9# Local imports
10from .. import fixer_base
11from ..fixer_util import Name, attr_chain
12
13MAPPING = {"sys":  {"maxint" : "maxsize"},
14          }
15LOOKUP = {}
16
17def alternates(members):
18    return "(" + "|".join(map(repr, members)) + ")"
19
20
21def build_pattern():
22    #bare = set()
23    for module, replace in list(MAPPING.items()):
24        for old_attr, new_attr in list(replace.items()):
25            LOOKUP[(module, old_attr)] = new_attr
26            #bare.add(module)
27            #bare.add(old_attr)
28            #yield """
29            #      import_name< 'import' (module=%r
30            #          | dotted_as_names< any* module=%r any* >) >
31            #      """ % (module, module)
32            yield """
33                  import_from< 'from' module_name=%r 'import'
34                      ( attr_name=%r | import_as_name< attr_name=%r 'as' any >) >
35                  """ % (module, old_attr, old_attr)
36            yield """
37                  power< module_name=%r trailer< '.' attr_name=%r > any* >
38                  """ % (module, old_attr)
39    #yield """bare_name=%s""" % alternates(bare)
40
41
42class FixRenames(fixer_base.BaseFix):
43    BM_compatible = True
44    PATTERN = "|".join(build_pattern())
45
46    order = "pre" # Pre-order tree traversal
47
48    # Don't match the node if it's within another match
49    def match(self, node):
50        match = super(FixRenames, self).match
51        results = match(node)
52        if results:
53            if any(match(obj) for obj in attr_chain(node, "parent")):
54                return False
55            return results
56        return False
57
58    #def start_tree(self, tree, filename):
59    #    super(FixRenames, self).start_tree(tree, filename)
60    #    self.replace = {}
61
62    def transform(self, node, results):
63        mod_name = results.get("module_name")
64        attr_name = results.get("attr_name")
65        #bare_name = results.get("bare_name")
66        #import_mod = results.get("module")
67
68        if mod_name and attr_name:
69            new_attr = LOOKUP[(mod_name.value, attr_name.value)]
70            attr_name.replace(Name(new_attr, prefix=attr_name.prefix))
71