1
1
Fork 0
mirror of https://github.com/pypa/pip synced 2023-12-13 21:30:23 +01:00

Ruff rules C4,C90,PERF

This commit is contained in:
Christian Clauss 2023-08-26 10:20:40 +02:00
parent a3378162f8
commit 69a1e956da
22 changed files with 93 additions and 100 deletions

View file

@ -23,7 +23,7 @@ repos:
- repo: https://github.com/astral-sh/ruff-pre-commit - repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version. # Ruff version.
rev: v0.0.270 rev: v0.0.286
hooks: hooks:
- id: ruff - id: ruff

View file

@ -0,0 +1 @@
Add ruff rules ASYNC,C4,C90,PERF,PLE,PLR for minor optimizations and to set upper limits on code complexity.

View file

@ -74,9 +74,9 @@ webencodings = "https://github.com/SimonSapin/python-webencodings/raw/master/LIC
[tool.ruff] [tool.ruff]
extend-exclude = [ extend-exclude = [
"_vendor",
"./build", "./build",
".scratch", ".scratch",
"_vendor",
"data", "data",
] ]
ignore = [ ignore = [
@ -88,21 +88,37 @@ ignore = [
] ]
line-length = 88 line-length = 88
select = [ select = [
"ASYNC",
"B", "B",
"C4",
"C90",
"E", "E",
"F", "F",
"W",
"G", "G",
"ISC",
"I", "I",
"ISC",
"PERF",
"PLE",
"PLR0",
"W",
] ]
[tool.ruff.per-file-ignores]
"noxfile.py" = ["G"]
"tests/*" = ["B011"]
[tool.ruff.isort] [tool.ruff.isort]
# We need to explicitly make pip "first party" as it's imported by code in # We need to explicitly make pip "first party" as it's imported by code in
# the docs and tests directories. # the docs and tests directories.
known-first-party = ["pip"] known-first-party = ["pip"]
known-third-party = ["pip._vendor"] known-third-party = ["pip._vendor"]
[tool.ruff.mccabe]
max-complexity = 33 # default is 10
[tool.ruff.per-file-ignores]
"noxfile.py" = ["G"]
"src/pip/_internal/*" = ["PERF203"]
"tests/*" = ["B011"]
[tool.ruff.pylint]
max-args = 15 # default is 5
max-branches = 28 # default is 12
max-returns = 13 # default is 6
max-statements = 134 # default is 50

View file

@ -78,12 +78,10 @@ class Cache:
if can_not_cache: if can_not_cache:
return [] return []
candidates = []
path = self.get_path_for_link(link) path = self.get_path_for_link(link)
if os.path.isdir(path): if os.path.isdir(path):
for candidate in os.listdir(path): return [(candidate, path) for candidate in os.listdir(path)]
candidates.append((candidate, path)) return []
return candidates
def get_path_for_link(self, link: Link) -> str: def get_path_for_link(self, link: Link) -> str:
"""Return a directory to store cached items in for link.""" """Return a directory to store cached items in for link."""

View file

@ -71,8 +71,9 @@ def autocomplete() -> None:
for opt in subcommand.parser.option_list_all: for opt in subcommand.parser.option_list_all:
if opt.help != optparse.SUPPRESS_HELP: if opt.help != optparse.SUPPRESS_HELP:
for opt_str in opt._long_opts + opt._short_opts: options += [
options.append((opt_str, opt.nargs)) (opt_str, opt.nargs) for opt_str in opt._long_opts + opt._short_opts
]
# filter out previously specified options from available options # filter out previously specified options from available options
prev_opts = [x.split("=")[0] for x in cwords[1 : cword - 1]] prev_opts = [x.split("=")[0] for x in cwords[1 : cword - 1]]

View file

@ -3,10 +3,10 @@ import textwrap
from optparse import Values from optparse import Values
from typing import Any, List from typing import Any, List
import pip._internal.utils.filesystem as filesystem
from pip._internal.cli.base_command import Command from pip._internal.cli.base_command import Command
from pip._internal.cli.status_codes import ERROR, SUCCESS from pip._internal.cli.status_codes import ERROR, SUCCESS
from pip._internal.exceptions import CommandError, PipError from pip._internal.exceptions import CommandError, PipError
from pip._internal.utils import filesystem
from pip._internal.utils.logging import getLogger from pip._internal.utils.logging import getLogger
logger = getLogger(__name__) logger = getLogger(__name__)
@ -151,14 +151,8 @@ class CacheCommand(Command):
logger.info("\n".join(sorted(results))) logger.info("\n".join(sorted(results)))
def format_for_abspath(self, files: List[str]) -> None: def format_for_abspath(self, files: List[str]) -> None:
if not files: if files:
return logger.info("\n".join(sorted(files)))
results = []
for filename in files:
results.append(filename)
logger.info("\n".join(sorted(results)))
def remove_cache_items(self, options: Values, args: List[Any]) -> None: def remove_cache_items(self, options: Values, args: List[Any]) -> None:
if len(args) > 1: if len(args) > 1:

View file

@ -135,7 +135,7 @@ def show_tags(options: Values) -> None:
def ca_bundle_info(config: Configuration) -> str: def ca_bundle_info(config: Configuration) -> str:
levels = set() levels = set()
for key, _ in config.items(): for key, _ in config.items(): # noqa: PERF102 Configuration has no keys() method.
levels.add(key.split(".")[0]) levels.add(key.split(".")[0])
if not levels: if not levels:

View file

@ -297,7 +297,7 @@ class ListCommand(IndexGroupCommand):
# Create and add a separator. # Create and add a separator.
if len(data) > 0: if len(data) > 0:
pkg_strings.insert(1, " ".join(map(lambda x: "-" * x, sizes))) pkg_strings.insert(1, " ".join(("-" * x for x in sizes)))
for val in pkg_strings: for val in pkg_strings:
write_output(val) write_output(val)

View file

@ -89,7 +89,7 @@ def distutils_scheme(
# finalize_options(); we only want to override here if the user # finalize_options(); we only want to override here if the user
# has explicitly requested it hence going back to the config # has explicitly requested it hence going back to the config
if "install_lib" in d.get_option_dict("install"): if "install_lib" in d.get_option_dict("install"):
scheme.update(dict(purelib=i.install_lib, platlib=i.install_lib)) scheme.update({"purelib": i.install_lib, "platlib": i.install_lib})
if running_under_virtualenv(): if running_under_virtualenv():
if home: if home:

View file

@ -33,7 +33,7 @@ class InstallationReport:
} }
if ireq.user_supplied and ireq.extras: if ireq.user_supplied and ireq.extras:
# For top level requirements, the list of requested extras, if any. # For top level requirements, the list of requested extras, if any.
res["requested_extras"] = list(sorted(ireq.extras)) res["requested_extras"] = sorted(ireq.extras)
return res return res
def to_dict(self) -> Dict[str, Any]: def to_dict(self) -> Dict[str, Any]:

