2
"""Bootstrap distribute installation
4
If you want to use setuptools in your package's setup.py, just include this
5
file in the same directory with it, and add this to the top of your setup.py::
7
from distribute_setup import use_setuptools
10
If you want to require a specific version of setuptools, set a download
11
mirror, or use an alternate download directory, you can do so by supplying
12
the appropriate options to ``use_setuptools()``.
14
This file can also be run as a script to install or upgrade setuptools.
22
from distutils import log
25
from site import USER_SITE
32
def _python_cmd(*args):
33
args = (sys.executable,) + args
34
return subprocess.call(args) == 0
37
# will be used for python 2.3
38
def _python_cmd(*args):
39
args = (sys.executable,) + args
40
# quoting arguments if windows
41
if sys.platform == 'win32':
46
args = [quote(arg) for arg in args]
47
return os.spawnl(os.P_WAIT, sys.executable, *args) == 0
49
DEFAULT_VERSION = "0.6.24"
50
DEFAULT_URL = "http://pypi.python.org/packages/source/d/distribute/"
51
SETUPTOOLS_FAKED_VERSION = "0.6c11"
53
SETUPTOOLS_PKG_INFO = """\
63
""" % SETUPTOOLS_FAKED_VERSION
66
def _install(tarball):
67
# extracting the tarball
68
tmpdir = tempfile.mkdtemp()
69
log.warn('Extracting in %s', tmpdir)
73
tar = tarfile.open(tarball)
77
# going in the directory
78
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
80
log.warn('Now working in %s', subdir)
83
log.warn('Installing Distribute')
84
if not _python_cmd('setup.py', 'install'):
85
log.warn('Something went wrong during the installation.')
86
log.warn('See the error message above.')
91
def _build_egg(egg, tarball, to_dir):
92
# extracting the tarball
93
tmpdir = tempfile.mkdtemp()
94
log.warn('Extracting in %s', tmpdir)
98
tar = tarfile.open(tarball)
102
# going in the directory
103
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
105
log.warn('Now working in %s', subdir)
108
log.warn('Building a Distribute egg in %s', to_dir)
109
_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
113
# returning the result
115
if not os.path.exists(egg):
116
raise IOError('Could not build the egg.')
119
def _do_download(version, download_base, to_dir, download_delay):
120
egg = os.path.join(to_dir, 'distribute-%s-py%d.%d.egg'
121
% (version, sys.version_info[0], sys.version_info[1]))
122
if not os.path.exists(egg):
123
tarball = download_setuptools(version, download_base,
124
to_dir, download_delay)
125
_build_egg(egg, tarball, to_dir)
126
sys.path.insert(0, egg)
128
setuptools.bootstrap_install_from = egg
131
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
132
to_dir=os.curdir, download_delay=15, no_fake=True):
133
# making sure we use the absolute path
134
to_dir = os.path.abspath(to_dir)
135
was_imported = 'pkg_resources' in sys.modules or \
136
'setuptools' in sys.modules
140
if not hasattr(pkg_resources, '_distribute'):
145
return _do_download(version, download_base, to_dir, download_delay)
147
pkg_resources.require("distribute>="+version)
149
except pkg_resources.VersionConflict:
150
e = sys.exc_info()[1]
153
"The required version of distribute (>=%s) is not available,\n"
154
"and can't be installed while this script is running. Please\n"
155
"install a more recent version first, using\n"
156
"'easy_install -U distribute'."
157
"\n\n(Currently using %r)\n" % (version, e.args[0]))
160
del pkg_resources, sys.modules['pkg_resources'] # reload ok
161
return _do_download(version, download_base, to_dir,
163
except pkg_resources.DistributionNotFound:
164
return _do_download(version, download_base, to_dir,
168
_create_fake_setuptools_pkg_info(to_dir)
170
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
171
to_dir=os.curdir, delay=15):
172
"""Download distribute from a specified location and return its filename
174
`version` should be a valid distribute version number that is available
175
as an egg for download under the `download_base` URL (which should end
176
with a '/'). `to_dir` is the directory where the egg will be downloaded.
177
`delay` is the number of seconds to pause before an actual download
180
# making sure we use the absolute path
181
to_dir = os.path.abspath(to_dir)
183
from urllib.request import urlopen
185
from urllib2 import urlopen
186
tgz_name = "distribute-%s.tar.gz" % version
187
url = download_base + tgz_name
188
saveto = os.path.join(to_dir, tgz_name)
190
if not os.path.exists(saveto): # Avoid repeated downloads
192
log.warn("Downloading %s", url)
194
# Read/write all in one block, so we don't create a corrupt file
195
# if the download is interrupted.
197
dst = open(saveto, "wb")
204
return os.path.realpath(saveto)
206
def _no_sandbox(function):
207
def __no_sandbox(*args, **kw):
209
from setuptools.sandbox import DirectorySandbox
210
if not hasattr(DirectorySandbox, '_old'):
211
def violation(*args):
213
DirectorySandbox._old = DirectorySandbox._violation
214
DirectorySandbox._violation = violation
222
return function(*args, **kw)
225
DirectorySandbox._violation = DirectorySandbox._old
226
del DirectorySandbox._old
230
def _patch_file(path, content):
231
"""Will backup the file then patch it"""
232
existing_content = open(path).read()
233
if existing_content == content:
235
log.warn('Already patched.')
237
log.warn('Patching...')
246
_patch_file = _no_sandbox(_patch_file)
248
def _same_content(path, content):
249
return open(path).read() == content
251
def _rename_path(path):
252
new_name = path + '.OLD.%s' % time.time()
253
log.warn('Renaming %s into %s', path, new_name)
254
os.rename(path, new_name)
257
def _remove_flat_installation(placeholder):
258
if not os.path.isdir(placeholder):
259
log.warn('Unkown installation at %s', placeholder)
262
for file in os.listdir(placeholder):
263
if fnmatch.fnmatch(file, 'setuptools*.egg-info'):
267
log.warn('Could not locate setuptools*.egg-info')
270
log.warn('Removing elements out of the way...')
271
pkg_info = os.path.join(placeholder, file)
272
if os.path.isdir(pkg_info):
273
patched = _patch_egg_dir(pkg_info)
275
patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO)
278
log.warn('%s already patched.', pkg_info)
280
# now let's move the files out of the way
281
for element in ('setuptools', 'pkg_resources.py', 'site.py'):
282
element = os.path.join(placeholder, element)
283
if os.path.exists(element):
284
_rename_path(element)
286
log.warn('Could not find the %s element of the '
287
'Setuptools distribution', element)
290
_remove_flat_installation = _no_sandbox(_remove_flat_installation)
292
def _after_install(dist):
293
log.warn('After install bootstrap.')
294
placeholder = dist.get_command_obj('install').install_purelib
295
_create_fake_setuptools_pkg_info(placeholder)
297
def _create_fake_setuptools_pkg_info(placeholder):
298
if not placeholder or not os.path.exists(placeholder):
299
log.warn('Could not find the install location')
301
pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1])
302
setuptools_file = 'setuptools-%s-py%s.egg-info' % \
303
(SETUPTOOLS_FAKED_VERSION, pyver)
304
pkg_info = os.path.join(placeholder, setuptools_file)
305
if os.path.exists(pkg_info):
306
log.warn('%s already exists', pkg_info)
309
log.warn('Creating %s', pkg_info)
310
f = open(pkg_info, 'w')
312
f.write(SETUPTOOLS_PKG_INFO)
316
pth_file = os.path.join(placeholder, 'setuptools.pth')
317
log.warn('Creating %s', pth_file)
318
f = open(pth_file, 'w')
320
f.write(os.path.join(os.curdir, setuptools_file))
324
_create_fake_setuptools_pkg_info = _no_sandbox(_create_fake_setuptools_pkg_info)
326
def _patch_egg_dir(path):
327
# let's check if it's already patched
328
pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
329
if os.path.exists(pkg_info):
330
if _same_content(pkg_info, SETUPTOOLS_PKG_INFO):
331
log.warn('%s already patched.', pkg_info)
335
os.mkdir(os.path.join(path, 'EGG-INFO'))
336
pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
337
f = open(pkg_info, 'w')
339
f.write(SETUPTOOLS_PKG_INFO)
344
_patch_egg_dir = _no_sandbox(_patch_egg_dir)
346
def _before_install():
347
log.warn('Before install bootstrap.')
351
def _under_prefix(location):
352
if 'install' not in sys.argv:
354
args = sys.argv[sys.argv.index('install')+1:]
355
for index, arg in enumerate(args):
356
for option in ('--root', '--prefix'):
357
if arg.startswith('%s=' % option):
358
top_dir = arg.split('root=')[-1]
359
return location.startswith(top_dir)
361
if len(args) > index:
362
top_dir = args[index+1]
363
return location.startswith(top_dir)
364
if arg == '--user' and USER_SITE is not None:
365
return location.startswith(USER_SITE)
369
def _fake_setuptools():
370
log.warn('Scanning installed packages')
375
log.warn('Setuptools or Distribute does not seem to be installed.')
377
ws = pkg_resources.working_set
379
setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools',
383
setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools'))
385
if setuptools_dist is None:
386
log.warn('No setuptools distribution found')
388
# detecting if it was already faked
389
setuptools_location = setuptools_dist.location
390
log.warn('Setuptools installation detected at %s', setuptools_location)
392
# if --root or --preix was provided, and if
393
# setuptools is not located in them, we don't patch it
394
if not _under_prefix(setuptools_location):
395
log.warn('Not patching, --root or --prefix is installing Distribute'
396
' in another location')
399
# let's see if its an egg
400
if not setuptools_location.endswith('.egg'):
401
log.warn('Non-egg installation')
402
res = _remove_flat_installation(setuptools_location)
406
log.warn('Egg installation')
407
pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO')
408
if (os.path.exists(pkg_info) and
409
_same_content(pkg_info, SETUPTOOLS_PKG_INFO)):
410
log.warn('Already patched.')
412
log.warn('Patching...')
413
# let's create a fake egg replacing setuptools one
414
res = _patch_egg_dir(setuptools_location)
417
log.warn('Patched done.')
422
log.warn('Relaunching...')
423
# we have to relaunch the process
424
# pip marker to avoid a relaunch bug
425
if sys.argv[:3] == ['-c', 'install', '--single-version-externally-managed']:
426
sys.argv[0] = 'setup.py'
427
args = [sys.executable] + sys.argv
428
sys.exit(subprocess.call(args))
431
def _extractall(self, path=".", members=None):
432
"""Extract all members from the archive to the current working
433
directory and set owner, modification time and permissions on
434
directories afterwards. `path' specifies a different directory
435
to extract to. `members' is optional and must be a subset of the
436
list returned by getmembers().
440
from tarfile import ExtractError
446
for tarinfo in members:
448
# Extract directories with a safe mode.
449
directories.append(tarinfo)
450
tarinfo = copy.copy(tarinfo)
451
tarinfo.mode = 448 # decimal for oct 0700
452
self.extract(tarinfo, path)
454
# Reverse sort directories.
455
if sys.version_info < (2, 4):
456
def sorter(dir1, dir2):
457
return cmp(dir1.name, dir2.name)
458
directories.sort(sorter)
459
directories.reverse()
461
directories.sort(key=operator.attrgetter('name'), reverse=True)
463
# Set correct owner, mtime and filemode on directories.
464
for tarinfo in directories:
465
dirpath = os.path.join(path, tarinfo.name)
467
self.chown(tarinfo, dirpath)
468
self.utime(tarinfo, dirpath)
469
self.chmod(tarinfo, dirpath)
471
e = sys.exc_info()[1]
472
if self.errorlevel > 1:
475
self._dbg(1, "tarfile: %s" % e)
478
def main(argv, version=DEFAULT_VERSION):
479
"""Install or upgrade setuptools and EasyInstall"""
480
tarball = download_setuptools()
484
if __name__ == '__main__':