downloader.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from __future__ import absolute_import
  2. from __future__ import print_function
  3. from __future__ import unicode_literals
  4. import hashlib
  5. import os
  6. import requests
  7. from .const import BINTRAY_ORG
  8. from .const import NAME
  9. from .const import REPO_ROOT
  10. from .utils import branch_name
  11. class BinaryDownloader(requests.Session):
  12. base_bintray_url = 'https://dl.bintray.com/{}'.format(BINTRAY_ORG)
  13. base_appveyor_url = 'https://ci.appveyor.com/api/projects/{}/artifacts/'.format(NAME)
  14. def __init__(self, destination, *args, **kwargs):
  15. super(BinaryDownloader, self).__init__(*args, **kwargs)
  16. self.destination = destination
  17. os.makedirs(self.destination, exist_ok=True)
  18. def download_from_bintray(self, repo_name, filename):
  19. print('Downloading {} from bintray'.format(filename))
  20. url = '{base}/{repo_name}/{filename}'.format(
  21. base=self.base_bintray_url, repo_name=repo_name, filename=filename
  22. )
  23. full_dest = os.path.join(REPO_ROOT, self.destination, filename)
  24. return self._download(url, full_dest)
  25. def download_from_appveyor(self, branch_name, filename):
  26. print('Downloading {} from appveyor'.format(filename))
  27. url = '{base}/dist%2F{filename}?branch={branch_name}'.format(
  28. base=self.base_appveyor_url, filename=filename, branch_name=branch_name
  29. )
  30. full_dest = os.path.join(REPO_ROOT, self.destination, filename)
  31. return self._download(url, full_dest)
  32. def _download(self, url, full_dest):
  33. m = hashlib.sha256()
  34. with open(full_dest, 'wb') as f:
  35. r = self.get(url, stream=True)
  36. for chunk in r.iter_content(chunk_size=1024 * 600, decode_unicode=False):
  37. print('.', end='', flush=True)
  38. m.update(chunk)
  39. f.write(chunk)
  40. print(' download complete')
  41. hex_digest = m.hexdigest()
  42. with open(full_dest + '.sha256', 'w') as f:
  43. f.write('{} {}\n'.format(hex_digest, os.path.basename(full_dest)))
  44. return full_dest, hex_digest
  45. def download_all(self, version):
  46. files = {
  47. 'docker-compose-Darwin-x86_64': None,
  48. 'docker-compose-Linux-x86_64': None,
  49. 'docker-compose-Windows-x86_64.exe': None,
  50. }
  51. for filename in files.keys():
  52. if 'Windows' in filename:
  53. files[filename] = self.download_from_appveyor(
  54. branch_name(version), filename
  55. )
  56. else:
  57. files[filename] = self.download_from_bintray(
  58. branch_name(version), filename
  59. )
  60. return files