Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Blacken src/pip/_internal/commands/ #10192

Merged
merged 6 commits into from
Aug 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ repos:
- id: black
exclude: |
(?x)
^src/pip/_internal/commands|
^src/pip/_internal/index|
^src/pip/_internal/models|
^src/pip/_internal/network|
Expand Down
163 changes: 89 additions & 74 deletions src/pip/_internal/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,87 +3,102 @@
"""

import importlib
from collections import OrderedDict, namedtuple
from collections import namedtuple
from typing import Any, Dict, Optional

from pip._internal.cli.base_command import Command

CommandInfo = namedtuple('CommandInfo', 'module_path, class_name, summary')
CommandInfo = namedtuple("CommandInfo", "module_path, class_name, summary")

# The ordering matters for help display.
# Also, even though the module path starts with the same
# "pip._internal.commands" prefix in each case, we include the full path
# because it makes testing easier (specifically when modifying commands_dict
# in test setup / teardown by adding info for a FakeCommand class defined
# in a test-related module).
# Finally, we need to pass an iterable of pairs here rather than a dict
# so that the ordering won't be lost when using Python 2.7.
commands_dict: Dict[str, CommandInfo] = OrderedDict([
('install', CommandInfo(
'pip._internal.commands.install', 'InstallCommand',
'Install packages.',
)),
('download', CommandInfo(
'pip._internal.commands.download', 'DownloadCommand',
'Download packages.',
)),
('uninstall', CommandInfo(
'pip._internal.commands.uninstall', 'UninstallCommand',
'Uninstall packages.',
)),
('freeze', CommandInfo(
'pip._internal.commands.freeze', 'FreezeCommand',
'Output installed packages in requirements format.',
)),
('list', CommandInfo(
'pip._internal.commands.list', 'ListCommand',
'List installed packages.',
)),
('show', CommandInfo(
'pip._internal.commands.show', 'ShowCommand',
'Show information about installed packages.',
)),
('check', CommandInfo(
'pip._internal.commands.check', 'CheckCommand',
'Verify installed packages have compatible dependencies.',
)),
('config', CommandInfo(
'pip._internal.commands.configuration', 'ConfigurationCommand',
'Manage local and global configuration.',
)),
('search', CommandInfo(
'pip._internal.commands.search', 'SearchCommand',
'Search PyPI for packages.',
)),
('cache', CommandInfo(
'pip._internal.commands.cache', 'CacheCommand',
# This dictionary does a bunch of heavy lifting for help output:
# - Enables avoiding additional (costly) imports for presenting `--help`.
# - The ordering matters for help display.
#
# Even though the module path starts with the same "pip._internal.commands"
# prefix, the full path makes testing easier (specifically when modifying
# `commands_dict` in test setup / teardown).
commands_dict: Dict[str, CommandInfo] = {
"install": CommandInfo(
"pip._internal.commands.install",
"InstallCommand",
"Install packages.",
),
"download": CommandInfo(
"pip._internal.commands.download",
"DownloadCommand",
"Download packages.",
),
"uninstall": CommandInfo(
"pip._internal.commands.uninstall",
"UninstallCommand",
"Uninstall packages.",
),
"freeze": CommandInfo(
"pip._internal.commands.freeze",
"FreezeCommand",
"Output installed packages in requirements format.",
),
"list": CommandInfo(
"pip._internal.commands.list",
"ListCommand",
"List installed packages.",
),
"show": CommandInfo(
"pip._internal.commands.show",
"ShowCommand",
"Show information about installed packages.",
),
"check": CommandInfo(
"pip._internal.commands.check",
"CheckCommand",
"Verify installed packages have compatible dependencies.",
),
"config": CommandInfo(
"pip._internal.commands.configuration",
"ConfigurationCommand",
"Manage local and global configuration.",
),
"search": CommandInfo(
"pip._internal.commands.search",
"SearchCommand",
"Search PyPI for packages.",
),
"cache": CommandInfo(
"pip._internal.commands.cache",
"CacheCommand",
"Inspect and manage pip's wheel cache.",
)),
('index', CommandInfo(
'pip._internal.commands.index', 'IndexCommand',
),
"index": CommandInfo(
"pip._internal.commands.index",
"IndexCommand",
"Inspect information available from package indexes.",
)),
('wheel', CommandInfo(
'pip._internal.commands.wheel', 'WheelCommand',
'Build wheels from your requirements.',
)),
('hash', CommandInfo(
'pip._internal.commands.hash', 'HashCommand',
'Compute hashes of package archives.',
)),
('completion', CommandInfo(
'pip._internal.commands.completion', 'CompletionCommand',
'A helper command used for command completion.',
)),
('debug', CommandInfo(
'pip._internal.commands.debug', 'DebugCommand',
'Show information useful for debugging.',
)),
('help', CommandInfo(
'pip._internal.commands.help', 'HelpCommand',
'Show help for commands.',
)),
])
),
"wheel": CommandInfo(
"pip._internal.commands.wheel",
"WheelCommand",
"Build wheels from your requirements.",
),
"hash": CommandInfo(
"pip._internal.commands.hash",
"HashCommand",
"Compute hashes of package archives.",
),
"completion": CommandInfo(
"pip._internal.commands.completion",
"CompletionCommand",
"A helper command used for command completion.",
),
"debug": CommandInfo(
"pip._internal.commands.debug",
"DebugCommand",
"Show information useful for debugging.",
),
"help": CommandInfo(
"pip._internal.commands.help",
"HelpCommand",
"Show help for commands.",
),
}


def create_command(name: str, **kwargs: Any) -> Command:
Expand Down
97 changes: 50 additions & 47 deletions src/pip/_internal/commands/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ class CacheCommand(Command):
def add_options(self) -> None:

self.cmd_opts.add_option(
'--format',
action='store',
dest='list_format',
"--format",
action="store",
dest="list_format",
default="human",
choices=('human', 'abspath'),
help="Select the output format among: human (default) or abspath"
choices=("human", "abspath"),
help="Select the output format among: human (default) or abspath",
)

self.parser.insert_option_group(0, self.cmd_opts)
Expand All @@ -59,8 +59,7 @@ def run(self, options: Values, args: List[Any]) -> int:
}

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

# Determine action
Expand All @@ -84,69 +83,73 @@ def run(self, options: Values, args: List[Any]) -> int:

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

logger.info(options.cache_dir)

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

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

http_cache_location = self._cache_dir(options, 'http')
wheels_cache_location = self._cache_dir(options, 'wheels')
http_cache_location = self._cache_dir(options, "http")
wheels_cache_location = self._cache_dir(options, "wheels")
http_cache_size = filesystem.format_directory_size(http_cache_location)
wheels_cache_size = filesystem.format_directory_size(
wheels_cache_location
wheels_cache_size = filesystem.format_directory_size(wheels_cache_location)

message = (
textwrap.dedent(
"""
Package index page cache location: {http_cache_location}
Package index page cache size: {http_cache_size}
Number of HTTP files: {num_http_files}
Wheels location: {wheels_cache_location}
Wheels size: {wheels_cache_size}
Number of wheels: {package_count}
"""
)
.format(
http_cache_location=http_cache_location,
http_cache_size=http_cache_size,
num_http_files=num_http_files,
wheels_cache_location=wheels_cache_location,
package_count=num_packages,
wheels_cache_size=wheels_cache_size,
)
.strip()
)

message = textwrap.dedent("""
Package index page cache location: {http_cache_location}
Package index page cache size: {http_cache_size}
Number of HTTP files: {num_http_files}
Wheels location: {wheels_cache_location}
Wheels size: {wheels_cache_size}
Number of wheels: {package_count}
""").format(
http_cache_location=http_cache_location,
http_cache_size=http_cache_size,
num_http_files=num_http_files,
wheels_cache_location=wheels_cache_location,
package_count=num_packages,
wheels_cache_size=wheels_cache_size,
).strip()

logger.info(message)

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

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

files = self._find_wheels(options, pattern)
if options.list_format == 'human':
if options.list_format == "human":
self.format_for_human(files)
else:
self.format_for_abspath(files)

def format_for_human(self, files: List[str]) -> None:
if not files:
logger.info('Nothing cached.')
logger.info("Nothing cached.")
return

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

def format_for_abspath(self, files: List[str]) -> None:
if not files:
Expand All @@ -156,23 +159,23 @@ def format_for_abspath(self, files: List[str]) -> None:
for filename in files:
results.append(filename)

logger.info('\n'.join(sorted(results)))
logger.info("\n".join(sorted(results)))

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

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

files = self._find_wheels(options, args[0])

# Only fetch http files if no specific pattern given
if args[0] == '*':
if args[0] == "*":
files += self._find_http_files(options)

if not files:
raise CommandError('No matching packages')
raise CommandError("No matching packages")

for filename in files:
os.unlink(filename)
Expand All @@ -181,19 +184,19 @@ def remove_cache_items(self, options: Values, args: List[Any]) -> None:

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

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

def _cache_dir(self, options: Values, subdir: str) -> str:
return os.path.join(options.cache_dir, subdir)

def _find_http_files(self, options: Values) -> List[str]:
http_dir = self._cache_dir(options, 'http')
return filesystem.find_files(http_dir, '*')
http_dir = self._cache_dir(options, "http")
return filesystem.find_files(http_dir, "*")

def _find_wheels(self, options: Values, pattern: str) -> List[str]:
wheel_dir = self._cache_dir(options, 'wheels')
wheel_dir = self._cache_dir(options, "wheels")

# The wheel filename format, as specified in PEP 427, is:
# {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl
Expand Down
10 changes: 8 additions & 2 deletions src/pip/_internal/commands/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,21 @@ def run(self, options: Values, args: List[Any]) -> int:
for dependency in missing[project_name]:
write_output(
"%s %s requires %s, which is not installed.",
project_name, version, dependency[0],
project_name,
version,
dependency[0],
)

for project_name in conflicting:
version = package_set[project_name].version
for dep_name, dep_version, req in conflicting[project_name]:
write_output(
"%s %s has requirement %s, but you have %s %s.",
project_name, version, req, dep_name, dep_version,
project_name,
version,
req,
dep_name,
dep_version,
)

if missing or conflicting or parsing_probs:
Expand Down
Loading