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