fix_renames.py 2.2 KB

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