0 | |
#!/usr/bin/env python
|
1 | |
"""Bootstrap setuptools installation
|
2 | |
|
3 | |
To use setuptools in your package's setup.py, include this
|
4 | |
file in the same directory and add this to the top of your setup.py::
|
5 | |
|
6 | |
from ez_setup import use_setuptools
|
7 | |
use_setuptools()
|
8 | |
|
9 | |
To require a specific version of setuptools, set a download
|
10 | |
mirror, or use an alternate download directory, simply supply
|
11 | |
the appropriate options to ``use_setuptools()``.
|
12 | |
|
13 | |
This file can also be run as a script to install or upgrade setuptools.
|
14 | |
"""
|
15 | |
import os
|
16 | |
import shutil
|
17 | |
import sys
|
18 | |
import tempfile
|
19 | |
import zipfile
|
20 | |
import optparse
|
21 | |
import subprocess
|
22 | |
import platform
|
23 | |
import textwrap
|
24 | |
import contextlib
|
25 | |
|
26 | |
from distutils import log
|
27 | |
|
28 | |
try:
|
29 | |
from urllib.request import urlopen
|
30 | |
except ImportError:
|
31 | |
from urllib2 import urlopen
|
32 | |
|
33 | |
try:
|
34 | |
from site import USER_SITE
|
35 | |
except ImportError:
|
36 | |
USER_SITE = None
|
37 | |
|
38 | |
DEFAULT_VERSION = "5.7"
|
39 | |
DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/"
|
40 | |
|
41 | |
def _python_cmd(*args):
|
42 | |
"""
|
43 | |
Return True if the command succeeded.
|
44 | |
"""
|
45 | |
args = (sys.executable,) + args
|
46 | |
return subprocess.call(args) == 0
|
47 | |
|
48 | |
|
49 | |
def _install(archive_filename, install_args=()):
|
50 | |
with archive_context(archive_filename):
|
51 | |
# installing
|
52 | |
log.warn('Installing Setuptools')
|
53 | |
if not _python_cmd('setup.py', 'install', *install_args):
|
54 | |
log.warn('Something went wrong during the installation.')
|
55 | |
log.warn('See the error message above.')
|
56 | |
# exitcode will be 2
|
57 | |
return 2
|
58 | |
|
59 | |
|
60 | |
def _build_egg(egg, archive_filename, to_dir):
|
61 | |
with archive_context(archive_filename):
|
62 | |
# building an egg
|
63 | |
log.warn('Building a Setuptools egg in %s', to_dir)
|
64 | |
_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
|
65 | |
# returning the result
|
66 | |
log.warn(egg)
|
67 | |
if not os.path.exists(egg):
|
68 | |
raise IOError('Could not build the egg.')
|
69 | |
|
70 | |
|
71 | |
class ContextualZipFile(zipfile.ZipFile):
|
72 | |
"""
|
73 | |
Supplement ZipFile class to support context manager for Python 2.6
|
74 | |
"""
|
75 | |
|
76 | |
def __enter__(self):
|
77 | |
return self
|
78 | |
|
79 | |
def __exit__(self, type, value, traceback):
|
80 | |
self.close()
|
81 | |
|
82 | |
def __new__(cls, *args, **kwargs):
|
83 | |
"""
|
84 | |
Construct a ZipFile or ContextualZipFile as appropriate
|
85 | |
"""
|
86 | |
if hasattr(zipfile.ZipFile, '__exit__'):
|
87 | |
return zipfile.ZipFile(*args, **kwargs)
|
88 | |
return super(ContextualZipFile, cls).__new__(cls)
|
89 | |
|
90 | |
|
91 | |
@contextlib.contextmanager
|
92 | |
def archive_context(filename):
|
93 | |
# extracting the archive
|
94 | |
tmpdir = tempfile.mkdtemp()
|
95 | |
log.warn('Extracting in %s', tmpdir)
|
96 | |
old_wd = os.getcwd()
|
97 | |
try:
|
98 | |
os.chdir(tmpdir)
|
99 | |
with ContextualZipFile(filename) as archive:
|
100 | |
archive.extractall()
|
101 | |
|
102 | |
# going in the directory
|
103 | |
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
|
104 | |
os.chdir(subdir)
|
105 | |
log.warn('Now working in %s', subdir)
|
106 | |
yield
|
107 | |
|
108 | |
finally:
|
109 | |
os.chdir(old_wd)
|
110 | |
shutil.rmtree(tmpdir)
|
111 | |
|
112 | |
|
113 | |
def _do_download(version, download_base, to_dir, download_delay):
|
114 | |
egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg'
|
115 | |
% (version, sys.version_info[0], sys.version_info[1]))
|
116 | |
if not os.path.exists(egg):
|
117 | |
archive = download_setuptools(version, download_base,
|
118 | |
to_dir, download_delay)
|
119 | |
_build_egg(egg, archive, to_dir)
|
120 | |
sys.path.insert(0, egg)
|
121 | |
|
122 | |
# Remove previously-imported pkg_resources if present (see
|
123 | |
# https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
|
124 | |
if 'pkg_resources' in sys.modules:
|
125 | |
del sys.modules['pkg_resources']
|
126 | |
|
127 | |
import setuptools
|
128 | |
setuptools.bootstrap_install_from = egg
|
129 | |
|
130 | |
|
131 | |
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
|
132 | |
to_dir=os.curdir, download_delay=15):
|
133 | |
to_dir = os.path.abspath(to_dir)
|
134 | |
rep_modules = 'pkg_resources', 'setuptools'
|
135 | |
imported = set(sys.modules).intersection(rep_modules)
|
136 | |
try:
|
137 | |
import pkg_resources
|
138 | |
except ImportError:
|
139 | |
return _do_download(version, download_base, to_dir, download_delay)
|
140 | |
try:
|
141 | |
pkg_resources.require("setuptools>=" + version)
|
142 | |
return
|
143 | |
except pkg_resources.DistributionNotFound:
|
144 | |
return _do_download(version, download_base, to_dir, download_delay)
|
145 | |
except pkg_resources.VersionConflict as VC_err:
|
146 | |
if imported:
|
147 | |
msg = textwrap.dedent("""
|
148 | |
The required version of setuptools (>={version}) is not available,
|
149 | |
and can't be installed while this script is running. Please
|
150 | |
install a more recent version first, using
|
151 | |
'easy_install -U setuptools'.
|
152 | |
|
153 | |
(Currently using {VC_err.args[0]!r})
|
154 | |
""").format(VC_err=VC_err, version=version)
|
155 | |
sys.stderr.write(msg)
|
156 | |
sys.exit(2)
|
157 | |
|
158 | |
# otherwise, reload ok
|
159 | |
del pkg_resources, sys.modules['pkg_resources']
|
160 | |
return _do_download(version, download_base, to_dir, download_delay)
|
161 | |
|
162 | |
def _clean_check(cmd, target):
|
163 | |
"""
|
164 | |
Run the command to download target. If the command fails, clean up before
|
165 | |
re-raising the error.
|
166 | |
"""
|
167 | |
try:
|
168 | |
subprocess.check_call(cmd)
|
169 | |
except subprocess.CalledProcessError:
|
170 | |
if os.access(target, os.F_OK):
|
171 | |
os.unlink(target)
|
172 | |
raise
|
173 | |
|
174 | |
def download_file_powershell(url, target):
|
175 | |
"""
|
176 | |
Download the file at url to target using Powershell (which will validate
|
177 | |
trust). Raise an exception if the command cannot complete.
|
178 | |
"""
|
179 | |
target = os.path.abspath(target)
|
180 | |
ps_cmd = (
|
181 | |
"[System.Net.WebRequest]::DefaultWebProxy.Credentials = "
|
182 | |
"[System.Net.CredentialCache]::DefaultCredentials; "
|
183 | |
"(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)"
|
184 | |
% vars()
|
185 | |
)
|
186 | |
cmd = [
|
187 | |
'powershell',
|
188 | |
'-Command',
|
189 | |
ps_cmd,
|
190 | |
]
|
191 | |
_clean_check(cmd, target)
|
192 | |
|
193 | |
def has_powershell():
|
194 | |
if platform.system() != 'Windows':
|
195 | |
return False
|
196 | |
cmd = ['powershell', '-Command', 'echo test']
|
197 | |
with open(os.path.devnull, 'wb') as devnull:
|
198 | |
try:
|
199 | |
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
|
200 | |
except Exception:
|
201 | |
return False
|
202 | |
return True
|
203 | |
|
204 | |
download_file_powershell.viable = has_powershell
|
205 | |
|
206 | |
def download_file_curl(url, target):
|
207 | |
cmd = ['curl', url, '--silent', '--output', target]
|
208 | |
_clean_check(cmd, target)
|
209 | |
|
210 | |
def has_curl():
|
211 | |
cmd = ['curl', '--version']
|
212 | |
with open(os.path.devnull, 'wb') as devnull:
|
213 | |
try:
|
214 | |
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
|
215 | |
except Exception:
|
216 | |
return False
|
217 | |
return True
|
218 | |
|
219 | |
download_file_curl.viable = has_curl
|
220 | |
|
221 | |
def download_file_wget(url, target):
|
222 | |
cmd = ['wget', url, '--quiet', '--output-document', target]
|
223 | |
_clean_check(cmd, target)
|
224 | |
|
225 | |
def has_wget():
|
226 | |
cmd = ['wget', '--version']
|
227 | |
with open(os.path.devnull, 'wb') as devnull:
|
228 | |
try:
|
229 | |
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
|
230 | |
except Exception:
|
231 | |
return False
|
232 | |
return True
|
233 | |
|
234 | |
download_file_wget.viable = has_wget
|
235 | |
|
236 | |
def download_file_insecure(url, target):
|
237 | |
"""
|
238 | |
Use Python to download the file, even though it cannot authenticate the
|
239 | |
connection.
|
240 | |
"""
|
241 | |
src = urlopen(url)
|
242 | |
try:
|
243 | |
# Read all the data in one block.
|
244 | |
data = src.read()
|
245 | |
finally:
|
246 | |
src.close()
|
247 | |
|
248 | |
# Write all the data in one block to avoid creating a partial file.
|
249 | |
with open(target, "wb") as dst:
|
250 | |
dst.write(data)
|
251 | |
|
252 | |
download_file_insecure.viable = lambda: True
|
253 | |
|
254 | |
def get_best_downloader():
|
255 | |
downloaders = (
|
256 | |
download_file_powershell,
|
257 | |
download_file_curl,
|
258 | |
download_file_wget,
|
259 | |
download_file_insecure,
|
260 | |
)
|
261 | |
viable_downloaders = (dl for dl in downloaders if dl.viable())
|
262 | |
return next(viable_downloaders, None)
|
263 | |
|
264 | |
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
|
265 | |
to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader):
|
266 | |
"""
|
267 | |
Download setuptools from a specified location and return its filename
|
268 | |
|
269 | |
`version` should be a valid setuptools version number that is available
|
270 | |
as an sdist for download under the `download_base` URL (which should end
|
271 | |
with a '/'). `to_dir` is the directory where the egg will be downloaded.
|
272 | |
`delay` is the number of seconds to pause before an actual download
|
273 | |
attempt.
|
274 | |
|
275 | |
``downloader_factory`` should be a function taking no arguments and
|
276 | |
returning a function for downloading a URL to a target.
|
277 | |
"""
|
278 | |
# making sure we use the absolute path
|
279 | |
to_dir = os.path.abspath(to_dir)
|
280 | |
zip_name = "setuptools-%s.zip" % version
|
281 | |
url = download_base + zip_name
|
282 | |
saveto = os.path.join(to_dir, zip_name)
|
283 | |
if not os.path.exists(saveto): # Avoid repeated downloads
|
284 | |
log.warn("Downloading %s", url)
|
285 | |
downloader = downloader_factory()
|
286 | |
downloader(url, saveto)
|
287 | |
return os.path.realpath(saveto)
|
288 | |
|
289 | |
def _build_install_args(options):
|
290 | |
"""
|
291 | |
Build the arguments to 'python setup.py install' on the setuptools package
|
292 | |
"""
|
293 | |
return ['--user'] if options.user_install else []
|
294 | |
|
295 | |
def _parse_args():
|
296 | |
"""
|
297 | |
Parse the command line for options
|
298 | |
"""
|
299 | |
parser = optparse.OptionParser()
|
300 | |
parser.add_option(
|
301 | |
'--user', dest='user_install', action='store_true', default=False,
|
302 | |
help='install in user site package (requires Python 2.6 or later)')
|
303 | |
parser.add_option(
|
304 | |
'--download-base', dest='download_base', metavar="URL",
|
305 | |
default=DEFAULT_URL,
|
306 | |
help='alternative URL from where to download the setuptools package')
|
307 | |
parser.add_option(
|
308 | |
'--insecure', dest='downloader_factory', action='store_const',
|
309 | |
const=lambda: download_file_insecure, default=get_best_downloader,
|
310 | |
help='Use internal, non-validating downloader'
|
311 | |
)
|
312 | |
parser.add_option(
|
313 | |
'--version', help="Specify which version to download",
|
314 | |
default=DEFAULT_VERSION,
|
315 | |
)
|
316 | |
options, args = parser.parse_args()
|
317 | |
# positional arguments are ignored
|
318 | |
return options
|
319 | |
|
320 | |
def main():
|
321 | |
"""Install or upgrade setuptools and EasyInstall"""
|
322 | |
options = _parse_args()
|
323 | |
archive = download_setuptools(
|
324 | |
version=options.version,
|
325 | |
download_base=options.download_base,
|
326 | |
downloader_factory=options.downloader_factory,
|
327 | |
)
|
328 | |
return _install(archive, _build_install_args(options))
|
329 | |
|
330 | |
if __name__ == '__main__':
|
331 | |
sys.exit(main())
|