lib2to3_ex.py 2.3 KB

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