from __future__ import absolute_import

import logging
import os
import textwrap

import pip._internal.utils.filesystem as filesystem
from pip._internal.cli.base_command import Command
from pip._internal.cli.status_codes import ERROR, SUCCESS
from pip._internal.exceptions import CommandError, PipError
from pip._internal.utils.typing import MYPY_CHECK_RUNNING

if MYPY_CHECK_RUNNING:
    from optparse import Values
    from typing import Any, List


logger = logging.getLogger(__name__)


class CacheCommand(Command):
    """
    Inspect and manage pip's wheel cache.

    Subcommands:

        info: Show information about the cache.
        list: List filenames of packages stored in the cache.
        remove: Remove one or more package from the cache.
        purge: Remove all items from the cache.

        <pattern> can be a glob expression or a package name.
    """

    usage = """
        %prog info
        %prog list [<pattern>]
        %prog remove <pattern>
        %prog purge
    """

    def run(self, options, args):
        # type: (Values, List[Any]) -> int
        handlers = {
            "info": self.get_cache_info,
            "list": self.list_cache_items,
            "remove": self.remove_cache_items,
            "purge": self.purge_cache,
        }

        # Determine action
        if not args or args[0] not in handlers:
            logger.error("Need an action ({}) to perform.".format(
                ", ".join(sorted(handlers)))
            )
            return ERROR

        action = args[0]

        # Error handling happens here, not in the action-handlers.
        try:
            handlers[action](options, args[1:])
        except PipError as e:
            logger.error(e.args[0])
            return ERROR

        return SUCCESS

    def get_cache_info(self, options, args):
        # type: (Values, List[Any]) -> None
        if args:
            raise CommandError('Too many arguments')

        num_packages = len(self._find_wheels(options, '*'))

        cache_location = self._wheels_cache_dir(options)
        cache_size = filesystem.format_directory_size(cache_location)

        message = textwrap.dedent("""
            Location: {location}
            Size: {size}
            Number of wheels: {package_count}
        """).format(
            location=cache_location,
            package_count=num_packages,
            size=cache_size,
        ).strip()

        logger.info(message)

    def list_cache_items(self, options, args):
        # type: (Values, List[Any]) -> None
        if len(args) > 1:
            raise CommandError('Too many arguments')

        if args:
            pattern = args[0]
        else:
            pattern = '*'

        files = self._find_wheels(options, pattern)

        if not files:
            logger.info('Nothing cached.')
            return

        results = []
        for filename in files:
            wheel = os.path.basename(filename)
            size = filesystem.format_file_size(filename)
            results.append(' - {} ({})'.format(wheel, size))
        logger.info('Cache contents:\n')
        logger.info('\n'.join(sorted(results)))

    def remove_cache_items(self, options, args):
        # type: (Values, List[Any]) -> None
        if len(args) > 1:
            raise CommandError('Too many arguments')

        if not args:
            raise CommandError('Please provide a pattern')

        files = self._find_wheels(options, args[0])
        if not files:
            raise CommandError('No matching packages')

        for filename in files:
            os.unlink(filename)
            logger.debug('Removed %s', filename)
        logger.info('Files removed: %s', len(files))

    def purge_cache(self, options, args):
        # type: (Values, List[Any]) -> None
        if args:
            raise CommandError('Too many arguments')

        return self.remove_cache_items(options, ['*'])

    def _wheels_cache_dir(self, options):
        # type: (Values) -> str
        return os.path.join(options.cache_dir, 'wheels')

    def _find_wheels(self, options, pattern):
        # type: (Values, str) -> List[str]
        wheel_dir = self._wheels_cache_dir(options)

        # The wheel filename format, as specified in PEP 427, is:
        #     {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl
        #
        # Additionally, non-alphanumeric values in the distribution are
        # normalized to underscores (_), meaning hyphens can never occur
        # before `-{version}`.
        #
        # Given that information:
        # - If the pattern we're given contains a hyphen (-), the user is
        #   providing at least the version. Thus, we can just append `*.whl`
        #   to match the rest of it.
        # - If the pattern we're given doesn't contain a hyphen (-), the
        #   user is only providing the name. Thus, we append `-*.whl` to
        #   match the hyphen before the version, followed by anything else.
        #
        # PEP 427: https://www.python.org/dev/peps/pep-0427/
        pattern = pattern + ("*.whl" if "-" in pattern else "-*.whl")

        return filesystem.find_files(wheel_dir, pattern)

