util.py 1.7 KB

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