ez_setup.py 12.2 KB
Newer Older
1
#!/usr/bin/env python
2

3 4
"""
Setuptools bootstrapping installer.
5

6
Maintained at https://github.com/pypa/setuptools/tree/bootstrap.
7

8
Run this script to install or upgrade setuptools.
9 10

This method is DEPRECATED. Check https://github.com/pypa/setuptools/issues/581 for more details.
11
"""
12

13 14 15 16
import os
import shutil
import sys
import tempfile
17
import zipfile
18 19 20
import optparse
import subprocess
import platform
21 22
import textwrap
import contextlib
23 24 25

from distutils import log

26 27 28 29 30
try:
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen

31 32 33 34 35
try:
    from site import USER_SITE
except ImportError:
    USER_SITE = None

36 37
# 33.1.1 is the last version that supports setuptools self upgrade/installation.
DEFAULT_VERSION = "33.1.1"
38 39
DEFAULT_URL = "https://pypi.io/packages/source/s/setuptools/"
DEFAULT_SAVE_DIR = os.curdir
40 41 42 43 44
DEFAULT_DEPRECATION_MESSAGE = "ez_setup.py is deprecated and when using it setuptools will be pinned to {0} since it's the last version that supports setuptools self upgrade/installation, check https://github.com/pypa/setuptools/issues/581 for more info; use pip to install setuptools"

MEANINGFUL_INVALID_ZIP_ERR_MSG = 'Maybe {0} is corrupted, delete it and try again.'

log.warn(DEFAULT_DEPRECATION_MESSAGE.format(DEFAULT_VERSION))
45

46 47

def _python_cmd(*args):
48 49 50 51 52
    """
    Execute a command.

    Return True if the command succeeded.
    """
53 54 55 56
    args = (sys.executable,) + args
    return subprocess.call(args) == 0


57 58 59
def _install(archive_filename, install_args=()):
    """Install Setuptools."""
    with archive_context(archive_filename):
60 61 62 63 64 65 66 67 68
        # installing
        log.warn('Installing Setuptools')
        if not _python_cmd('setup.py', 'install', *install_args):
            log.warn('Something went wrong during the installation.')
            log.warn('See the error message above.')
            # exitcode will be 2
            return 2


69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
def _build_egg(egg, archive_filename, to_dir):
    """Build Setuptools egg."""
    with archive_context(archive_filename):
        # building an egg
        log.warn('Building a Setuptools egg in %s', to_dir)
        _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
    # returning the result
    log.warn(egg)
    if not os.path.exists(egg):
        raise IOError('Could not build the egg.')


class ContextualZipFile(zipfile.ZipFile):

    """Supplement ZipFile class to support context manager for Python 2.6."""

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.close()

    def __new__(cls, *args, **kwargs):
        """Construct a ZipFile or ContextualZipFile as appropriate."""
        if hasattr(zipfile.ZipFile, '__exit__'):
            return zipfile.ZipFile(*args, **kwargs)
        return super(ContextualZipFile, cls).__new__(cls)


@contextlib.contextmanager
def archive_context(filename):
    """
    Unzip filename to a temporary directory, set to the cwd.

    The unzipped target is cleaned up after.
    """
105 106 107 108 109
    tmpdir = tempfile.mkdtemp()
    log.warn('Extracting in %s', tmpdir)
    old_wd = os.getcwd()
    try:
        os.chdir(tmpdir)
110 111 112 113 114 115 116 117 118 119
        try:
            with ContextualZipFile(filename) as archive:
                archive.extractall()
        except zipfile.BadZipfile as err:
            if not err.args:
                err.args = ('', )
            err.args = err.args + (
                MEANINGFUL_INVALID_ZIP_ERR_MSG.format(filename),
            )
            raise
120 121 122 123 124

        # going in the directory
        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
        os.chdir(subdir)
        log.warn('Now working in %s', subdir)
125
        yield
126 127 128 129 130 131 132

    finally:
        os.chdir(old_wd)
        shutil.rmtree(tmpdir)


def _do_download(version, download_base, to_dir, download_delay):
133
    """Download Setuptools."""
134 135 136
    py_desig = 'py{sys.version_info[0]}.{sys.version_info[1]}'.format(sys=sys)
    tp = 'setuptools-{version}-{py_desig}.egg'
    egg = os.path.join(to_dir, tp.format(**locals()))
