lib2to3_ex.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. """
  2. Customized Mixin2to3 support:
  3. - adds support for converting doctests
  4. This module raises an ImportError on Python 2.
  5. """
  6. from distutils.util import Mixin2to3 as _Mixin2to3
  7. from distutils import log
  8. from lib2to3.refactor import RefactoringTool, get_fixers_from_package
  9. import setuptools
  10. class DistutilsRefactoringTool(RefactoringTool):
  11. def log_error(self, msg, *args, **kw):
  12. log.error(msg, *args)
  13. def log_message(self, msg, *args):
  14. log.info(msg, *args)
  15. def log_debug(self, msg, *args):
  16. log.debug(msg, *args)
  17. class Mixin2to3(_Mixin2to3):
  18. def run_2to3(self, files, doctests=False):
  19. # See of the distribution option has been set, otherwise check the
  20. # setuptools default.
  21. if self.distribution.use_2to3 is not True:
  22. return
  23. if not files:
  24. return
  25. log.info("Fixing " + " ".join(files))
  26. self.__build_fixer_names()
  27. self.__exclude_fixers()
  28. if doctests:
  29. if setuptools.run_2to3_on_doctests:
  30. r = DistutilsRefactoringTool(self.fixer_names)
  31. r.refactor(files, write=True, doctests_only=True)
  32. else:
  33. _Mixin2to3.run_2to3(self, files)
  34. def __build_fixer_names(self):
  35. if self.fixer_names:
  36. return
  37. self.fixer_names = []
  38. for p in setuptools.lib2to3_fixer_packages:
  39. self.fixer_names.extend(get_fixers_from_package(p))
  40. if self.distribution.use_2to3_fixers is not None:
  41. for p in self.distribution.use_2to3_fixers:
  42. self.fixer_names.extend(get_fixers_from_package(p))
  43. def __exclude_fixers(self):
  44. excluded_fixers = getattr(self, 'exclude_fixers', [])
  45. if self.distribution.use_2to3_exclude_fixers is not None:
  46. excluded_fixers.extend(self.distribution.use_2to3_exclude_fixers)
  47. for fixer_name in excluded_fixers:
  48. if fixer_name in self.fixer_names:
  49. self.fixer_names.remove(fixer_name)