wheels.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. """Find, download and unpack wheels."""
  2. import fnmatch
  3. import hashlib
  4. import logging
  5. import glob
  6. import os
  7. import re
  8. import shutil
  9. import yarg
  10. import zipfile
  11. from pathlib import Path
  12. from requests_download import download, HashTracker
  13. from tempfile import mkdtemp
  14. from .util import get_cache_dir, normalize_path
  15. logger = logging.getLogger(__name__)
  16. class NoWheelError(Exception): pass
  17. class CompatibilityScorer:
  18. """Score wheels for a given target platform
  19. 0 for any score means incompatible.
  20. Higher numbers are more platform specific.
  21. """
  22. def __init__(self, py_version, platform):
  23. self.py_version = py_version
  24. self.platform = platform
  25. def score_platform(self, platform):
  26. # target = 'win_amd64' if self.bitness == 64 else 'win32'
  27. d = {self.platform: 2, 'any': 1}
  28. return max(d.get(p, 0) for p in platform.split('.'))
  29. def score_abi(self, abi):
  30. py_version_nodot = ''.join(self.py_version.split('.')[:2])
  31. # Are there other valid options here?
  32. d = {'cp%sm' % py_version_nodot: 3, # Is the m reliable?
  33. 'abi3': 2, 'none': 1}
  34. return max(d.get(a, 0) for a in abi.split('.'))
  35. def score_interpreter(self, interpreter):
  36. py_version_nodot = ''.join(self.py_version.split('.')[:2])
  37. py_version_major = self.py_version.split('.')[0]
  38. d = {'cp'+py_version_nodot: 4,
  39. 'cp'+py_version_major: 3,
  40. 'py'+py_version_nodot: 2,
  41. 'py'+py_version_major: 1
  42. }
  43. return max(d.get(i, 0) for i in interpreter.split('.'))
  44. def score(self, whl_filename):
  45. m = re.search(r'-([^-]+)-([^-]+)-([^-]+)\.whl$', whl_filename)
  46. if not m:
  47. raise ValueError("Failed to find wheel tag in %r" % whl_filename)
  48. interpreter, abi, platform = m.group(1, 2, 3)
  49. return (
  50. self.score_platform(platform),
  51. self.score_abi(abi),
  52. self.score_interpreter(interpreter)
  53. )
  54. class WheelLocator(object):
  55. def __init__(self, requirement, scorer, extra_sources=None):
  56. self.requirement = requirement
  57. self.scorer = scorer
  58. self.extra_sources = extra_sources or []
  59. if requirement.count('==') != 1:
  60. raise ValueError("Requirement {!r} did not match name==version".format(requirement))
  61. self.name, self.version = requirement.split('==', 1)
  62. def pick_best_wheel(self, release_list):
  63. best_score = (0, 0, 0)
  64. best = None
  65. for release in release_list:
  66. if release.package_type != 'wheel':
  67. continue
  68. score = self.scorer.score(release.filename)
  69. if any(s==0 for s in score):
  70. # Incompatible
  71. continue
  72. if score > best_score:
  73. best = release
  74. best_score = score
  75. return best
  76. def check_extra_sources(self):
  77. """Find a compatible wheel in the specified extra_sources directories.
  78. Returns a Path or None.
  79. """
  80. whl_filename_prefix = '{name}-{version}-'.format(
  81. name=re.sub(r'[^\w\d.]+', '_', self.name),
  82. version=re.sub(r'[^\w\d.]+', '_', self.version),
  83. )
  84. for source in self.extra_sources:
  85. candidates = [CachedRelease(p.name)
  86. for p in source.iterdir()
  87. if p.name.startswith(whl_filename_prefix)]
  88. rel = self.pick_best_wheel(candidates)
  89. if rel:
  90. path = source / rel.filename
  91. return path
  92. def check_cache(self):
  93. """Find a wheel previously downloaded from PyPI in the cache.
  94. Returns a Path or None.
  95. """
  96. release_dir = get_cache_dir() / 'pypi' / self.name / self.version
  97. if not release_dir.is_dir():
  98. return None
  99. rel = self.pick_best_wheel(CachedRelease(p.name)
  100. for p in release_dir.iterdir())
  101. if rel is None:
  102. return None
  103. return release_dir / rel.filename
  104. def get_from_pypi(self):
  105. """Download a compatible wheel from PyPI.
  106. Downloads to the cache directory and returns the destination as a Path.
  107. Raises NoWheelError if no compatible wheel is found.
  108. """
  109. try:
  110. pypi_pkg = yarg.get(self.name)
  111. except yarg.HTTPError as e:
  112. if e.status_code == 404:
  113. raise NoWheelError("No package named {} found on PyPI".format(self.name))
  114. raise
  115. release_list = pypi_pkg.release(self.version)
  116. if release_list is None:
  117. raise NoWheelError("No release {0.version} for package {0.name}".format(self))
  118. preferred_release = self.pick_best_wheel(release_list)
  119. if preferred_release is None:
  120. raise NoWheelError('No compatible wheels found for {0.name} {0.version}'.format(self))
  121. download_to = get_cache_dir() / 'pypi' / self.name / self.version
  122. try:
  123. download_to.mkdir(parents=True)
  124. except OSError:
  125. # Ignore OSError only if the directory exists
  126. if not download_to.is_dir():
  127. raise
  128. target = download_to / preferred_release.filename
  129. from . import __version__
  130. hasher = HashTracker(hashlib.md5())
  131. headers = {'user-agent': 'pynsist/'+__version__}
  132. logger.info('Downloading wheel: %s', preferred_release.url)
  133. download(preferred_release.url, str(target), headers=headers,
  134. trackers=(hasher,))
  135. if hasher.hashobj.hexdigest() != preferred_release.md5_digest:
  136. target.unlink()
  137. raise ValueError('Downloaded wheel corrupted: {}'.format(preferred_release.url))
  138. return target
  139. def fetch(self):
  140. """Find and return a compatible wheel (main interface)"""
  141. p = self.check_extra_sources()
  142. if p is not None:
  143. logger.info('Using wheel from extra directory: %s', p)
  144. return p
  145. p = self.check_cache()
  146. if p is not None:
  147. logger.info('Using cached wheel: %s', p)
  148. return p
  149. return self.get_from_pypi()
  150. class CachedRelease(object):
  151. # Mock enough of the yarg Release object to be compatible with
  152. # pick_best_release above
  153. def __init__(self, filename):
  154. self.filename = filename
  155. self.package_type = 'wheel' if filename.endswith('.whl') else ''
  156. def merge_dir_to(src, dst):
  157. """Merge all files from one directory into another.
  158. Subdirectories will be merged recursively. If filenames are the same, those
  159. from src will overwrite those in dst. If a regular file clashes with a
  160. directory, an error will occur.
  161. """
  162. for p in src.iterdir():
  163. if p.is_dir():
  164. dst_p = dst / p.name
  165. if dst_p.is_dir():
  166. merge_dir_to(p, dst_p)
  167. elif dst_p.is_file():
  168. raise RuntimeError('Directory {} clashes with file {}'
  169. .format(p, dst_p))
  170. else:
  171. shutil.copytree(str(p), str(dst_p))
  172. else:
  173. # Copy regular file
  174. dst_p = dst / p.name
  175. if dst_p.is_dir():
  176. raise RuntimeError('File {} clashes with directory {}'
  177. .format(p, dst_p))
  178. shutil.copy2(str(p), str(dst_p))
  179. def extract_wheel(whl_file, target_dir, exclude=None):
  180. """Extract importable modules from a wheel to the target directory
  181. """
  182. # Extract to temporary directory
  183. td = Path(mkdtemp())
  184. with zipfile.ZipFile(str(whl_file), mode='r') as zf:
  185. if exclude:
  186. exclude_regexen = make_exclude_regexen(exclude)
  187. for zpath in zf.namelist():
  188. if is_excluded('pkgs/' + zpath, exclude_regexen):
  189. continue # Skip excluded paths
  190. zf.extract(zpath, path=str(td))
  191. else:
  192. zf.extractall(str(td))
  193. # Move extra lib files out of the .data subdirectory
  194. for p in td.iterdir():
  195. if p.suffix == '.data':
  196. if (p / 'purelib').is_dir():
  197. merge_dir_to(p / 'purelib', td)
  198. if (p / 'platlib').is_dir():
  199. merge_dir_to(p / 'platlib', td)
  200. # HACK: Some wheels from Christoph Gohlke's page have extra package
  201. # files added in data/Lib/site-packages. This is a trick that relies
  202. # on the default installation layout. It doesn't look like it will
  203. # change, so in the best tradition of packaging, we'll work around
  204. # the workaround.
  205. # This is especially ugly because we do a case-insensitive match,
  206. # regardless of the filesystem.
  207. if (p / 'data').is_dir():
  208. for sd in (p / 'data').iterdir():
  209. if sd.name.lower() == 'lib' and sd.is_dir():
  210. for sd2 in sd.iterdir():
  211. if sd2.name.lower() == 'site-packages' and sd2.is_dir():
  212. merge_dir_to(sd2, td)
  213. # Copy to target directory
  214. target = Path(target_dir)
  215. copied_something = False
  216. for p in td.iterdir():
  217. if p.suffix not in {'.data'}:
  218. if p.is_dir():
  219. # If the dst directory already exists, this will combine them.
  220. # shutil.copytree will not combine them.
  221. try:
  222. target.joinpath(p.name).mkdir()
  223. except OSError:
  224. if not target.joinpath(p.name).is_dir():
  225. raise
  226. merge_dir_to(p, target / p.name)
  227. else:
  228. shutil.copy2(str(p), str(target))
  229. copied_something = True
  230. if not copied_something:
  231. raise RuntimeError("Did not find any files to extract from wheel {}"
  232. .format(whl_file))
  233. # Clean up temporary directory
  234. shutil.rmtree(str(td))
  235. class WheelGetter:
  236. def __init__(self, requirements, wheel_globs, target_dir,
  237. py_version, bitness, extra_sources=None, exclude=None):
  238. self.requirements = requirements
  239. self.wheel_globs = wheel_globs
  240. self.target_dir = target_dir
  241. target_platform = 'win_amd64' if bitness == 64 else 'win32'
  242. self.scorer = CompatibilityScorer(py_version, target_platform)
  243. self.extra_sources = extra_sources
  244. self.exclude = exclude
  245. self.got_distributions = {}
  246. def get_all(self):
  247. self.get_requirements()
  248. self.get_globs()
  249. def get_requirements(self):
  250. for req in self.requirements:
  251. wl = WheelLocator(req, self.scorer, self.extra_sources)
  252. whl_file = wl.fetch()
  253. extract_wheel(whl_file, self.target_dir, exclude=self.exclude)
  254. self.got_distributions[wl.name] = whl_file
  255. def get_globs(self):
  256. for glob_path in self.wheel_globs:
  257. paths = glob.glob(glob_path)
  258. if not paths:
  259. raise ValueError('Glob path {} does not match any files'
  260. .format(glob_path))
  261. for path in paths:
  262. logger.info('Collecting wheel file: %s (from: %s)',
  263. os.path.basename(path), glob_path)
  264. self.validate_wheel(path)
  265. extract_wheel(path, self.target_dir, exclude=self.exclude)
  266. def validate_wheel(self, whl_path):
  267. """
  268. Verify that the given wheel can safely be included in the current installer.
  269. If so, the given wheel info will be included in the given wheel info array.
  270. If not, an exception will be raised.
  271. """
  272. wheel_name = os.path.basename(whl_path)
  273. distribution = wheel_name.split('-', 1)[0]
  274. # Check that a distribution of same name has not been included before
  275. if distribution in self.got_distributions:
  276. prev_path = self.got_distributions[distribution]
  277. raise ValueError('Multiple wheels specified for {}:\n {}\n {}'.format(
  278. distribution, prev_path, whl_path))
  279. # Check that the wheel is compatible with the installer environment
  280. scores = self.scorer.score(wheel_name)
  281. if any(s == 0 for s in scores):
  282. raise ValueError('Wheel {} is not compatible with Python {}, {}'
  283. .format(wheel_name, self.scorer.py_version, self.scorer.platform))
  284. self.got_distributions[distribution] = whl_path
  285. def make_exclude_regexen(exclude_patterns):
  286. """Translate exclude glob patterns to regex pattern objects.
  287. Handles matching files under a named directory.
  288. """
  289. re_pats = set()
  290. for pattern in exclude_patterns:
  291. re_pats.add(fnmatch.translate(pattern))
  292. if not pattern.endswith('*'):
  293. # Also use the pattern as a directory name and match anything
  294. # under that directory.
  295. suffix = '*' if pattern.endswith('/') else '/*'
  296. re_pats.add(fnmatch.translate(pattern + suffix))
  297. return [re.compile(p) for p in sorted(re_pats)]
  298. def is_excluded(path, exclude_regexen):
  299. """Return True if path matches an exclude pattern"""
  300. path = normalize_path(path)
  301. for re_pattern in exclude_regexen:
  302. if re_pattern.match(path):
  303. return True
  304. return False