blob: 7cf6a4b82673694d4ffa7b0aa61041578c3e0ad1 [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 Stuffte2df3ea2014-02-21 07:42:39 -050013_PIP_VERSION = "1.5.4"
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:
Nick Coghlana46cf122014-02-28 23:35:05 +1000131 msg = ("ensurepip will only uninstall a matching version "
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000132 "({!r} installed, {!r} bundled)")
Nick Coghlana46cf122014-02-28 23:35:05 +1000133 print(msg.format(pip.__version__, _PIP_VERSION), file=sys.stderr)
134 return
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000135
Nick Coghlanae2ee962013-12-23 23:07:07 +1000136 _require_ssl_for_pip()
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000137 _disable_pip_configuration_settings()
Nick Coghlaned9af522013-12-23 17:39:12 +1000138
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000139 # Construct the arguments to be passed to the pip command
140 args = ["uninstall", "-y"]
141 if verbosity:
142 args += ["-" + "v" * verbosity]
143
144 _run_pip(args + [p[0] for p in reversed(_PROJECTS)])
Nick Coghlanf71cae02013-12-23 18:20:34 +1000145
146
147def _main(argv=None):
Nick Coghlanc00fa632014-02-15 09:14:54 +1000148 if ssl is None:
149 print("Ignoring ensurepip failure: {}".format(_MISSING_SSL_MESSAGE),
150 file=sys.stderr)
151 return
152
Nick Coghlanf71cae02013-12-23 18:20:34 +1000153 import argparse
154 parser = argparse.ArgumentParser(prog="python -m ensurepip")
155 parser.add_argument(
156 "--version",
157 action="version",
158 version="pip {}".format(version()),
159 help="Show the version of pip that is bundled with this Python.",
160 )
161 parser.add_argument(
162 "-v", "--verbose",
163 action="count",
164 default=0,
165 dest="verbosity",
166 help=("Give more output. Option is additive, and can be used up to 3 "
167 "times."),
168 )
169 parser.add_argument(
170 "-U", "--upgrade",
171 action="store_true",
172 default=False,
173 help="Upgrade pip and dependencies, even if already installed.",
174 )
175 parser.add_argument(
176 "--user",
177 action="store_true",
178 default=False,
179 help="Install using the user scheme.",
180 )
181 parser.add_argument(
182 "--root",
183 default=None,
184 help="Install everything relative to this alternate root directory.",
185 )
186 parser.add_argument(
187 "--altinstall",
188 action="store_true",
189 default=False,
190 help=("Make an alternate install, installing only the X.Y versioned"
191 "scripts (Default: pipX, pipX.Y, easy_install-X.Y)"),
192 )
193 parser.add_argument(
194 "--default-pip",
195 action="store_true",
196 default=False,
197 help=("Make a default pip install, installing the unqualified pip "
198 "and easy_install in addition to the versioned scripts"),
199 )
200
201 args = parser.parse_args(argv)
202
203 bootstrap(
204 root=args.root,
205 upgrade=args.upgrade,
206 user=args.user,
207 verbosity=args.verbosity,
208 altinstall=args.altinstall,
209 default_pip=args.default_pip,
210 )