137
    if not os.path.exists(egg):
138
        archive = download_setuptools(version, download_base,
139
            to_dir, download_delay)
140
        _build_egg(egg, archive, to_dir)
141 142 143 144 145
    sys.path.insert(0, egg)

    # Remove previously-imported pkg_resources if present (see
    # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
    if 'pkg_resources' in sys.modules:
146
        _unload_pkg_resources()
147 148 149 150 151

    import setuptools
    setuptools.bootstrap_install_from = egg


152 153 154 155 156 157 158 159 160
def use_setuptools(
        version=DEFAULT_VERSION, download_base=DEFAULT_URL,
        to_dir=DEFAULT_SAVE_DIR, download_delay=15):
    """
    Ensure that a setuptools version is installed.

    Return None. Raise SystemExit if the requested version
    or later cannot be installed.
    """
161
    to_dir = os.path.abspath(to_dir)
162 163 164 165 166 167

    # prior to importing, capture the module state for
    # representative modules.
    rep_modules = 'pkg_resources', 'setuptools'
    imported = set(sys.modules).intersection(rep_modules)

168 169 170
    try:
        import pkg_resources
        pkg_resources.require("setuptools>=" + version)
171
        # a suitable version is already installed
172
        return
173 174 175
    except ImportError:
        # pkg_resources not available; setuptools is not installed; download
        pass
176
    except pkg_resources.DistributionNotFound:
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
        # no version of setuptools was found; allow download
        pass
    except pkg_resources.VersionConflict as VC_err:
        if imported:
            _conflict_bail(VC_err, version)

        # otherwise, unload pkg_resources to allow the downloaded version to
        #  take precedence.
        del pkg_resources
        _unload_pkg_resources()

    return _do_download(version, download_base, to_dir, download_delay)


def _conflict_bail(VC_err, version):
    """
    Setuptools was imported prior to invocation, so it is
    unsafe to unload it. Bail out.
    """
    conflict_tmpl = textwrap.dedent("""
        The required version of setuptools (>={version}) is not available,
        and can't be installed while this script is running. Please
        install a more recent version first, using
        'easy_install -U setuptools'.

        (Currently using {VC_err.args[0]!r})
        """)
    msg = conflict_tmpl.format(**locals())
    sys.stderr.write(msg)
    sys.exit(2)


def _unload_pkg_resources():
    sys.meta_path = [
        importer
        for importer in sys.meta_path
        if importer.__class__.__module__ != 'pkg_resources.extern'
    ]
    del_modules = [
        name for name in sys.modules
        if name.startswith('pkg_resources')
    ]
    for mod_name in del_modules:
        del sys.modules[mod_name]

222 223 224

def _clean_check(cmd, target):
    """
225 226 227
    Run the command to download target.

    If the command fails, clean up before re-raising the error.
228 229 230 231 232 233 234 235
    """
    try:
        subprocess.check_call(cmd)
    except subprocess.CalledProcessError:
        if os.access(target, os.F_OK):
            os.unlink(target)
        raise

236

237 238
def download_file_powershell(url, target):
    """
239 240 241 242
    Download the file at url to target using Powershell.

    Powershell will validate trust.
    Raise an exception if the command cannot complete.
243 244
    """
    target = os.path.abspath(target)
245 246 247 248 249 250
    ps_cmd = (
        "[System.Net.WebRequest]::DefaultWebProxy.Credentials = "
        "[System.Net.CredentialCache]::DefaultCredentials; "
        '(new-object System.Net.WebClient).DownloadFile("%(url)s", "%(target)s")'
        % locals()
    )
251 252 253
    cmd = [
        'powershell',
        '-Command',
254
        ps_cmd,
255 256 257
    ]
    _clean_check(cmd, target)

258

259
def has_powershell():
260
    """Determine if Powershell is available."""
261 262 263
    if platform.system() != 'Windows':
        return False
    cmd = ['powershell', '-Command', 'echo test']
264
    with open(os.path.devnull, 'wb') as devnull:
265 266
        try:
            subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
267
        except Exception:
268 269 270 271
            return False
    return True
download_file_powershell.viable = has_powershell

272

273
def download_file_curl(url, target):
274
    cmd = ['curl', url, '--location', '--silent', '--output', target]
275 276
    _clean_check(cmd, target)

277

278 279
def has_curl():
    cmd = ['curl', '--version']
