prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  pip version check file doesn't honor cache-dir
  - Pip version: 7.1.0
  - Python version: 2.7.6
  - Operating System: Fedora 22
  
  My pip config looks like:
  
  ```
  [dev@machine ~] $ cat ~/.config/pip/pip.conf 
  [global]
  cache-dir=/ssd/dev/.pip/cache
  ```
  
  Whenever I try to install any package, it caches the wheels in the `cache-dir` as specified above. However, the pip-version check is performed and the file `selfcheck.json` and it's lock file is placed in the directory: `$HOME/.cache/pip/` , which should have been inside the `cache-dir` as specified above.
  
  I get around this problem by specifying the following in the pip config (but it's not a very good solution):
  
  ```
  disable-pip-version-check=true
  ```
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `src/pip/_internal/utils/outdated.py`
  Content:
  ```
  1 from __future__ import absolute_import
  2 
  3 import datetime
  4 import json
  5 import logging
  6 import os.path
  7 import sys
  8 
  9 from pip._vendor import lockfile
  10 from pip._vendor.packaging import version as packaging_version
  11 
  12 from pip._internal.compat import WINDOWS
  13 from pip._internal.index import PackageFinder
  14 from pip._internal.locations import USER_CACHE_DIR, running_under_virtualenv
  15 from pip._internal.utils.filesystem import check_path_owner
  16 from pip._internal.utils.misc import ensure_dir, get_installed_version
  17 
  18 SELFCHECK_DATE_FMT = "%Y-%m-%dT%H:%M:%SZ"
  19 
  20 
  21 logger = logging.getLogger(__name__)
  22 
  23 
  24 class VirtualenvSelfCheckState(object):
  25     def __init__(self):
  26         self.statefile_path = os.path.join(sys.prefix, "pip-selfcheck.json")
  27 
  28         # Load the existing state
  29         try:
  30             with open(self.statefile_path) as statefile:
  31                 self.state = json.load(statefile)
  32         except (IOError, ValueError):
  33             self.state = {}
  34 
  35     def save(self, pypi_version, current_time):
  36         # Attempt to write out our version check file
  37         with open(self.statefile_path, "w") as statefile:
  38             json.dump(
  39                 {
  40                     "last_check": current_time.strftime(SELFCHECK_DATE_FMT),
  41                     "pypi_version": pypi_version,
  42                 },
  43                 statefile,
  44                 sort_keys=True,
  45                 separators=(",", ":")
  46             )
  47 
  48 
  49 class GlobalSelfCheckState(object):
  50     def __init__(self):
  51         self.statefile_path = os.path.join(USER_CACHE_DIR, "selfcheck.json")
  52 
  53         # Load the existing state
  54         try:
  55             with open(self.statefile_path) as statefile:
  56                 self.state = json.load(statefile)[sys.prefix]
  57         except (IOError, ValueError, KeyError):
  58             self.state = {}
  59 
  60     def save(self, pypi_version, current_time):
  61         # Check to make sure that we own the directory
  62         if not check_path_owner(os.path.dirname(self.statefile_path)):
  63             return
  64 
  65         # Now that we've ensured the directory is owned by this user, we'll go
  66         # ahead and make sure that all our directories are created.
  67         ensure_dir(os.path.dirname(self.statefile_path))
  68 
  69         # Attempt to write out our version check file
  70         with lockfile.LockFile(self.statefile_path):
  71             if os.path.exists(self.statefile_path):
  72                 with open(self.statefile_path) as statefile:
  73                     state = json.load(statefile)
  74             else:
  75                 state = {}
  76 
  77             state[sys.prefix] = {
  78                 "last_check": current_time.strftime(SELFCHECK_DATE_FMT),
  79                 "pypi_version": pypi_version,
  80             }
  81 
  82             with open(self.statefile_path, "w") as statefile:
  83                 json.dump(state, statefile, sort_keys=True,
  84                           separators=(",", ":"))
  85 
  86 
  87 def load_selfcheck_statefile():
  88     if running_under_virtualenv():
  89         return VirtualenvSelfCheckState()
  90     else:
  91         return GlobalSelfCheckState()
  92 
  93 
  94 def pip_version_check(session, options):
  95     """Check for an update for pip.
  96 
  97     Limit the frequency of checks to once per week. State is stored either in
  98     the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix
  99     of the pip script path.
  100     """
  101     installed_version = get_installed_version("pip")
  102     if not installed_version:
  103         return
  104 
  105     pip_version = packaging_version.parse(installed_version)
  106     pypi_version = None
  107 
  108     try:
  109         state = load_selfcheck_statefile()
  110 
  111         current_time = datetime.datetime.utcnow()
  112         # Determine if we need to refresh the state
  113         if "last_check" in state.state and "pypi_version" in state.state:
  114             last_check = datetime.datetime.strptime(
  115                 state.state["last_check"],
  116                 SELFCHECK_DATE_FMT
  117             )
  118             if (current_time - last_check).total_seconds() < 7 * 24 * 60 * 60:
  119                 pypi_version = state.state["pypi_version"]
  120 
  121         # Refresh the version if we need to or just see if we need to warn
  122         if pypi_version is None:
  123             # Lets use PackageFinder to see what the latest pip version is
  124             finder = PackageFinder(
  125                 find_links=options.find_links,
  126                 index_urls=[options.index_url] + options.extra_index_urls,
  127                 allow_all_prereleases=False,  # Explicitly set to False
  128                 trusted_hosts=options.trusted_hosts,
  129                 process_dependency_links=options.process_dependency_links,
  130                 session=session,
  131             )
  132             all_candidates = finder.find_all_candidates("pip")
  133             if not all_candidates:
  134                 return
  135             pypi_version = str(
  136                 max(all_candidates, key=lambda c: c.version).version
  137             )
  138 
  139             # save that we've performed a check
  140             state.save(pypi_version, current_time)
  141 
  142         remote_version = packaging_version.parse(pypi_version)
  143 
  144         # Determine if our pypi_version is older
  145         if (pip_version < remote_version and
  146                 pip_version.base_version != remote_version.base_version):
  147             # Advise "python -m pip" on Windows to avoid issues
  148             # with overwriting pip.exe.
  149             if WINDOWS:
  150                 pip_cmd = "python -m pip"
  151             else:
  152                 pip_cmd = "pip"
  153             logger.warning(
  154                 "You are using pip version %s, however version %s is "
  155                 "available.\nYou should consider upgrading via the "
  156                 "'%s install --upgrade pip' command.",
  157                 pip_version, pypi_version, pip_cmd
  158             )
  159     except Exception:
  160         logger.debug(
  161             "There was an error checking the latest version of pip",
  162             exc_info=True,
  163         )
  164
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/src/pip/_internal/utils/outdated.py b/src/pip/_internal/utils/outdated.py
  --- a/src/pip/_internal/utils/outdated.py
  +++ b/src/pip/_internal/utils/outdated.py
  @@ -11,7 +11,6 @@
   
   from pip._internal.compat import WINDOWS
   from pip._internal.index import PackageFinder
  -from pip._internal.locations import USER_CACHE_DIR, running_under_virtualenv
   from pip._internal.utils.filesystem import check_path_owner
   from pip._internal.utils.misc import ensure_dir, get_installed_version
   
  @@ -21,34 +20,9 @@
   logger = logging.getLogger(__name__)
   
   
  -class VirtualenvSelfCheckState(object):
  -    def __init__(self):
  -        self.statefile_path = os.path.join(sys.prefix, "pip-selfcheck.json")
  -
  -        # Load the existing state
  -        try:
  -            with open(self.statefile_path) as statefile:
  -                self.state = json.load(statefile)
  -        except (IOError, ValueError):
  -            self.state = {}
  -
  -    def save(self, pypi_version, current_time):
  -        # Attempt to write out our version check file
  -        with open(self.statefile_path, "w") as statefile:
  -            json.dump(
  -                {
  -                    "last_check": current_time.strftime(SELFCHECK_DATE_FMT),
  -                    "pypi_version": pypi_version,
  -                },
  -                statefile,
  -                sort_keys=True,
  -                separators=(",", ":")
  -            )
  -
  -
  -class GlobalSelfCheckState(object):
  -    def __init__(self):
  -        self.statefile_path = os.path.join(USER_CACHE_DIR, "selfcheck.json")
  +class SelfCheckState(object):
  +    def __init__(self, cache_dir):
  +        self.statefile_path = os.path.join(cache_dir, "selfcheck.json")
   
           # Load the existing state
           try:
  @@ -84,13 +58,6 @@
                             separators=(",", ":"))
   
   
  -def load_selfcheck_statefile():
  -    if running_under_virtualenv():
  -        return VirtualenvSelfCheckState()
  -    else:
  -        return GlobalSelfCheckState()
  -
  -
   def pip_version_check(session, options):
       """Check for an update for pip.
   
  @@ -106,7 +73,7 @@
       pypi_version = None
   
       try:
  -        state = load_selfcheck_statefile()
  +        state = SelfCheckState(cache_dir=options.cache_dir)
   
           current_time = datetime.datetime.utcnow()
           # Determine if we need to refresh the state
  
verification_info: {"golden_diff": "diff --git a/src/pip/_internal/utils/outdated.py b/src/pip/_internal/utils/outdated.py\n--- a/src/pip/_internal/utils/outdated.py\n+++ b/src/pip/_internal/utils/outdated.py\n@@ -11,7 +11,6 @@\n \n from pip._internal.compat import WINDOWS\n from pip._internal.index import PackageFinder\n-from pip._internal.locations import USER_CACHE_DIR, running_under_virtualenv\n from pip._internal.utils.filesystem import check_path_owner\n from pip._internal.utils.misc import ensure_dir, get_installed_version\n \n@@ -21,34 +20,9 @@\n logger = logging.getLogger(__name__)\n \n \n-class VirtualenvSelfCheckState(object):\n-    def __init__(self):\n-        self.statefile_path = os.path.join(sys.prefix, \"pip-selfcheck.json\")\n-\n-        # Load the existing state\n-        try:\n-            with open(self.statefile_path) as statefile:\n-                self.state = json.load(statefile)\n-        except (IOError, ValueError):\n-            self.state = {}\n-\n-    def save(self, pypi_version, current_time):\n-        # Attempt to write out our version check file\n-        with open(self.statefile_path, \"w\") as statefile:\n-            json.dump(\n-                {\n-                    \"last_check\": current_time.strftime(SELFCHECK_DATE_FMT),\n-                    \"pypi_version\": pypi_version,\n-                },\n-                statefile,\n-                sort_keys=True,\n-                separators=(\",\", \":\")\n-            )\n-\n-\n-class GlobalSelfCheckState(object):\n-    def __init__(self):\n-        self.statefile_path = os.path.join(USER_CACHE_DIR, \"selfcheck.json\")\n+class SelfCheckState(object):\n+    def __init__(self, cache_dir):\n+        self.statefile_path = os.path.join(cache_dir, \"selfcheck.json\")\n \n         # Load the existing state\n         try:\n@@ -84,13 +58,6 @@\n                           separators=(\",\", \":\"))\n \n \n-def load_selfcheck_statefile():\n-    if running_under_virtualenv():\n-        return VirtualenvSelfCheckState()\n-    else:\n-        return GlobalSelfCheckState()\n-\n-\n def pip_version_check(session, options):\n     \"\"\"Check for an update for pip.\n \n@@ -106,7 +73,7 @@\n     pypi_version = None\n \n     try:\n-        state = load_selfcheck_statefile()\n+        state = SelfCheckState(cache_dir=options.cache_dir)\n \n         current_time = datetime.datetime.utcnow()\n         # Determine if we need to refresh the state\n", "issue": "pip version check file doesn't honor cache-dir\n- Pip version: 7.1.0\n- Python version: 2.7.6\n- Operating System: Fedora 22\n\nMy pip config looks like:\n\n```\n[dev@machine ~] $ cat ~/.config/pip/pip.conf \n[global]\ncache-dir=/ssd/dev/.pip/cache\n```\n\nWhenever I try to install any package, it caches the wheels in the `cache-dir` as specified above. However, the pip-version check is performed and the file `selfcheck.json` and it's lock file is placed in the directory: `$HOME/.cache/pip/` , which should have been inside the `cache-dir` as specified above.\n\nI get around this problem by specifying the following in the pip config (but it's not a very good solution):\n\n```\ndisable-pip-version-check=true\n```\n\n", "before_files": [{"content": "from __future__ import absolute_import\n\nimport datetime\nimport json\nimport logging\nimport os.path\nimport sys\n\nfrom pip._vendor import lockfile\nfrom pip._vendor.packaging import version as packaging_version\n\nfrom pip._internal.compat import WINDOWS\nfrom pip._internal.index import PackageFinder\nfrom pip._internal.locations import USER_CACHE_DIR, running_under_virtualenv\nfrom pip._internal.utils.filesystem import check_path_owner\nfrom pip._internal.utils.misc import ensure_dir, get_installed_version\n\nSELFCHECK_DATE_FMT = \"%Y-%m-%dT%H:%M:%SZ\"\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass VirtualenvSelfCheckState(object):\n    def __init__(self):\n        self.statefile_path = os.path.join(sys.prefix, \"pip-selfcheck.json\")\n\n        # Load the existing state\n        try:\n            with open(self.statefile_path) as statefile:\n                self.state = json.load(statefile)\n        except (IOError, ValueError):\n            self.state = {}\n\n    def save(self, pypi_version, current_time):\n        # Attempt to write out our version check file\n        with open(self.statefile_path, \"w\") as statefile:\n            json.dump(\n                {\n                    \"last_check\": current_time.strftime(SELFCHECK_DATE_FMT),\n                    \"pypi_version\": pypi_version,\n                },\n                statefile,\n                sort_keys=True,\n                separators=(\",\", \":\")\n            )\n\n\nclass GlobalSelfCheckState(object):\n    def __init__(self):\n        self.statefile_path = os.path.join(USER_CACHE_DIR, \"selfcheck.json\")\n\n        # Load the existing state\n        try:\n            with open(self.statefile_path) as statefile:\n                self.state = json.load(statefile)[sys.prefix]\n        except (IOError, ValueError, KeyError):\n            self.state = {}\n\n    def save(self, pypi_version, current_time):\n        # Check to make sure that we own the directory\n        if not check_path_owner(os.path.dirname(self.statefile_path)):\n            return\n\n        # Now that we've ensured the directory is owned by this user, we'll go\n        # ahead and make sure that all our directories are created.\n        ensure_dir(os.path.dirname(self.statefile_path))\n\n        # Attempt to write out our version check file\n        with lockfile.LockFile(self.statefile_path):\n            if os.path.exists(self.statefile_path):\n                with open(self.statefile_path) as statefile:\n                    state = json.load(statefile)\n            else:\n                state = {}\n\n            state[sys.prefix] = {\n                \"last_check\": current_time.strftime(SELFCHECK_DATE_FMT),\n                \"pypi_version\": pypi_version,\n            }\n\n            with open(self.statefile_path, \"w\") as statefile:\n                json.dump(state, statefile, sort_keys=True,\n                          separators=(\",\", \":\"))\n\n\ndef load_selfcheck_statefile():\n    if running_under_virtualenv():\n        return VirtualenvSelfCheckState()\n    else:\n        return GlobalSelfCheckState()\n\n\ndef pip_version_check(session, options):\n    \"\"\"Check for an update for pip.\n\n    Limit the frequency of checks to once per week. State is stored either in\n    the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix\n    of the pip script path.\n    \"\"\"\n    installed_version = get_installed_version(\"pip\")\n    if not installed_version:\n        return\n\n    pip_version = packaging_version.parse(installed_version)\n    pypi_version = None\n\n    try:\n        state = load_selfcheck_statefile()\n\n        current_time = datetime.datetime.utcnow()\n        # Determine if we need to refresh the state\n        if \"last_check\" in state.state and \"pypi_version\" in state.state:\n            last_check = datetime.datetime.strptime(\n                state.state[\"last_check\"],\n                SELFCHECK_DATE_FMT\n            )\n            if (current_time - last_check).total_seconds() < 7 * 24 * 60 * 60:\n                pypi_version = state.state[\"pypi_version\"]\n\n        # Refresh the version if we need to or just see if we need to warn\n        if pypi_version is None:\n            # Lets use PackageFinder to see what the latest pip version is\n            finder = PackageFinder(\n                find_links=options.find_links,\n                index_urls=[options.index_url] + options.extra_index_urls,\n                allow_all_prereleases=False,  # Explicitly set to False\n                trusted_hosts=options.trusted_hosts,\n                process_dependency_links=options.process_dependency_links,\n                session=session,\n            )\n            all_candidates = finder.find_all_candidates(\"pip\")\n            if not all_candidates:\n                return\n            pypi_version = str(\n                max(all_candidates, key=lambda c: c.version).version\n            )\n\n            # save that we've performed a check\n            state.save(pypi_version, current_time)\n\n        remote_version = packaging_version.parse(pypi_version)\n\n        # Determine if our pypi_version is older\n        if (pip_version < remote_version and\n                pip_version.base_version != remote_version.base_version):\n            # Advise \"python -m pip\" on Windows to avoid issues\n            # with overwriting pip.exe.\n            if WINDOWS:\n                pip_cmd = \"python -m pip\"\n            else:\n                pip_cmd = \"pip\"\n            logger.warning(\n                \"You are using pip version %s, however version %s is \"\n                \"available.\\nYou should consider upgrading via the \"\n                \"'%s install --upgrade pip' command.\",\n                pip_version, pypi_version, pip_cmd\n            )\n    except Exception:\n        logger.debug(\n            \"There was an error checking the latest version of pip\",\n            exc_info=True,\n        )\n", "path": "src/pip/_internal/utils/outdated.py"}], "after_files": [{"content": "from __future__ import absolute_import\n\nimport datetime\nimport json\nimport logging\nimport os.path\nimport sys\n\nfrom pip._vendor import lockfile\nfrom pip._vendor.packaging import version as packaging_version\n\nfrom pip._internal.compat import WINDOWS\nfrom pip._internal.index import PackageFinder\nfrom pip._internal.utils.filesystem import check_path_owner\nfrom pip._internal.utils.misc import ensure_dir, get_installed_version\n\nSELFCHECK_DATE_FMT = \"%Y-%m-%dT%H:%M:%SZ\"\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass SelfCheckState(object):\n    def __init__(self, cache_dir):\n        self.statefile_path = os.path.join(cache_dir, \"selfcheck.json\")\n\n        # Load the existing state\n        try:\n            with open(self.statefile_path) as statefile:\n                self.state = json.load(statefile)[sys.prefix]\n        except (IOError, ValueError, KeyError):\n            self.state = {}\n\n    def save(self, pypi_version, current_time):\n        # Check to make sure that we own the directory\n        if not check_path_owner(os.path.dirname(self.statefile_path)):\n            return\n\n        # Now that we've ensured the directory is owned by this user, we'll go\n        # ahead and make sure that all our directories are created.\n        ensure_dir(os.path.dirname(self.statefile_path))\n\n        # Attempt to write out our version check file\n        with lockfile.LockFile(self.statefile_path):\n            if os.path.exists(self.statefile_path):\n                with open(self.statefile_path) as statefile:\n                    state = json.load(statefile)\n            else:\n                state = {}\n\n            state[sys.prefix] = {\n                \"last_check\": current_time.strftime(SELFCHECK_DATE_FMT),\n                \"pypi_version\": pypi_version,\n            }\n\n            with open(self.statefile_path, \"w\") as statefile:\n                json.dump(state, statefile, sort_keys=True,\n                          separators=(\",\", \":\"))\n\n\ndef pip_version_check(session, options):\n    \"\"\"Check for an update for pip.\n\n    Limit the frequency of checks to once per week. State is stored either in\n    the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix\n    of the pip script path.\n    \"\"\"\n    installed_version = get_installed_version(\"pip\")\n    if not installed_version:\n        return\n\n    pip_version = packaging_version.parse(installed_version)\n    pypi_version = None\n\n    try:\n        state = SelfCheckState(cache_dir=options.cache_dir)\n\n        current_time = datetime.datetime.utcnow()\n        # Determine if we need to refresh the state\n        if \"last_check\" in state.state and \"pypi_version\" in state.state:\n            last_check = datetime.datetime.strptime(\n                state.state[\"last_check\"],\n                SELFCHECK_DATE_FMT\n            )\n            if (current_time - last_check).total_seconds() < 7 * 24 * 60 * 60:\n                pypi_version = state.state[\"pypi_version\"]\n\n        # Refresh the version if we need to or just see if we need to warn\n        if pypi_version is None:\n            # Lets use PackageFinder to see what the latest pip version is\n            finder = PackageFinder(\n                find_links=options.find_links,\n                index_urls=[options.index_url] + options.extra_index_urls,\n                allow_all_prereleases=False,  # Explicitly set to False\n                trusted_hosts=options.trusted_hosts,\n                process_dependency_links=options.process_dependency_links,\n                session=session,\n            )\n            all_candidates = finder.find_all_candidates(\"pip\")\n            if not all_candidates:\n                return\n            pypi_version = str(\n                max(all_candidates, key=lambda c: c.version).version\n            )\n\n            # save that we've performed a check\n            state.save(pypi_version, current_time)\n\n        remote_version = packaging_version.parse(pypi_version)\n\n        # Determine if our pypi_version is older\n        if (pip_version < remote_version and\n                pip_version.base_version != remote_version.base_version):\n            # Advise \"python -m pip\" on Windows to avoid issues\n            # with overwriting pip.exe.\n            if WINDOWS:\n                pip_cmd = \"python -m pip\"\n            else:\n                pip_cmd = \"pip\"\n            logger.warning(\n                \"You are using pip version %s, however version %s is \"\n                \"available.\\nYou should consider upgrading via the \"\n                \"'%s install --upgrade pip' command.\",\n                pip_version, pypi_version, pip_cmd\n            )\n    except Exception:\n        logger.debug(\n            \"There was an error checking the latest version of pip\",\n            exc_info=True,\n        )\n", "path": "src/pip/_internal/utils/outdated.py"}]}