util.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. CACHE_ENV_VAR = 'PYNSIST_CACHE_DIR'
  23. def get_cache_dir(ensure_existence=False):
  24. specified = os.environ.get(CACHE_ENV_VAR, None)
  25. if specified:
  26. p = Path(specified)
  27. elif os.name == 'posix' and sys.platform != 'darwin':
  28. # Linux, Unix, AIX, etc.
  29. # use ~/.cache if empty OR not set
  30. xdg = os.environ.get("XDG_CACHE_HOME", None) or (os.path.expanduser('~/.cache'))
  31. p = Path(xdg, 'pynsist')
  32. elif sys.platform == 'darwin':
  33. p = Path(os.path.expanduser('~'), 'Library/Caches/pynsist')
  34. else:
  35. # Windows (hopefully)
  36. local = os.environ.get('LOCALAPPDATA', None) or (os.path.expanduser('~\\AppData\\Local'))
  37. if local.startswith('~'):
  38. logger.warning("Could not find cache directory. Please set any of "
  39. "these environment variables: "
  40. "LOCALAPPDATA, HOME, USERPROFILE or HOMEPATH")
  41. p = Path(local, 'pynsist')
  42. if ensure_existence:
  43. p.mkdir(parents=True, exist_ok=True)
  44. return p
  45. def normalize_path(path):
  46. """Normalize paths to contain "/" only"""
  47. return os.path.normpath(path).replace('\\', '/')