util.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import os
  2. import errno
  3. import logging
  4. from pathlib import Path
  5. import requests
  6. import sys
  7. logger = logging.getLogger(__name__)
  8. PY3 = sys.version_info[0] >= 3
  9. if PY3:
  10. text_types = (str,)
  11. else:
  12. text_types = (str, unicode) # analysis:ignore
  13. def download(url, target):
  14. """Download a file using requests.
  15. This is like urllib.request.urlretrieve, but requests validates SSL
  16. certificates by default.
  17. """
  18. if isinstance(target, Path):
  19. target = str(target)
  20. from . import __version__
  21. headers = {'user-agent': 'Pynsist/'+__version__}
  22. r = requests.get(url, headers=headers, stream=True)
  23. r.raise_for_status()
  24. with open(target, 'wb') as f:
  25. for chunk in r.iter_content(chunk_size=1024):
  26. if chunk:
  27. f.write(chunk)
  28. def get_cache_dir(ensure_existence=False):
  29. if os.name == 'posix' and sys.platform != 'darwin':
  30. # Linux, Unix, AIX, etc.
  31. # use ~/.cache if empty OR not set
  32. xdg = os.environ.get("XDG_CACHE_HOME", None) or (os.path.expanduser('~/.cache'))
  33. p = Path(xdg, 'pynsist')
  34. elif sys.platform == 'darwin':
  35. p = Path(os.path.expanduser('~'), 'Library/Caches/pynsist')
  36. else:
  37. # Windows (hopefully)
  38. local = os.environ.get('LOCALAPPDATA', None) or (os.path.expanduser('~\\AppData\\Local'))
  39. if local.startswith('~'):
  40. logger.warning("Could not find cache directory. Please set any of "
  41. "these environment variables: "
  42. "LOCALAPPDATA, HOME, USERPROFILE or HOMEPATH")
  43. p = Path(local, 'pynsist')
  44. if ensure_existence:
  45. try:
  46. p.mkdir(parents=True)
  47. except OSError as e:
  48. # Py2 compatible equivalent of FileExistsError
  49. if e.errno != errno.EEXIST:
  50. raise
  51. return p