2
Support for installing and building the "wheel" binary package format.
4
from __future__ import with_statement
14
from base64 import urlsafe_b64encode
16
from pip.locations import distutils_scheme
17
from pip.log import logger
18
from pip import pep425tags
19
from pip.util import call_subprocess, normalize_path, make_path_relative
22
# don't use pkg_resources.Requirement.parse, to avoid the override in distribute,
23
# that converts 'setuptools' to 'distribute'.
24
setuptools_requirement = list(pkg_resources.parse_requirements("setuptools>=0.8"))[0]
26
def wheel_setuptools_support():
28
Return True if we have a setuptools that supports wheel.
32
installed_setuptools = pkg_resources.get_distribution('setuptools')
33
if installed_setuptools in setuptools_requirement:
35
except pkg_resources.DistributionNotFound:
38
logger.warn("%s is required for wheel installs." % setuptools_requirement)
41
def rehash(path, algo='sha256', blocksize=1<<20):
42
"""Return (hash, length) for path using hashlib.new(algo)"""
46
block = f.read(blocksize)
50
block = f.read(blocksize)
51
digest = 'sha256='+urlsafe_b64encode(h.digest()).decode('latin1').rstrip('=')
52
return (digest, length)
57
if isinstance(s, unicode):
58
return s.encode('ascii')
62
if isinstance(s, str):
63
return s.encode('ascii')
65
def open_for_csv(name, mode):
66
if sys.version_info[0] < 3:
70
nl = { 'newline': '' }
72
return open(name, mode + bin, **nl)
75
"""Replace #!python with #!/path/to/python
76
Return True if file was changed."""
77
# XXX RECORD hashes will need to be updated
78
if os.path.isfile(path):
79
script = open(path, 'rb')
81
firstline = script.readline()
82
if not firstline.startswith(binary('#!python')):
84
exename = sys.executable.encode(sys.getfilesystemencoding())
85
firstline = binary('#!') + exename + binary(os.linesep)
89
script = open(path, 'wb')
91
script.write(firstline)
97
dist_info_re = re.compile(r"""^(?P<namever>(?P<name>.+?)(-(?P<ver>\d.+?))?)
98
\.dist-info$""", re.VERBOSE)
100
def root_is_purelib(name, wheeldir):
102
Return True if the extracted wheel in wheeldir should go into purelib.
104
name_folded = name.replace("-", "_")
105
for item in os.listdir(wheeldir):
106
match = dist_info_re.match(item)
107
if match and match.group('name') == name_folded:
108
with open(os.path.join(wheeldir, item, 'WHEEL')) as wheel:
110
line = line.lower().rstrip()
111
if line == "root-is-purelib: true":
115
def move_wheel_files(name, req, wheeldir, user=False, home=None):
116
"""Install a wheel"""
118
scheme = distutils_scheme(name, user=user, home=home)
120
if root_is_purelib(name, wheeldir):
121
lib_dir = scheme['purelib']
123
lib_dir = scheme['platlib']
127
source = wheeldir.rstrip(os.path.sep) + os.path.sep
131
def normpath(src, p):
132
return make_path_relative(src, p).replace(os.path.sep, '/')
134
def record_installed(srcfile, destfile, modified=False):
135
"""Map archive RECORD paths to installation RECORD paths."""
136
oldpath = normpath(srcfile, wheeldir)
137
newpath = normpath(destfile, lib_dir)
138
installed[oldpath] = newpath
140
changed.add(destfile)
142
def clobber(source, dest, is_base, fixer=None):
143
if not os.path.exists(dest): # common for the 'include' path
146
for dir, subdirs, files in os.walk(source):
147
basedir = dir[len(source):].lstrip(os.path.sep)
148
if is_base and basedir.split(os.path.sep, 1)[0].endswith('.data'):
151
destsubdir = os.path.join(dest, basedir, s)
152
if is_base and basedir == '' and destsubdir.endswith('.data'):
156
and s.endswith('.dist-info')
157
# is self.req.project_name case preserving?
158
and s.lower().startswith(req.project_name.replace('-', '_').lower())):
159
assert not info_dir, 'Multiple .dist-info directories'
160
info_dir.append(destsubdir)
161
if not os.path.exists(destsubdir):
162
os.makedirs(destsubdir)
164
srcfile = os.path.join(dir, f)
165
destfile = os.path.join(dest, basedir, f)
166
shutil.move(srcfile, destfile)
169
changed = fixer(destfile)
170
record_installed(srcfile, destfile, changed)
172
clobber(source, lib_dir, True)
174
assert info_dir, "%s .dist-info directory not found" % req
176
for datadir in data_dirs:
178
for subdir in os.listdir(os.path.join(wheeldir, datadir)):
180
if subdir == 'scripts':
182
source = os.path.join(wheeldir, datadir, subdir)
183
dest = scheme[subdir]
184
clobber(source, dest, False, fixer=fixer)
186
record = os.path.join(info_dir[0], 'RECORD')
187
temp_record = os.path.join(info_dir[0], 'RECORD.pip')
188
with open_for_csv(record, 'r') as record_in:
189
with open_for_csv(temp_record, 'w+') as record_out:
190
reader = csv.reader(record_in)
191
writer = csv.writer(record_out)
193
row[0] = installed.pop(row[0], row[0])
194
if row[0] in changed:
195
row[1], row[2] = rehash(row[0])
198
writer.writerow((installed[f], '', ''))
199
shutil.move(temp_record, record)
203
def unique(*args, **kw):
205
for item in fn(*args, **kw):
211
# TODO: this goes somewhere besides the wheel module
213
def uninstallation_paths(dist):
215
Yield all the uninstallation paths for dist based on RECORD-without-.pyc
217
Yield paths to all the files in RECORD. For each .py file in RECORD, add
218
the .pyc in the same directory.
220
UninstallPathSet.add() takes care of the __pycache__ .pyc.
222
from pip.req import FakeFile # circular import
223
r = csv.reader(FakeFile(dist.get_metadata_lines('RECORD')))
225
path = os.path.join(dist.location, row[0])
227
if path.endswith('.py'):
228
dn, fn = os.path.split(path)
230
path = os.path.join(dn, base+'.pyc')
237
# TODO: maybe move the install code into this class
239
wheel_file_re = re.compile(
240
r"""^(?P<namever>(?P<name>.+?)(-(?P<ver>\d.+?))?)
241
((-(?P<build>\d.*?))?-(?P<pyver>.+?)-(?P<abi>.+?)-(?P<plat>.+?)
242
\.whl|\.dist-info)$""",
245
def __init__(self, filename):
246
wheel_info = self.wheel_file_re.match(filename)
247
self.filename = filename
248
self.name = wheel_info.group('name').replace('_', '-')
249
self.version = wheel_info.group('ver')
250
self.pyversions = wheel_info.group('pyver').split('.')
251
self.abis = wheel_info.group('abi').split('.')
252
self.plats = wheel_info.group('plat').split('.')
254
# All the tag combinations from this file
255
self.file_tags = set((x, y, z) for x in self.pyversions for y
256
in self.abis for z in self.plats)
258
def support_index_min(self, tags=None):
260
Return the lowest index that a file_tag achieves in the supported_tags list
261
e.g. if there are 8 supported tags, and one of the file tags is first in the
264
if tags is None: # for mock
265
tags = pep425tags.supported_tags
266
indexes = [tags.index(c) for c in self.file_tags if c in tags]
267
return min(indexes) if indexes else None
269
def supported(self, tags=None):
270
"""Is this wheel supported on this system?"""
271
if tags is None: # for mock
272
tags = pep425tags.supported_tags
273
return bool(set(tags).intersection(self.file_tags))
276
class WheelBuilder(object):
277
"""Build wheels from a RequirementSet."""
279
def __init__(self, requirement_set, finder, wheel_dir, build_options=[], global_options=[]):
280
self.requirement_set = requirement_set
282
self.wheel_dir = normalize_path(wheel_dir)
283
self.build_options = build_options
284
self.global_options = global_options
286
def _build_one(self, req):
287
"""Build one wheel."""
290
sys.executable, '-c',
291
"import setuptools;__file__=%r;"\
292
"exec(compile(open(__file__).read().replace('\\r\\n', '\\n'), __file__, 'exec'))" % req.setup_py] + \
293
list(self.global_options)
295
logger.notify('Running setup.py bdist_wheel for %s' % req.name)
296
logger.notify('Destination directory: %s' % self.wheel_dir)
297
wheel_args = base_args + ['bdist_wheel', '-d', self.wheel_dir] + self.build_options
299
call_subprocess(wheel_args, cwd=req.source_dir, show_stdout=False)
302
logger.error('Failed building wheel for %s' % req.name)
308
#unpack and constructs req set
309
self.requirement_set.prepare_files(self.finder)
311
reqset = self.requirement_set.requirements.values()
314
if not os.path.exists(self.wheel_dir):
315
os.makedirs(self.wheel_dir)
318
logger.notify('Building wheels for collected packages: %s' % ', '.join([req.name for req in reqset]))
320
build_success, build_failure = [], []
323
logger.notify("Skipping building wheel: %s", req.url)
325
if self._build_one(req):
326
build_success.append(req)
328
build_failure.append(req)
331
#notify sucess/failure
333
logger.notify('Successfully built %s' % ' '.join([req.name for req in build_success]))
335
logger.notify('Failed to build %s' % ' '.join([req.name for req in build_failure]))