build_env.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. """Build Environment used for isolation during sdist building
  2. """
  3. import os
  4. from distutils.sysconfig import get_python_lib
  5. from sysconfig import get_paths
  6. from pip._internal.utils.temp_dir import TempDirectory
  7. class BuildEnvironment(object):
  8. """Creates and manages an isolated environment to install build deps
  9. """
  10. def __init__(self, no_clean):
  11. self._temp_dir = TempDirectory(kind="build-env")
  12. self._no_clean = no_clean
  13. @property
  14. def path(self):
  15. return self._temp_dir.path
  16. def __enter__(self):
  17. self._temp_dir.create()
  18. self.save_path = os.environ.get('PATH', None)
  19. self.save_pythonpath = os.environ.get('PYTHONPATH', None)
  20. self.save_nousersite = os.environ.get('PYTHONNOUSERSITE', None)
  21. install_scheme = 'nt' if (os.name == 'nt') else 'posix_prefix'
  22. install_dirs = get_paths(install_scheme, vars={
  23. 'base': self.path,
  24. 'platbase': self.path,
  25. })
  26. scripts = install_dirs['scripts']
  27. if self.save_path:
  28. os.environ['PATH'] = scripts + os.pathsep + self.save_path
  29. else:
  30. os.environ['PATH'] = scripts + os.pathsep + os.defpath
  31. # Note: prefer distutils' sysconfig to get the
  32. # library paths so PyPy is correctly supported.
  33. purelib = get_python_lib(plat_specific=0, prefix=self.path)
  34. platlib = get_python_lib(plat_specific=1, prefix=self.path)
  35. if purelib == platlib:
  36. lib_dirs = purelib
  37. else:
  38. lib_dirs = purelib + os.pathsep + platlib
  39. if self.save_pythonpath:
  40. os.environ['PYTHONPATH'] = lib_dirs + os.pathsep + \
  41. self.save_pythonpath
  42. else:
  43. os.environ['PYTHONPATH'] = lib_dirs
  44. os.environ['PYTHONNOUSERSITE'] = '1'
  45. return self.path
  46. def __exit__(self, exc_type, exc_val, exc_tb):
  47. if not self._no_clean:
  48. self._temp_dir.cleanup()
  49. def restore_var(varname, old_value):
  50. if old_value is None:
  51. os.environ.pop(varname, None)
  52. else:
  53. os.environ[varname] = old_value
  54. restore_var('PATH', self.save_path)
  55. restore_var('PYTHONPATH', self.save_pythonpath)
  56. restore_var('PYTHONNOUSERSITE', self.save_nousersite)
  57. def cleanup(self):
  58. self._temp_dir.cleanup()
  59. class NoOpBuildEnvironment(BuildEnvironment):
  60. """A no-op drop-in replacement for BuildEnvironment
  61. """
  62. def __init__(self, no_clean):
  63. pass
  64. def __enter__(self):
  65. pass
  66. def __exit__(self, exc_type, exc_val, exc_tb):
  67. pass
  68. def cleanup(self):
  69. pass