src/pip/_internal/commands/cache.py
from __future__ import absolute_import

import logging
import os
import textwrap

import pip._internal.utils.filesystem as filesystem
from pip._internal.cli.base_command import Command
from pip._internal.cli.status_codes import ERROR, SUCCESS
from pip._internal.exceptions import CommandError, PipError
from pip._internal.utils.typing import MYPY_CHECK_RUNNING

if MYPY_CHECK_RUNNING:
    from optparse import Values
    from typing import Any, List


logger = logging.getLogger(__name__)


class CacheCommand(Command):
    """
    Inspect and manage pip's wheel cache.

    Subcommands:

        info: Show information about the cache.
        list: List filenames of packages stored in the cache.
        remove: Remove one or more package from the cache.
        purge: Remove all items from the cache.

        <pattern> can be a glob expression or a package name.
    """

    usage = """
        %prog info
        %prog list [<pattern>]
        %prog remove <pattern>
        %prog purge
    """

    def run(self, options, args):
        # type: (Values, List[Any]) -> int
        handlers = {
            "info": self.get_cache_info,
            "list": self.list_cache_items,
            "remove": self.remove_cache_items,
            "purge": self.purge_cache,
        }

        if not options.cache_dir:
            logger.error("pip cache commands can not "
                         "function since cache is disabled.")
            return ERROR

        # Determine action
        if not args or args[0] not in handlers:
            logger.error("Need an action ({}) to perform.".format(
                ", ".join(sorted(handlers)))
            )
            return ERROR

        action = args[0]

        # Error handling happens here, not in the action-handlers.
        try:
            handlers[action](options, args[1:])
        except PipError as e:
            logger.error(e.args[0])
            return ERROR

        return SUCCESS

    def get_cache_info(self, options, args):
        # type: (Values, List[Any]) -> None
        if args:
            raise CommandError('Too many arguments')

        num_packages = len(self._find_wheels(options, '*'))

        cache_location = self._wheels_cache_dir(options)
        cache_size = filesystem.format_directory_size(cache_location)

        message = textwrap.dedent("""
            Location: {location}
            Size: {size}
            Number of wheels: {package_count}
        """).format(
            location=cache_location,
            package_count=num_packages,
            size=cache_size,
        ).strip()

        logger.info(message)

    def list_cache_items(self, options, args):
        # type: (Values, List[Any]) -> None
        if len(args) > 1:
            raise CommandError('Too many arguments')

        if args:
            pattern = args[0]
        else:
            pattern = '*'

        files = self._find_wheels(options, pattern)

        if not files:
            logger.info('Nothing cached.')
            return

        results = []
        for filename in files:
            wheel = os.path.basename(filename)
            size = filesystem.format_file_size(filename)
            results.append(' - {} ({})'.format(wheel, size))
        logger.info('Cache contents:\n')
        logger.info('\n'.join(sorted(results)))

    def remove_cache_items(self, options, args):
        # type: (Values, List[Any]) -> None
        if len(args) > 1:
            raise CommandError('Too many arguments')

        if not args:
            raise CommandError('Please provide a pattern')

        files = self._find_wheels(options, args[0])
        if not files:
            raise CommandError('No matching packages')

        for filename in files:
            os.unlink(filename)
            logger.debug('Removed %s', filename)
        logger.info('Files removed: %s', len(files))

    def purge_cache(self, options, args):
        # type: (Values, List[Any]) -> None
        if args:
            raise CommandError('Too many arguments')

        return self.remove_cache_items(options, ['*'])

    def _wheels_cache_dir(self, options):
        # type: (Values) -> str
        return os.path.join(options.cache_dir, 'wheels')

    def _find_wheels(self, options, pattern):
        # type: (Values, str) -> List[str]
        wheel_dir = self._wheels_cache_dir(options)

        # The wheel filename format, as specified in PEP 427, is:
        #     {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl
        #
        # Additionally, non-alphanumeric values in the distribution are
        # normalized to underscores (_), meaning hyphens can never occur
        # before `-{version}`.
        #
        # Given that information:
        # - If the pattern we're given contains a hyphen (-), the user is
        #   providing at least the version. Thus, we can just append `*.whl`
        #   to match the rest of it.
        # - If the pattern we're given doesn't contain a hyphen (-), the
        #   user is only providing the name. Thus, we append `-*.whl` to
        #   match the hyphen before the version, followed by anything else.
        #
        # PEP 427: https://www.python.org/dev/peps/pep-0427/
        pattern = pattern + ("*.whl" if "-" in pattern else "-*.whl")

        return filesystem.find_files(wheel_dir, pattern)

