You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

161 lines
5.4 KiB

  1. from __future__ import absolute_import
  2. import datetime
  3. import json
  4. import logging
  5. import os.path
  6. import sys
  7. from pip._vendor import lockfile
  8. from pip._vendor.packaging import version as packaging_version
  9. from pip.compat import total_seconds, WINDOWS
  10. from pip.index import PyPI
  11. from pip.locations import USER_CACHE_DIR, running_under_virtualenv
  12. from pip.utils import ensure_dir
  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. ensure_dir(os.path.dirname(self.statefile_path))
  53. # Attempt to write out our version check file
  54. with lockfile.LockFile(self.statefile_path):
  55. if os.path.exists(self.statefile_path):
  56. with open(self.statefile_path) as statefile:
  57. state = json.load(statefile)
  58. else:
  59. state = {}
  60. state[sys.prefix] = {
  61. "last_check": current_time.strftime(SELFCHECK_DATE_FMT),
  62. "pypi_version": pypi_version,
  63. }
  64. with open(self.statefile_path, "w") as statefile:
  65. json.dump(state, statefile, sort_keys=True,
  66. separators=(",", ":"))
  67. def load_selfcheck_statefile():
  68. if running_under_virtualenv():
  69. return VirtualenvSelfCheckState()
  70. else:
  71. return GlobalSelfCheckState()
  72. def pip_version_check(session):
  73. """Check for an update for pip.
  74. Limit the frequency of checks to once per week. State is stored either in
  75. the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix
  76. of the pip script path.
  77. """
  78. import pip # imported here to prevent circular imports
  79. pypi_version = None
  80. try:
  81. state = load_selfcheck_statefile()
  82. current_time = datetime.datetime.utcnow()
  83. # Determine if we need to refresh the state
  84. if "last_check" in state.state and "pypi_version" in state.state:
  85. last_check = datetime.datetime.strptime(
  86. state.state["last_check"],
  87. SELFCHECK_DATE_FMT
  88. )
  89. if total_seconds(current_time - last_check) < 7 * 24 * 60 * 60:
  90. pypi_version = state.state["pypi_version"]
  91. # Refresh the version if we need to or just see if we need to warn
  92. if pypi_version is None:
  93. resp = session.get(
  94. PyPI.pip_json_url,
  95. headers={"Accept": "application/json"},
  96. )
  97. resp.raise_for_status()
  98. pypi_version = [
  99. v for v in sorted(
  100. list(resp.json()["releases"]),
  101. key=packaging_version.parse,
  102. )
  103. if not packaging_version.parse(v).is_prerelease
  104. ][-1]
  105. # save that we've performed a check
  106. state.save(pypi_version, current_time)
  107. pip_version = packaging_version.parse(pip.__version__)
  108. remote_version = packaging_version.parse(pypi_version)
  109. # Determine if our pypi_version is older
  110. if (pip_version < remote_version and
  111. pip_version.base_version != remote_version.base_version):
  112. # Advise "python -m pip" on Windows to avoid issues
  113. # with overwriting pip.exe.
  114. if WINDOWS:
  115. pip_cmd = "python -m pip"
  116. else:
  117. pip_cmd = "pip"
  118. logger.warning(
  119. "You are using pip version %s, however version %s is "
  120. "available.\nYou should consider upgrading via the "
  121. "'%s install --upgrade pip' command." % (pip.__version__,
  122. pypi_version,
  123. pip_cmd)
  124. )
  125. except Exception:
  126. logger.debug(
  127. "There was an error checking the latest version of pip",
  128. exc_info=True,
  129. )