View file

@ -267,9 +267,9 @@ def get_csv_rows_for_installed(
path = _fs_to_record_path(f, lib_dir) path = _fs_to_record_path(f, lib_dir)
digest, length = rehash(f) digest, length = rehash(f)
installed_rows.append((path, digest, length)) installed_rows.append((path, digest, length))
for installed_record_path in installed.values(): return installed_rows + [
installed_rows.append((installed_record_path, "", "")) (installed_record_path, "", "") for installed_record_path in installed.values()
return installed_rows ]
def get_console_script_specs(console: Dict[str, str]) -> List[str]: def get_console_script_specs(console: Dict[str, str]) -> List[str]:

View file

@ -274,7 +274,7 @@ class StashedUninstallPathSet:
def commit(self) -> None: def commit(self) -> None:
"""Commits the uninstall by removing stashed files.""" """Commits the uninstall by removing stashed files."""
for _, save_dir in self._save_dirs.items(): for save_dir in self._save_dirs.values():
save_dir.cleanup() save_dir.cleanup()
self._moves = [] self._moves = []
self._save_dirs = {} self._save_dirs = {}

View file

@ -36,10 +36,7 @@ def http_cache_files(http_cache_dir: str) -> List[str]:
return [] return []
filenames = glob(os.path.join(destination, "*")) filenames = glob(os.path.join(destination, "*"))
files = [] return [os.path.join(destination, filename) for filename in filenames]
for filename in filenames:
files.append(os.path.join(destination, filename))
return files
@pytest.fixture @pytest.fixture
@ -50,10 +47,7 @@ def wheel_cache_files(wheel_cache_dir: str) -> List[str]:
return [] return []
filenames = glob(os.path.join(destination, "*.whl")) filenames = glob(os.path.join(destination, "*.whl"))
files = [] return [os.path.join(destination, filename) for filename in filenames]
for filename in filenames:
files.append(os.path.join(destination, filename))
return files
@pytest.fixture @pytest.fixture
@ -107,7 +101,7 @@ def list_matches_wheel(wheel_name: str, result: TestPipResult) -> bool:
`- foo-1.2.3-py3-none-any.whl `.""" `- foo-1.2.3-py3-none-any.whl `."""
lines = result.stdout.splitlines() lines = result.stdout.splitlines()
expected = f" - {wheel_name}-py3-none-any.whl " expected = f" - {wheel_name}-py3-none-any.whl "
return any(map(lambda line: line.startswith(expected), lines)) return any((line.startswith(expected) for line in lines))
def list_matches_wheel_abspath(wheel_name: str, result: TestPipResult) -> bool: def list_matches_wheel_abspath(wheel_name: str, result: TestPipResult) -> bool:
@ -120,11 +114,9 @@ def list_matches_wheel_abspath(wheel_name: str, result: TestPipResult) -> bool:
lines = result.stdout.splitlines() lines = result.stdout.splitlines()
expected = f"{wheel_name}-py3-none-any.whl" expected = f"{wheel_name}-py3-none-any.whl"
return any( return any(
map( (
lambda line: ( (os.path.basename(line).startswith(expected) and os.path.exists(line))
os.path.basename(line).startswith(expected) and os.path.exists(line) for line in lines
),
lines,
) )
) )

View file

@ -102,8 +102,8 @@ def test_help_commands_equally_functional(in_memory_pip: InMemoryPip) -> None:
results = list(map(in_memory_pip.pip, ("help", "--help"))) results = list(map(in_memory_pip.pip, ("help", "--help")))
results.append(in_memory_pip.pip()) results.append(in_memory_pip.pip())
out = map(lambda x: x.stdout, results) out = (x.stdout for x in results)
ret = map(lambda x: x.returncode, results) ret = (x.returncode for x in results)
msg = '"pip --help" != "pip help" != "pip"' msg = '"pip --help" != "pip help" != "pip"'
assert len(set(out)) == 1, "output of: " + msg assert len(set(out)) == 1, "output of: " + msg

View file

@ -273,25 +273,19 @@ def test_outdated_flag(script: PipTestEnvironment, data: TestData) -> None:
"latest_version": "3.0", "latest_version": "3.0",
"latest_filetype": "sdist", "latest_filetype": "sdist",
} in json_output } in json_output
assert ( assert {
dict( "name": "simplewheel",
name="simplewheel", "version": "1.0",
version="1.0", "latest_version": "2.0",
latest_version="2.0", "latest_filetype": "wheel",
latest_filetype="wheel", } in json_output
) assert {
in json_output "name": "pip-test-package",
) "version": "0.1",
assert ( "latest_version": "0.1.1",
dict( "latest_filetype": "sdist",
name="pip-test-package", "editable_project_location": "<location>",
version="0.1", } in json_output
latest_version="0.1.1",
latest_filetype="sdist",
editable_project_location="<location>",
)
in json_output
)
assert "simple2" not in {p["name"] for p in json_output} assert "simple2" not in {p["name"] for p in json_output}