280
    with open(os.path.devnull, 'wb') as devnull:
281 282
        try:
            subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
283
        except Exception:
284 285 286 287
            return False
    return True
download_file_curl.viable = has_curl

288

289 290 291 292
def download_file_wget(url, target):
    cmd = ['wget', url, '--quiet', '--output-document', target]
    _clean_check(cmd, target)

293

294 295
def has_wget():
    cmd = ['wget', '--version']
296
    with open(os.path.devnull, 'wb') as devnull:
297 298
        try:
            subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
299
        except Exception:
300 301 302 303
            return False
    return True
download_file_wget.viable = has_wget

304

305
def download_file_insecure(url, target):
306 307
    """Use Python to download the file, without connection authentication."""
    src = urlopen(url)
308
    try:
309
        # Read all the data in one block.
310 311
        data = src.read()
    finally:
312
        src.close()
313

314 315 316
    # Write all the data in one block to avoid creating a partial file.
    with open(target, "wb") as dst:
        dst.write(data)
317 318
download_file_insecure.viable = lambda: True

319

320
def get_best_downloader():
321
    downloaders = (
322 323 324 325
        download_file_powershell,
        download_file_curl,
        download_file_wget,
        download_file_insecure,
326 327 328
    )
    viable_downloaders = (dl for dl in downloaders if dl.viable())
    return next(viable_downloaders, None)
329 330


331 332 333 334 335 336
def download_setuptools(
        version=DEFAULT_VERSION, download_base=DEFAULT_URL,
        to_dir=DEFAULT_SAVE_DIR, delay=15,
        downloader_factory=get_best_downloader):
    """
    Download setuptools from a specified location and return its filename.
337 338

    `version` should be a valid setuptools version number that is available
339
    as an sdist for download under the `download_base` URL (which should end
340 341 342 343 344 345 346 347 348
    with a '/'). `to_dir` is the directory where the egg will be downloaded.
    `delay` is the number of seconds to pause before an actual download
    attempt.

    ``downloader_factory`` should be a function taking no arguments and
    returning a function for downloading a URL to a target.
    """
    # making sure we use the absolute path
    to_dir = os.path.abspath(to_dir)
349 350 351
    zip_name = "setuptools-%s.zip" % version
    url = download_base + zip_name
    saveto = os.path.join(to_dir, zip_name)
352 353 354 355 356 357 358 359 360
    if not os.path.exists(saveto):  # Avoid repeated downloads
        log.warn("Downloading %s", url)
        downloader = downloader_factory()
        downloader(url, saveto)
    return os.path.realpath(saveto)


def _build_install_args(options):
    """
361 362 363
    Build the arguments to 'python setup.py install' on the setuptools package.

    Returns list of command line arguments.
364
    """
365 366
    return ['--user'] if options.user_install else []

367 368

def _parse_args():
369
    """Parse the command line for options."""
370 371 372
    parser = optparse.OptionParser()
    parser.add_option(
        '--user', dest='user_install', action='store_true', default=False,
373
        help='install in user site package')
374 375 376 377 378 379 380 381 382
    parser.add_option(
        '--download-base', dest='download_base', metavar="URL",
        default=DEFAULT_URL,
        help='alternative URL from where to download the setuptools package')
    parser.add_option(
        '--insecure', dest='downloader_factory', action='store_const',
        const=lambda: download_file_insecure, default=get_best_downloader,
        help='Use internal, non-validating downloader'
    )
383 384 385 386 387 388 389 390 391
    parser.add_option(
        '--version', help="Specify which version to download",
        default=DEFAULT_VERSION,
    )
    parser.add_option(
        '--to-dir',
        help="Directory to save (and re-use) package",
        default=DEFAULT_SAVE_DIR,
    )
392 393 394 395
    options, args = parser.parse_args()
    # positional arguments are ignored
    return options

396 397 398 399 400 401 402 403 404 405 406 407 408

def _download_args(options):
    """Return args for download_setuptools function from cmdline args."""
    return dict(
        version=options.version,
        download_base=options.download_base,
        downloader_factory=options.downloader_factory,
        to_dir=options.to_dir,
    )


def main():
    """Install or upgrade setuptools and EasyInstall."""
409
    options = _parse_args()
410 411
    archive = download_setuptools(**_download_args(options))
    return _install(archive, _build_install_args(options))
412 413 414

if __name__ == '__main__':
    sys.exit(main())