logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

__init__.py (9487B)


  1. import collections
  2. import os
  3. import os.path
  4. import subprocess
  5. import sys
  6. import sysconfig
  7. import tempfile
  8. from importlib import resources
  9. __all__ = ["version", "bootstrap"]
  10. _PACKAGE_NAMES = ('setuptools', 'pip')
  11. _SETUPTOOLS_VERSION = "57.4.0"
  12. _PIP_VERSION = "21.2.3"
  13. _PROJECTS = [
  14. ("setuptools", _SETUPTOOLS_VERSION, "py3"),
  15. ("pip", _PIP_VERSION, "py3"),
  16. ]
  17. # Packages bundled in ensurepip._bundled have wheel_name set.
  18. # Packages from WHEEL_PKG_DIR have wheel_path set.
  19. _Package = collections.namedtuple('Package',
  20. ('version', 'wheel_name', 'wheel_path'))
  21. # Directory of system wheel packages. Some Linux distribution packaging
  22. # policies recommend against bundling dependencies. For example, Fedora
  23. # installs wheel packages in the /usr/share/python-wheels/ directory and don't
  24. # install the ensurepip._bundled package.
  25. _WHEEL_PKG_DIR = sysconfig.get_config_var('WHEEL_PKG_DIR')
  26. def _find_packages(path):
  27. packages = {}
  28. try:
  29. filenames = os.listdir(path)
  30. except OSError:
  31. # Ignore: path doesn't exist or permission error
  32. filenames = ()
  33. # Make the code deterministic if a directory contains multiple wheel files
  34. # of the same package, but don't attempt to implement correct version
  35. # comparison since this case should not happen.
  36. filenames = sorted(filenames)
  37. for filename in filenames:
  38. # filename is like 'pip-20.2.3-py2.py3-none-any.whl'
  39. if not filename.endswith(".whl"):
  40. continue
  41. for name in _PACKAGE_NAMES:
  42. prefix = name + '-'
  43. if filename.startswith(prefix):
  44. break
  45. else:
  46. continue
  47. # Extract '20.2.2' from 'pip-20.2.2-py2.py3-none-any.whl'
  48. version = filename.removeprefix(prefix).partition('-')[0]
  49. wheel_path = os.path.join(path, filename)
  50. packages[name] = _Package(version, None, wheel_path)
  51. return packages
  52. def _get_packages():
  53. global _PACKAGES, _WHEEL_PKG_DIR
  54. if _PACKAGES is not None:
  55. return _PACKAGES
  56. packages = {}
  57. for name, version, py_tag in _PROJECTS:
  58. wheel_name = f"{name}-{version}-{py_tag}-none-any.whl"
  59. packages[name] = _Package(version, wheel_name, None)
  60. if _WHEEL_PKG_DIR:
  61. dir_packages = _find_packages(_WHEEL_PKG_DIR)
  62. # only used the wheel package directory if all packages are found there
  63. if all(name in dir_packages for name in _PACKAGE_NAMES):
  64. packages = dir_packages
  65. _PACKAGES = packages
  66. return packages
  67. _PACKAGES = None
  68. def _run_pip(args, additional_paths=None):
  69. # Run the bootstraping in a subprocess to avoid leaking any state that happens
  70. # after pip has executed. Particulary, this avoids the case when pip holds onto
  71. # the files in *additional_paths*, preventing us to remove them at the end of the
  72. # invocation.
  73. code = f"""
  74. import runpy
  75. import sys
  76. sys.path = {additional_paths or []} + sys.path
  77. sys.argv[1:] = {args}
  78. runpy.run_module("pip", run_name="__main__", alter_sys=True)
  79. """
  80. return subprocess.run([sys.executable, '-W', 'ignore::DeprecationWarning',
  81. "-c", code], check=True).returncode
  82. def version():
  83. """
  84. Returns a string specifying the bundled version of pip.
  85. """
  86. return _get_packages()['pip'].version
  87. def _disable_pip_configuration_settings():
  88. # We deliberately ignore all pip environment variables
  89. # when invoking pip
  90. # See http://bugs.python.org/issue19734 for details
  91. keys_to_remove = [k for k in os.environ if k.startswith("PIP_")]
  92. for k in keys_to_remove:
  93. del os.environ[k]
  94. # We also ignore the settings in the default pip configuration file
  95. # See http://bugs.python.org/issue20053 for details
  96. os.environ['PIP_CONFIG_FILE'] = os.devnull
  97. def bootstrap(*, root=None, upgrade=False, user=False,
  98. altinstall=False, default_pip=False,
  99. verbosity=0):
  100. """
  101. Bootstrap pip into the current Python installation (or the given root
  102. directory).
  103. Note that calling this function will alter both sys.path and os.environ.
  104. """
  105. # Discard the return value
  106. _bootstrap(root=root, upgrade=upgrade, user=user,
  107. altinstall=altinstall, default_pip=default_pip,
  108. verbosity=verbosity)
  109. def _bootstrap(*, root=None, upgrade=False, user=False,
  110. altinstall=False, default_pip=False,
  111. verbosity=0):
  112. """
  113. Bootstrap pip into the current Python installation (or the given root
  114. directory). Returns pip command status code.
  115. Note that calling this function will alter both sys.path and os.environ.
  116. """
  117. if altinstall and default_pip:
  118. raise ValueError("Cannot use altinstall and default_pip together")
  119. sys.audit("ensurepip.bootstrap", root)
  120. _disable_pip_configuration_settings()
  121. # By default, installing pip and setuptools installs all of the
  122. # following scripts (X.Y == running Python version):
  123. #
  124. # pip, pipX, pipX.Y, easy_install, easy_install-X.Y
  125. #
  126. # pip 1.5+ allows ensurepip to request that some of those be left out
  127. if altinstall:
  128. # omit pip, pipX and easy_install
  129. os.environ["ENSUREPIP_OPTIONS"] = "altinstall"
  130. elif not default_pip:
  131. # omit pip and easy_install
  132. os.environ["ENSUREPIP_OPTIONS"] = "install"
  133. with tempfile.TemporaryDirectory() as tmpdir:
  134. # Put our bundled wheels into a temporary directory and construct the
  135. # additional paths that need added to sys.path
  136. additional_paths = []
  137. for name, package in _get_packages().items():
  138. if package.wheel_name:
  139. # Use bundled wheel package
  140. from ensurepip import _bundled
  141. wheel_name = package.wheel_name
  142. whl = resources.read_binary(_bundled, wheel_name)
  143. else:
  144. # Use the wheel package directory
  145. with open(package.wheel_path, "rb") as fp:
  146. whl = fp.read()
  147. wheel_name = os.path.basename(package.wheel_path)
  148. filename = os.path.join(tmpdir, wheel_name)
  149. with open(filename, "wb") as fp:
  150. fp.write(whl)
  151. additional_paths.append(filename)
  152. # Construct the arguments to be passed to the pip command
  153. args = ["install", "--no-cache-dir", "--no-index", "--find-links", tmpdir]
  154. if root:
  155. args += ["--root", root]
  156. if upgrade:
  157. args += ["--upgrade"]
  158. if user:
  159. args += ["--user"]
  160. if verbosity:
  161. args += ["-" + "v" * verbosity]
  162. return _run_pip([*args, *_PACKAGE_NAMES], additional_paths)
  163. def _uninstall_helper(*, verbosity=0):
  164. """Helper to support a clean default uninstall process on Windows
  165. Note that calling this function may alter os.environ.
  166. """
  167. # Nothing to do if pip was never installed, or has been removed
  168. try:
  169. import pip
  170. except ImportError:
  171. return
  172. # If the installed pip version doesn't match the available one,
  173. # leave it alone
  174. available_version = version()
  175. if pip.__version__ != available_version:
  176. print(f"ensurepip will only uninstall a matching version "
  177. f"({pip.__version__!r} installed, "
  178. f"{available_version!r} available)",
  179. file=sys.stderr)
  180. return
  181. _disable_pip_configuration_settings()
  182. # Construct the arguments to be passed to the pip command
  183. args = ["uninstall", "-y", "--disable-pip-version-check"]
  184. if verbosity:
  185. args += ["-" + "v" * verbosity]
  186. return _run_pip([*args, *reversed(_PACKAGE_NAMES)])
  187. def _main(argv=None):
  188. import argparse
  189. parser = argparse.ArgumentParser(prog="python -m ensurepip")
  190. parser.add_argument(
  191. "--version",
  192. action="version",
  193. version="pip {}".format(version()),
  194. help="Show the version of pip that is bundled with this Python.",
  195. )
  196. parser.add_argument(
  197. "-v", "--verbose",
  198. action="count",
  199. default=0,
  200. dest="verbosity",
  201. help=("Give more output. Option is additive, and can be used up to 3 "
  202. "times."),
  203. )
  204. parser.add_argument(
  205. "-U", "--upgrade",
  206. action="store_true",
  207. default=False,
  208. help="Upgrade pip and dependencies, even if already installed.",
  209. )
  210. parser.add_argument(
  211. "--user",
  212. action="store_true",
  213. default=False,
  214. help="Install using the user scheme.",
  215. )
  216. parser.add_argument(
  217. "--root",
  218. default=None,
  219. help="Install everything relative to this alternate root directory.",
  220. )
  221. parser.add_argument(
  222. "--altinstall",
  223. action="store_true",
  224. default=False,
  225. help=("Make an alternate install, installing only the X.Y versioned "
  226. "scripts (Default: pipX, pipX.Y, easy_install-X.Y)."),
  227. )
  228. parser.add_argument(
  229. "--default-pip",
  230. action="store_true",
  231. default=False,
  232. help=("Make a default pip install, installing the unqualified pip "
  233. "and easy_install in addition to the versioned scripts."),
  234. )
  235. args = parser.parse_args(argv)
  236. return _bootstrap(
  237. root=args.root,
  238. upgrade=args.upgrade,
  239. user=args.user,
  240. verbosity=args.verbosity,
  241. altinstall=args.altinstall,
  242. default_pip=args.default_pip,
  243. )