View file

@ -740,21 +740,19 @@ class PipTestEnvironment(TestFileEnvironment):
def assert_installed(self, **kwargs: str) -> None: def assert_installed(self, **kwargs: str) -> None:
ret = self.pip("list", "--format=json") ret = self.pip("list", "--format=json")
installed = set( installed = {
(canonicalize_name(val["name"]), val["version"]) (canonicalize_name(val["name"]), val["version"])
for val in json.loads(ret.stdout) for val in json.loads(ret.stdout)
) }
expected = set((canonicalize_name(k), v) for k, v in kwargs.items()) expected = {(canonicalize_name(k), v) for k, v in kwargs.items()}
assert expected <= installed, "{!r} not all in {!r}".format(expected, installed) assert expected <= installed, "{!r} not all in {!r}".format(expected, installed)
def assert_not_installed(self, *args: str) -> None: def assert_not_installed(self, *args: str) -> None:
ret = self.pip("list", "--format=json") ret = self.pip("list", "--format=json")
installed = set( installed = {canonicalize_name(val["name"]) for val in json.loads(ret.stdout)}
canonicalize_name(val["name"]) for val in json.loads(ret.stdout)
)
# None of the given names should be listed as installed, i.e. their # None of the given names should be listed as installed, i.e. their
# intersection should be empty. # intersection should be empty.
expected = set(canonicalize_name(k) for k in args) expected = {canonicalize_name(k) for k in args}
assert not (expected & installed), "{!r} contained in {!r}".format( assert not (expected & installed), "{!r} contained in {!r}".format(
expected, installed expected, installed
) )
@ -798,16 +796,16 @@ def diff_states(
return path.startswith(prefix) return path.startswith(prefix)
start_keys = { start_keys = {
k for k in start.keys() if not any([prefix_match(k, i) for i in ignore]) k for k in start.keys() if not any(prefix_match(k, i) for i in ignore)
} }
end_keys = {k for k in end.keys() if not any([prefix_match(k, i) for i in ignore])} end_keys = {k for k in end.keys() if not any(prefix_match(k, i) for i in ignore)}
deleted = {k: start[k] for k in start_keys.difference(end_keys)} deleted = {k: start[k] for k in start_keys.difference(end_keys)}
created = {k: end[k] for k in end_keys.difference(start_keys)} created = {k: end[k] for k in end_keys.difference(start_keys)}
updated = {} updated = {}
for k in start_keys.intersection(end_keys): for k in start_keys.intersection(end_keys):
if start[k].size != end[k].size: if start[k].size != end[k].size:
updated[k] = end[k] updated[k] = end[k]
return dict(deleted=deleted, created=created, updated=updated) return {"deleted": deleted, "created": created, "updated": updated}
def assert_all_changes( def assert_all_changes(

View file

@ -234,7 +234,7 @@ class TestCandidateEvaluator:
) )
sort_key = evaluator._sort_key sort_key = evaluator._sort_key
results = sorted(links, key=sort_key, reverse=True) results = sorted(links, key=sort_key, reverse=True)
results2 = sorted(reversed(links), key=sort_key, reverse=True) results2 = sorted(links, key=sort_key, reverse=True)
assert links == results, results assert links == results, results
assert links == results2, results2 assert links == results2, results2
@ -261,7 +261,7 @@ class TestCandidateEvaluator:
candidate_evaluator = CandidateEvaluator.create("my-project") candidate_evaluator = CandidateEvaluator.create("my-project")
sort_key = candidate_evaluator._sort_key sort_key = candidate_evaluator._sort_key
results = sorted(links, key=sort_key, reverse=True) results = sorted(links, key=sort_key, reverse=True)
results2 = sorted(reversed(links), key=sort_key, reverse=True) results2 = sorted(links, key=sort_key, reverse=True)
assert links == results, results assert links == results, results
assert links == results2, results2 assert links == results2, results2
@ -301,7 +301,7 @@ class TestCandidateEvaluator:
) )
sort_key = evaluator._sort_key sort_key = evaluator._sort_key
results = sorted(links, key=sort_key, reverse=True) results = sorted(links, key=sort_key, reverse=True)
results2 = sorted(reversed(links), key=sort_key, reverse=True) results2 = sorted(links, key=sort_key, reverse=True)
assert links == results, results assert links == results, results
assert links == results2, results2 assert links == results2, results2

