pypi.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. """Find, download and unpack wheels."""
  2. import fnmatch
  3. import hashlib
  4. import logging
  5. from pathlib import Path
  6. import re
  7. import shutil
  8. from tempfile import mkdtemp
  9. import zipfile
  10. import yarg
  11. from requests_download import download, HashTracker
  12. from .util import get_cache_dir, normalize_path
  13. logger = logging.getLogger(__name__)
  14. class NoWheelError(Exception): pass
  15. class WheelLocator(object):
  16. def __init__(self, requirement, py_version, bitness, extra_sources=None):
  17. self.requirement = requirement
  18. self.py_version = py_version
  19. self.bitness = bitness
  20. self.extra_sources = extra_sources or []
  21. if requirement.count('==') != 1:
  22. raise ValueError("Requirement {!r} did not match name==version".format(requirement))
  23. self.name, self.version = requirement.split('==', 1)
  24. def score_platform(self, platform):
  25. target = 'win_amd64' if self.bitness == 64 else 'win32'
  26. d = {target: 2, 'any': 1}
  27. return max(d.get(p, 0) for p in platform.split('.'))
  28. def score_abi(self, abi):
  29. py_version_nodot = ''.join(self.py_version.split('.')[:2])
  30. # Are there other valid options here?
  31. d = {'cp%sm' % py_version_nodot: 3, # Is the m reliable?
  32. 'abi3': 2, 'none': 1}
  33. return max(d.get(a, 0) for a in abi.split('.'))
  34. def score_interpreter(self, interpreter):
  35. py_version_nodot = ''.join(self.py_version.split('.')[:2])
  36. py_version_major = self.py_version.split('.')[0]
  37. d = {'cp'+py_version_nodot: 4,
  38. 'cp'+py_version_major: 3,
  39. 'py'+py_version_nodot: 2,
  40. 'py'+py_version_major: 1
  41. }
  42. return max(d.get(i, 0) for i in interpreter.split('.'))
  43. def pick_best_wheel(self, release_list):
  44. best_score = (0, 0, 0)
  45. best = None
  46. for release in release_list:
  47. if release.package_type != 'wheel':
  48. continue
  49. m = re.search(r'-([^-]+)-([^-]+)-([^-]+)\.whl', release.filename)
  50. if not m:
  51. continue
  52. interpreter, abi, platform = m.group(1, 2, 3)
  53. score = (self.score_platform(platform),
  54. self.score_abi(abi),
  55. self.score_interpreter(interpreter)
  56. )
  57. if any(s==0 for s in score):
  58. # Incompatible
  59. continue
  60. if score > best_score:
  61. best = release
  62. best_score = score
  63. return best
  64. def check_extra_sources(self):
  65. """Find a compatible wheel in the specified extra_sources directories.
  66. Returns a Path or None.
  67. """
  68. whl_filename_prefix = '{name}-{version}-'.format(
  69. name=re.sub("[^\w\d.]+", "_", self.name),
  70. version=re.sub("[^\w\d.]+", "_", self.version),
  71. )
  72. for source in self.extra_sources:
  73. candidates = [CachedRelease(p.name)
  74. for p in source.iterdir()
  75. if p.name.startswith(whl_filename_prefix)]
  76. rel = self.pick_best_wheel(candidates)
  77. if rel:
  78. path = source / rel.filename
  79. logger.info('Using wheel from extra directory: %s', path)
  80. return path
  81. def check_cache(self):
  82. """Find a wheel previously downloaded from PyPI in the cache.
  83. Returns a Path or None.
  84. """
  85. release_dir = get_cache_dir() / 'pypi' / self.name / self.version
  86. if not release_dir.is_dir():
  87. return None
  88. rel = self.pick_best_wheel(CachedRelease(p.name)
  89. for p in release_dir.iterdir())
  90. if rel is None:
  91. return None
  92. logger.info('Using cached wheel: %s', rel.filename)
  93. return release_dir / rel.filename
  94. def get_from_pypi(self):
  95. """Download a compatible wheel from PyPI.
  96. Downloads to the cache directory and returns the destination as a Path.
  97. Raises NoWheelError if no compatible wheel is found.
  98. """
  99. try:
  100. pypi_pkg = yarg.get(self.name)
  101. except yarg.HTTPError as e:
  102. if e.status_code == 404:
  103. raise NoWheelError("No package named {} found on PyPI".format(self.name))
  104. raise
  105. release_list = pypi_pkg.release(self.version)
  106. if release_list is None:
  107. raise NoWheelError("No release {0.version} for package {0.name}".format(self))
  108. preferred_release = self.pick_best_wheel(release_list)
  109. if preferred_release is None:
  110. raise NoWheelError('No compatible wheels found for {0.name} {0.version}'.format(self))
  111. download_to = get_cache_dir() / 'pypi' / self.name / self.version
  112. try:
  113. download_to.mkdir(parents=True)
  114. except OSError:
  115. # Ignore OSError only if the directory exists
  116. if not download_to.is_dir():
  117. raise
  118. target = download_to / preferred_release.filename
  119. from . import __version__
  120. hasher = HashTracker(hashlib.md5())
  121. headers = {'user-agent': 'pynsist/'+__version__}
  122. logger.info('Downloading wheel: %s', preferred_release.url)
  123. download(preferred_release.url, str(target), headers=headers,
  124. trackers=(hasher,))
  125. if hasher.hashobj.hexdigest() != preferred_release.md5_digest:
  126. target.unlink()
  127. raise ValueError('Downloaded wheel corrupted: {}'.format(preferred_release.url))
  128. return target
  129. def fetch(self):
  130. """Find and return a compatible wheel (main interface)"""
  131. p = self.check_extra_sources()
  132. if p is not None:
  133. return p
  134. p = self.check_cache()
  135. if p is not None:
  136. return p
  137. return self.get_from_pypi()
  138. class CachedRelease(object):
  139. # Mock enough of the yarg Release object to be compatible with
  140. # pick_best_release above
  141. def __init__(self, filename):
  142. self.filename = filename
  143. self.package_type = 'wheel' if filename.endswith('.whl') else ''
  144. def merge_dir_to(src, dst):
  145. """Merge all files from one directory into another.
  146. Subdirectories will be merged recursively. If filenames are the same, those
  147. from src will overwrite those in dst. If a regular file clashes with a
  148. directory, an error will occur.
  149. """
  150. for p in src.iterdir():
  151. if p.is_dir():
  152. dst_p = dst / p.name
  153. if dst_p.is_dir():
  154. merge_dir_to(p, dst_p)
  155. elif dst_p.is_file():
  156. raise RuntimeError('Directory {} clashes with file {}'
  157. .format(p, dst_p))
  158. else:
  159. shutil.copytree(str(p), str(dst_p))
  160. else:
  161. # Copy regular file
  162. dst_p = dst / p.name
  163. if dst_p.is_dir():
  164. raise RuntimeError('File {} clashes with directory {}'
  165. .format(p, dst_p))
  166. shutil.copy2(str(p), str(dst_p))
  167. def extract_wheel(whl_file, target_dir, exclude=None):
  168. """Extract importable modules from a wheel to the target directory
  169. """
  170. # Extract to temporary directory
  171. td = Path(mkdtemp())
  172. with zipfile.ZipFile(str(whl_file), mode='r') as zf:
  173. if exclude:
  174. basename = Path(Path(target_dir).name)
  175. for zpath in zf.namelist():
  176. path = basename / zpath
  177. if is_excluded(path, exclude):
  178. continue # Skip excluded paths
  179. zf.extract(zpath, path=str(td))
  180. else:
  181. zf.extractall(str(td))
  182. # Move extra lib files out of the .data subdirectory
  183. for p in td.iterdir():
  184. if p.suffix == '.data':
  185. if (p / 'purelib').is_dir():
  186. merge_dir_to(p / 'purelib', td)
  187. if (p / 'platlib').is_dir():
  188. merge_dir_to(p / 'platlib', td)
  189. # Copy to target directory
  190. target = Path(target_dir)
  191. copied_something = False
  192. for p in td.iterdir():
  193. if p.suffix not in {'.data', '.dist-info'}:
  194. if p.is_dir():
  195. # If the dst directory already exists, this will combine them.
  196. # shutil.copytree will not combine them.
  197. try:
  198. target.joinpath(p.name).mkdir()
  199. except OSError:
  200. if not target.joinpath(p.name).is_dir():
  201. raise
  202. merge_dir_to(p, target / p.name)
  203. else:
  204. shutil.copy2(str(p), str(target))
  205. copied_something = True
  206. if not copied_something:
  207. raise RuntimeError("Did not find any files to extract from wheel {}"
  208. .format(whl_file))
  209. # Clean up temporary directory
  210. shutil.rmtree(str(td))
  211. def fetch_pypi_wheels(requirements, target_dir, py_version, bitness,
  212. extra_sources=None, exclude=None):
  213. for req in requirements:
  214. wl = WheelLocator(req, py_version, bitness, extra_sources)
  215. whl_file = wl.fetch()
  216. extract_wheel(whl_file, target_dir, exclude=exclude)
  217. def is_excluded(path, exclude):
  218. """Return True if path matches an exclude pattern"""
  219. path = normalize_path(path)
  220. for pattern in (exclude or ()):
  221. if fnmatch.fnmatch(path, pattern):
  222. return True
  223. return False