src/pip/_internal/commands/cache.py
diff --git a/news/8124.bugfix b/news/8124.bugfix
new file mode 100644
index 00000000000..a859381e0d8
--- /dev/null
+++ b/news/8124.bugfix
@@ -0,0 +1 @@
+Abort pip cache commands early when cache is disabled.
diff --git a/src/pip/_internal/commands/cache.py b/src/pip/_internal/commands/cache.py
index 7e3f72e080b..3c345dfa0d1 100644
--- a/src/pip/_internal/commands/cache.py
+++ b/src/pip/_internal/commands/cache.py
@@ -48,6 +48,11 @@ def run(self, options, args):
             "purge": self.purge_cache,
         }
 
+        if not options.cache_dir:
+            logger.error("pip cache commands can not "
+                         "function since cache is disabled.")
+            return ERROR
+
         # Determine action
         if not args or args[0] not in handlers:
             logger.error("Need an action ({}) to perform.".format(
diff --git a/tests/functional/test_cache.py b/tests/functional/test_cache.py
index a464ece7945..7fec4dd56c4 100644
--- a/tests/functional/test_cache.py
+++ b/tests/functional/test_cache.py
@@ -216,3 +216,15 @@ def test_cache_purge_too_many_args(script, wheel_cache_files):
     # Make sure nothing was deleted.
     for filename in wheel_cache_files:
         assert os.path.exists(filename)
+
+
+@pytest.mark.parametrize("command", ["info", "list", "remove", "purge"])
+def test_cache_abort_when_no_cache_dir(script, command):
+    """Running any pip cache command when cache is disabled should
+    abort and log an informative error"""
+    result = script.pip('cache', command, '--no-cache-dir',
+                        expect_error=True)
+    assert result.stdout == ''
+
+    assert ('ERROR: pip cache commands can not function'
+            ' since cache is disabled.' in result.stderr.splitlines())

'pip cache info' fails when no-cache-dir set
pip version: pip 20.1b1
Python version: CPython 3.8.1
OS: Win 10 64

Testing 20.1 beta, execute 'pip cache info' and crashes.  I'm guessing it's due to pip.ini turning off caching.

pip.ini:
```
[global]
no-cache-dir = false
```

Command execution:
```
> pip cache info
ERROR: Exception:
Traceback (most recent call last):
  File "c:\program files\python38\lib\site-packages\pip\_internal\cli\base_command.py", line 188, in _main
    status = self.run(options, args)
  File "c:\program files\python38\lib\site-packages\pip\_internal\commands\cache.py", line 62, in run
    handlers[action](options, args[1:])
  File "c:\program files\python38\lib\site-packages\pip\_internal\commands\cache.py", line 74, in get_cache_info
    num_packages = len(self._find_wheels(options, '*'))
  File "c:\program files\python38\lib\site-packages\pip\_internal\commands\cache.py", line 145, in _find_wheels
    wheel_dir = self._wheels_cache_dir(options)
  File "c:\program files\python38\lib\site-packages\pip\_internal\commands\cache.py", line 141, in _wheels_cache_dir
    return os.path.join(options.cache_dir, 'wheels')
  File "c:\program files\python38\lib\ntpath.py", line 78, in join
    path = os.fspath(path)
TypeError: expected str, bytes or os.PathLike object, not bool
```

