blob: 26d411f6194c3b22fbac59057b016cadf6982f62 [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 Stufftd9ddd3f2013-12-31 06:52:47 -050011_SETUPTOOLS_VERSION = "2.0.2"
Nick Coghland0cf0632013-11-11 22:11:55 +100012
Donald Stufftf7f58f82014-01-02 09:33:35 -050013_PIP_VERSION = "1.5"
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 Coghlaned9af522013-12-23 17:39:12 +100050def _clear_pip_environment_variables():
51 # 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]
57
Nick Coghland0cf0632013-11-11 22:11:55 +100058
59def bootstrap(*, root=None, upgrade=False, user=False,
60 altinstall=False, default_pip=False,
61 verbosity=0):
62 """
63 Bootstrap pip into the current Python installation (or the given root
64 directory).
Nick Coghlan6256fcb2013-12-23 16:16:07 +100065
66 Note that calling this function will alter both sys.path and os.environ.
Nick Coghland0cf0632013-11-11 22:11:55 +100067 """
68 if altinstall and default_pip:
69 raise ValueError("Cannot use altinstall and default_pip together")
70
Nick Coghlanae2ee962013-12-23 23:07:07 +100071 _require_ssl_for_pip()
Nick Coghlaned9af522013-12-23 17:39:12 +100072 _clear_pip_environment_variables()
Nick Coghlan6256fcb2013-12-23 16:16:07 +100073
Nick Coghland0cf0632013-11-11 22:11:55 +100074 # By default, installing pip and setuptools installs all of the
75 # following scripts (X.Y == running Python version):
76 #
77 # pip, pipX, pipX.Y, easy_install, easy_install-X.Y
78 #
79 # pip 1.5+ allows ensurepip to request that some of those be left out
80 if altinstall:
81 # omit pip, pipX and easy_install
82 os.environ["ENSUREPIP_OPTIONS"] = "altinstall"
83 elif not default_pip:
84 # omit pip and easy_install
85 os.environ["ENSUREPIP_OPTIONS"] = "install"
86
87 with tempfile.TemporaryDirectory() as tmpdir:
88 # Put our bundled wheels into a temporary directory and construct the
89 # additional paths that need added to sys.path
90 additional_paths = []
91 for project, version in _PROJECTS:
92 wheel_name = "{}-{}-py2.py3-none-any.whl".format(project, version)
93 whl = pkgutil.get_data(
94 "ensurepip",
95 "_bundled/{}".format(wheel_name),
96 )
97 with open(os.path.join(tmpdir, wheel_name), "wb") as fp:
98 fp.write(whl)
99
100 additional_paths.append(os.path.join(tmpdir, wheel_name))
101
102 # Construct the arguments to be passed to the pip command
Donald Stufftf7f58f82014-01-02 09:33:35 -0500103 args = ["install", "--no-index", "--find-links", tmpdir]
Nick Coghland0cf0632013-11-11 22:11:55 +1000104 if root:
105 args += ["--root", root]
106 if upgrade:
107 args += ["--upgrade"]
108 if user:
109 args += ["--user"]
110 if verbosity:
111 args += ["-" + "v" * verbosity]
112
113 _run_pip(args + [p[0] for p in _PROJECTS], additional_paths)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000114
Nick Coghlanf71cae02013-12-23 18:20:34 +1000115def _uninstall_helper(*, verbosity=0):
Nick Coghlaned9af522013-12-23 17:39:12 +1000116 """Helper to support a clean default uninstall process on Windows
117
118 Note that calling this function may alter os.environ.
119 """
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000120 # Nothing to do if pip was never installed, or has been removed
121 try:
122 import pip
123 except ImportError:
124 return
125
126 # If the pip version doesn't match the bundled one, leave it alone
127 if pip.__version__ != _PIP_VERSION:
128 msg = ("ensurepip will only uninstall a matching pip "
129 "({!r} installed, {!r} bundled)")
130 raise RuntimeError(msg.format(pip.__version__, _PIP_VERSION))
131
Nick Coghlanae2ee962013-12-23 23:07:07 +1000132 _require_ssl_for_pip()
Nick Coghlaned9af522013-12-23 17:39:12 +1000133 _clear_pip_environment_variables()
134
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000135 # Construct the arguments to be passed to the pip command
136 args = ["uninstall", "-y"]
137 if verbosity:
138 args += ["-" + "v" * verbosity]
139
140 _run_pip(args + [p[0] for p in reversed(_PROJECTS)])
Nick Coghlanf71cae02013-12-23 18:20:34 +1000141
142
143def _main(argv=None):
144 import argparse
145 parser = argparse.ArgumentParser(prog="python -m ensurepip")
146 parser.add_argument(
147 "--version",
148 action="version",
149 version="pip {}".format(version()),
150 help="Show the version of pip that is bundled with this Python.",
151 )
152 parser.add_argument(
153 "-v", "--verbose",
154 action="count",
155 default=0,
156 dest="verbosity",
157 help=("Give more output. Option is additive, and can be used up to 3 "
158 "times."),
159 )
160 parser.add_argument(
161 "-U", "--upgrade",
162 action="store_true",
163 default=False,
164 help="Upgrade pip and dependencies, even if already installed.",
165 )
166 parser.add_argument(
167 "--user",
168 action="store_true",
169 default=False,
170 help="Install using the user scheme.",
171 )
172 parser.add_argument(
173 "--root",
174 default=None,
175 help="Install everything relative to this alternate root directory.",
176 )
177 parser.add_argument(
178 "--altinstall",
179 action="store_true",
180 default=False,
181 help=("Make an alternate install, installing only the X.Y versioned"
182 "scripts (Default: pipX, pipX.Y, easy_install-X.Y)"),
183 )
184 parser.add_argument(
185 "--default-pip",
186 action="store_true",
187 default=False,
188 help=("Make a default pip install, installing the unqualified pip "
189 "and easy_install in addition to the versioned scripts"),
190 )
191
192 args = parser.parse_args(argv)
193
194 bootstrap(
195 root=args.root,
196 upgrade=args.upgrade,
197 user=args.user,
198 verbosity=args.verbosity,
199 altinstall=args.altinstall,
200 default_pip=args.default_pip,
201 )