outdated.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. from __future__ import absolute_import
  2. import datetime
  3. import errno
  4. import json
  5. import logging
  6. import os.path
  7. import sys
  8. from pip._vendor import lockfile
  9. from pip._vendor import pkg_resources
  10. from pip.compat import total_seconds
  11. from pip.index import PyPI
  12. from pip.locations import USER_CACHE_DIR, running_under_virtualenv
  13. from pip.utils.filesystem import check_path_owner
  14. SELFCHECK_DATE_FMT = "%Y-%m-%dT%H:%M:%SZ"
  15. logger = logging.getLogger(__name__)
  16. class VirtualenvSelfCheckState(object):
  17. def __init__(self):
  18. self.statefile_path = os.path.join(sys.prefix, "pip-selfcheck.json")
  19. # Load the existing state
  20. try:
  21. with open(self.statefile_path) as statefile:
  22. self.state = json.load(statefile)
  23. except (IOError, ValueError):
  24. self.state = {}
  25. def save(self, pypi_version, current_time):
  26. # Attempt to write out our version check file
  27. with open(self.statefile_path, "w") as statefile:
  28. json.dump(
  29. {
  30. "last_check": current_time.strftime(SELFCHECK_DATE_FMT),
  31. "pypi_version": pypi_version,
  32. },
  33. statefile,
  34. sort_keys=True,
  35. separators=(",", ":")
  36. )
  37. class GlobalSelfCheckState(object):
  38. def __init__(self):
  39. self.statefile_path = os.path.join(USER_CACHE_DIR, "selfcheck.json")
  40. # Load the existing state
  41. try:
  42. with open(self.statefile_path) as statefile:
  43. self.state = json.load(statefile)[sys.prefix]
  44. except (IOError, ValueError, KeyError):
  45. self.state = {}
  46. def save(self, pypi_version, current_time):
  47. # Check to make sure that we own the directory
  48. if not check_path_owner(os.path.dirname(self.statefile_path)):
  49. return
  50. # Now that we've ensured the directory is owned by this user, we'll go
  51. # ahead and make sure that all our directories are created.
  52. try:
  53. os.makedirs(os.path.dirname(self.statefile_path))
  54. except OSError as exc:
  55. if exc.errno != errno.EEXIST:
  56. raise
  57. # Attempt to write out our version check file
  58. with lockfile.LockFile(self.statefile_path):
  59. if os.path.exists(self.statefile_path):
  60. with open(self.statefile_path) as statefile:
  61. state = json.load(statefile)
  62. else:
  63. state = {}
  64. state[sys.prefix] = {
  65. "last_check": current_time.strftime(SELFCHECK_DATE_FMT),
  66. "pypi_version": pypi_version,
  67. }
  68. with open(self.statefile_path, "w") as statefile:
  69. json.dump(state, statefile, sort_keys=True,
  70. separators=(",", ":"))
  71. def load_selfcheck_statefile():
  72. if running_under_virtualenv():
  73. return VirtualenvSelfCheckState()
  74. else:
  75. return GlobalSelfCheckState()
  76. def pip_version_check(session):
  77. """Check for an update for pip.
  78. Limit the frequency of checks to once per week. State is stored either in
  79. the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix
  80. of the pip script path.
  81. """
  82. import pip # imported here to prevent circular imports
  83. pypi_version = None
  84. try:
  85. state = load_selfcheck_statefile()
  86. current_time = datetime.datetime.utcnow()
  87. # Determine if we need to refresh the state
  88. if "last_check" in state.state and "pypi_version" in state.state:
  89. last_check = datetime.datetime.strptime(
  90. state.state["last_check"],
  91. SELFCHECK_DATE_FMT
  92. )
  93. if total_seconds(current_time - last_check) < 7 * 24 * 60 * 60:
  94. pypi_version = state.state["pypi_version"]
  95. # Refresh the version if we need to or just see if we need to warn
  96. if pypi_version is None:
  97. resp = session.get(
  98. PyPI.pip_json_url,
  99. headers={"Accept": "application/json"},
  100. )
  101. resp.raise_for_status()
  102. pypi_version = resp.json()["info"]["version"]
  103. # save that we've performed a check
  104. state.save(pypi_version, current_time)
  105. pip_version = pkg_resources.parse_version(pip.__version__)
  106. # Determine if our pypi_version is older
  107. if pip_version < pkg_resources.parse_version(pypi_version):
  108. logger.warning(
  109. "You are using pip version %s, however version %s is "
  110. "available.\nYou should consider upgrading via the "
  111. "'pip install --upgrade pip' command." % (pip.__version__,
  112. pypi_version)
  113. )
  114. except Exception:
  115. logger.debug(
  116. "There was an error checking the latest version of pip",
  117. exc_info=True,
  118. )