util.py 2.0 KB

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