View file

@ -21,13 +21,13 @@ class TestIndentingFormatter:
def make_record(self, msg: str, level_name: str) -> logging.LogRecord: def make_record(self, msg: str, level_name: str) -> logging.LogRecord:
level_number = getattr(logging, level_name) level_number = getattr(logging, level_name)
attrs = dict( attrs = {
msg=msg, "msg": msg,
created=1547704837.040001 + time.timezone, "created": 1547704837.040001 + time.timezone,
msecs=40, "msecs": 40,
levelname=level_name, "levelname": level_name,
levelno=level_number, "levelno": level_number,
) }
record = logging.makeLogRecord(attrs) record = logging.makeLogRecord(attrs)
return record return record

View file

@ -59,10 +59,9 @@ def test_uninstallation_paths() -> None:
def test_compressed_listing(tmpdir: Path) -> None: def test_compressed_listing(tmpdir: Path) -> None:
def in_tmpdir(paths: List[str]) -> List[str]: def in_tmpdir(paths: List[str]) -> List[str]:
li = [] return [
for path in paths: str(os.path.join(tmpdir, path.replace("/", os.path.sep))) for path in paths
li.append(str(os.path.join(tmpdir, path.replace("/", os.path.sep)))) ]
return li
sample = in_tmpdir( sample = in_tmpdir(
[ [

View file

@ -40,7 +40,7 @@ def test_pip_self_version_check_calls_underlying_implementation(
) -> None: ) -> None:
# GIVEN # GIVEN
mock_session = Mock() mock_session = Mock()
fake_options = Values(dict(cache_dir=str(tmpdir))) fake_options = Values({"cache_dir": str(tmpdir)})
# WHEN # WHEN
self_outdated_check.pip_self_version_check(mock_session, fake_options) self_outdated_check.pip_self_version_check(mock_session, fake_options)

View file

@ -54,18 +54,18 @@ class TestTargetPython:
"kwargs, expected", "kwargs, expected",
[ [
({}, ""), ({}, ""),
(dict(py_version_info=(3, 6)), "version_info='3.6'"), ({"py_version_info": (3, 6)}, "version_info='3.6'"),
( (
dict(platforms=["darwin"], py_version_info=(3, 6)), {"platforms": ["darwin"], "py_version_info": (3, 6)},
"platforms=['darwin'] version_info='3.6'", "platforms=['darwin'] version_info='3.6'",
), ),
( (
dict( {
platforms=["darwin"], "platforms": ["darwin"],
py_version_info=(3, 6), "py_version_info": (3, 6),
abis=["cp36m"], "abis": ["cp36m"],
implementation="cp", "implementation": "cp",
), },
( (
"platforms=['darwin'] version_info='3.6' abis=['cp36m'] " "platforms=['darwin'] version_info='3.6' abis=['cp36m'] "
"implementation='cp'" "implementation='cp'"

View file

@ -73,7 +73,7 @@ def test_rev_options_repr() -> None:
Git, Git,
["HEAD", "opt1", "opt2"], ["HEAD", "opt1", "opt2"],
["123", "opt1", "opt2"], ["123", "opt1", "opt2"],
dict(extra_args=["opt1", "opt2"]), {"extra_args": ["opt1", "opt2"]},
), ),
], ],
) )