blob: e8d6abeb1fc367f58e0b424ac50a1e82829b6120 [file] [log] [blame]
Nick Coghland0cf0632013-11-11 22:11:55 +10001import os
2import os.path
3import pkgutil
4import sys
5import tempfile
6
Nick Coghland0cf0632013-11-11 22:11:55 +10007
8__all__ = ["version", "bootstrap"]
9
10
Donald Stufft0711dd92014-01-26 00:22:39 -050011_SETUPTOOLS_VERSION = "2.1"
Nick Coghland0cf0632013-11-11 22:11:55 +100012
Donald Stufft0711dd92014-01-26 00:22:39 -050013_PIP_VERSION = "1.5.2"
Nick Coghland0cf0632013-11-11 22:11:55 +100014
Nick Coghlanae2ee962013-12-23 23:07:07 +100015# pip currently requires ssl support, so we try to provide a nicer
16# error message when that is missing (http://bugs.python.org/issue19744)
17_MISSING_SSL_MESSAGE = ("pip {} requires SSL/TLS".format(_PIP_VERSION))
18try:
19 import ssl
20except ImportError:
21 ssl = None
22 def _require_ssl_for_pip():
23 raise RuntimeError(_MISSING_SSL_MESSAGE)
24else:
25 def _require_ssl_for_pip():
26 pass
27
Nick Coghland0cf0632013-11-11 22:11:55 +100028_PROJECTS = [
29 ("setuptools", _SETUPTOOLS_VERSION),
30 ("pip", _PIP_VERSION),
31]
32
33
Nick Coghlanfdf3a622013-11-30 17:15:09 +100034def _run_pip(args, additional_paths=None):
Nick Coghland0cf0632013-11-11 22:11:55 +100035 # Add our bundled software to the sys.path so we can import it
Nick Coghlanfdf3a622013-11-30 17:15:09 +100036 if additional_paths is not None:
37 sys.path = additional_paths + sys.path
Nick Coghland0cf0632013-11-11 22:11:55 +100038
39 # Install the bundled software
40 import pip
41 pip.main(args)
42
43
44def version():
45 """
46 Returns a string specifying the bundled version of pip.
47 """
48 return _PIP_VERSION
49
Nick Coghlan6edd82a2014-02-04 23:02:36 +100050def _disable_pip_configuration_settings():
Nick Coghlaned9af522013-12-23 17:39:12 +100051 # We deliberately ignore all pip environment variables
52 # when invoking pip
53 # See http://bugs.python.org/issue19734 for details
54 keys_to_remove = [k for k in os.environ if k.startswith("PIP_")]
55 for k in keys_to_remove:
56 del os.environ[k]
Nick Coghlan6edd82a2014-02-04 23:02:36 +100057 # We also ignore the settings in the default pip configuration file
58 # See http://bugs.python.org/issue20053 for details
59 os.environ['PIP_CONFIG_FILE'] = os.devnull
Nick Coghlaned9af522013-12-23 17:39:12 +100060
Nick Coghland0cf0632013-11-11 22:11:55 +100061
62def bootstrap(*, root=None, upgrade=False, user=False,
63 altinstall=False, default_pip=False,
64 verbosity=0):
65 """
66 Bootstrap pip into the current Python installation (or the given root
67 directory).
Nick Coghlan6256fcb2013-12-23 16:16:07 +100068
69 Note that calling this function will alter both sys.path and os.environ.
Nick Coghland0cf0632013-11-11 22:11:55 +100070 """
71 if altinstall and default_pip:
72 raise ValueError("Cannot use altinstall and default_pip together")
73
Nick Coghlanae2ee962013-12-23 23:07:07 +100074 _require_ssl_for_pip()
Nick Coghlan6edd82a2014-02-04 23:02:36 +100075 _disable_pip_configuration_settings()
Nick Coghlan6256fcb2013-12-23 16:16:07 +100076
Nick Coghland0cf0632013-11-11 22:11:55 +100077 # By default, installing pip and setuptools installs all of the
78 # following scripts (X.Y == running Python version):
79 #
80 # pip, pipX, pipX.Y, easy_install, easy_install-X.Y
81 #
82 # pip 1.5+ allows ensurepip to request that some of those be left out
83 if altinstall:
84 # omit pip, pipX and easy_install
85 os.environ["ENSUREPIP_OPTIONS"] = "altinstall"
86 elif not default_pip:
87 # omit pip and easy_install
88 os.environ["ENSUREPIP_OPTIONS"] = "install"
89
90 with tempfile.TemporaryDirectory() as tmpdir:
91 # Put our bundled wheels into a temporary directory and construct the
92 # additional paths that need added to sys.path
93 additional_paths = []
94 for project, version in _PROJECTS:
95 wheel_name = "{}-{}-py2.py3-none-any.whl".format(project, version)
96 whl = pkgutil.get_data(
97 "ensurepip",
98 "_bundled/{}".format(wheel_name),
99 )
100 with open(os.path.join(tmpdir, wheel_name), "wb") as fp:
101 fp.write(whl)
102
103 additional_paths.append(os.path.join(tmpdir, wheel_name))
104
105 # Construct the arguments to be passed to the pip command
Donald Stufftf7f58f82014-01-02 09:33:35 -0500106 args = ["install", "--no-index", "--find-links", tmpdir]
Nick Coghland0cf0632013-11-11 22:11:55 +1000107 if root:
108 args += ["--root", root]
109 if upgrade:
110 args += ["--upgrade"]
111 if user:
112 args += ["--user"]
113 if verbosity:
114 args += ["-" + "v" * verbosity]
115
116 _run_pip(args + [p[0] for p in _PROJECTS], additional_paths)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000117
Nick Coghlanf71cae02013-12-23 18:20:34 +1000118def _uninstall_helper(*, verbosity=0):
Nick Coghlaned9af522013-12-23 17:39:12 +1000119 """Helper to support a clean default uninstall process on Windows
120
121 Note that calling this function may alter os.environ.
122 """
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000123 # Nothing to do if pip was never installed, or has been removed
124 try:
125 import pip
126 except ImportError:
127 return
128
129 # If the pip version doesn't match the bundled one, leave it alone
130 if pip.__version__ != _PIP_VERSION:
131 msg = ("ensurepip will only uninstall a matching pip "
132 "({!r} installed, {!r} bundled)")
133 raise RuntimeError(msg.format(pip.__version__, _PIP_VERSION))
134
Nick Coghlanae2ee962013-12-23 23:07:07 +1000135 _require_ssl_for_pip()
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000136 _disable_pip_configuration_settings()
Nick Coghlaned9af522013-12-23 17:39:12 +1000137
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000138 # Construct the arguments to be passed to the pip command
139 args = ["uninstall", "-y"]
140 if verbosity:
141 args += ["-" + "v" * verbosity]
142
143 _run_pip(args + [p[0] for p in reversed(_PROJECTS)])
Nick Coghlanf71cae02013-12-23 18:20:34 +1000144
145
146def _main(argv=None):
147 import argparse
148 parser = argparse.ArgumentParser(prog="python -m ensurepip")
149 parser.add_argument(
150 "--version",
151 action="version",
152 version="pip {}".format(version()),
153 help="Show the version of pip that is bundled with this Python.",
154 )
155 parser.add_argument(
156 "-v", "--verbose",
157 action="count",
158 default=0,
159 dest="verbosity",
160 help=("Give more output. Option is additive, and can be used up to 3 "
161 "times."),
162 )
163 parser.add_argument(
164 "-U", "--upgrade",
165 action="store_true",
166 default=False,
167 help="Upgrade pip and dependencies, even if already installed.",
168 )
169 parser.add_argument(
170 "--user",
171 action="store_true",
172 default=False,
173 help="Install using the user scheme.",
174 )
175 parser.add_argument(
176 "--root",
177 default=None,
178 help="Install everything relative to this alternate root directory.",
179 )
180 parser.add_argument(
181 "--altinstall",
182 action="store_true",
183 default=False,
184 help=("Make an alternate install, installing only the X.Y versioned"
185 "scripts (Default: pipX, pipX.Y, easy_install-X.Y)"),
186 )
187 parser.add_argument(
188 "--default-pip",
189 action="store_true",
190 default=False,
191 help=("Make a default pip install, installing the unqualified pip "
192 "and easy_install in addition to the versioned scripts"),
193 )
194
195 args = parser.parse_args(argv)
196
197 bootstrap(
198 root=args.root,
199 upgrade=args.upgrade,
200 user=args.user,
201 verbosity=args.verbosity,
202 altinstall=args.altinstall,
203 default_pip=args.default_pip,
204 )