Skip to content

Commit 8773acd

Browse files
even-evenvyuroshchin
andauthored
add C4 and perflint ruff rules (#989)
Co-authored-by: vyuroshchin <vyuroshchin@sberautotech.ru>
1 parent 1c6681b commit 8773acd

File tree

17 files changed

+101
-97
lines changed

17 files changed

+101
-97
lines changed

pip_audit/_audit.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,4 +93,4 @@ def audit(
9393
seen_aliases.update(v.aliases | {v.id})
9494
unique_vulns.append(v)
9595

96-
yield (dep, unique_vulns)
96+
yield dep, unique_vulns

pip_audit/_cli.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -584,7 +584,7 @@ def audit() -> None: # pragma: no cover
584584

585585
# If the `--fix` flag has been applied, find a set of suitable fix versions and upgrade the
586586
# dependencies at the source
587-
fixes = list()
587+
fixes = []
588588
fixed_pkg_count = 0
589589
fixed_vuln_count = 0
590590
if args.fix:

pip_audit/_dependency_source/pip.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,9 @@ def collect(self) -> Iterator[Dependency]:
112112
# The `pip list` call that underlies `pip_api` could fail for myriad reasons.
113113
# We collect them all into a single well-defined error.
114114
try:
115-
for _, dist in pip_api.installed_distributions(
115+
for dist in pip_api.installed_distributions(
116116
local=self._local, paths=list(self._paths)
117-
).items():
117+
).values():
118118
dep: Dependency
119119
if dist.editable and self._skip_editable:
120120
dep = SkippedDependency(

pip_audit/_dependency_source/requirement.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ def fix(self, fix_version: ResolvedFixVersion) -> None:
195195
tmp_files: list[IO[str]] = [
196196
stack.enter_context(NamedTemporaryFile(mode="r+")) for _ in self._filenames
197197
]
198-
for filename, tmp_file in zip(self._filenames, tmp_files):
198+
for filename, tmp_file in zip(self._filenames, tmp_files, strict=True):
199199
with filename.open("r") as f:
200200
shutil.copyfileobj(f, tmp_file)
201201

@@ -225,7 +225,7 @@ def _fix_file(self, filename: Path, fix_version: ResolvedFixVersion) -> None:
225225
# Check ahead of time for anything invalid in the requirements file since we don't want to
226226
# encounter this while writing out the file. Check for duplicate requirements and lines that
227227
# failed to parse.
228-
req_specifiers: dict[str, SpecifierSet] = dict()
228+
req_specifiers: dict[str, SpecifierSet] = {}
229229

230230
for req in reqs:
231231
if (
@@ -281,12 +281,12 @@ def _fix_file(self, filename: Path, fix_version: ResolvedFixVersion) -> None:
281281
print(f"{fix_version.dep.canonical_name}=={fix_version.version}", file=f)
282282

283283
def _recover_files(self, tmp_files: list[IO[str]]) -> None:
284-
for filename, tmp_file in zip(self._filenames, tmp_files):
284+
for filename, tmp_file in zip(self._filenames, tmp_files, strict=True):
285285
try:
286286
tmp_file.seek(0)
287287
with filename.open("w") as f:
288288
shutil.copyfileobj(tmp_file, f)
289-
except Exception as e:
289+
except Exception as e: # noqa: PERF203
290290
# Not much we can do at this point since we're already handling an exception. Just
291291
# log the error and try to recover the rest of the files.
292292
logger.warning(f"encountered an exception during file recovery: {e}")
@@ -298,7 +298,7 @@ def _collect_preresolved_deps(
298298
"""
299299
Collect pre-resolved (pinned) dependencies.
300300
"""
301-
req_specifiers: dict[str, SpecifierSet] = dict()
301+
req_specifiers: dict[str, SpecifierSet] = {}
302302
for req in reqs:
303303
if not req.hash_options and require_hashes:
304304
raise RequirementSourceError(f"requirement {req.dumps()} does not contain a hash")

pip_audit/_format/columns.py

Lines changed: 27 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -74,13 +74,19 @@ def format(
7474
if self.output_desc:
7575
header.append("Description")
7676
vuln_data.append(header)
77-
for dep, vulns in result.items():
78-
if dep.is_skipped():
79-
continue
80-
dep = cast(service.ResolvedDependency, dep)
81-
applied_fix = next((f for f in fixes if f.dep == dep), None)
82-
for vuln in vulns:
83-
vuln_data.append(self._format_vuln(dep, vuln, applied_fix))
77+
78+
vuln_rows = [
79+
self._format_vuln(
80+
cast(service.ResolvedDependency, dep),
81+
vuln,
82+
next((f for f in fixes if f.dep == dep), None),
83+
)
84+
for dep, vulns in result.items()
85+
if not dep.is_skipped()
86+
for vuln in vulns
87+
]
88+
89+
vuln_data.extend(vuln_rows)
8490

8591
columns_string = ""
8692

@@ -90,37 +96,29 @@ def format(
9096

9197
# Create and add a separator.
9298
if len(vuln_data) > 0:
93-
vuln_strings.insert(1, " ".join(map(lambda x: "-" * x, sizes)))
99+
vuln_strings.insert(1, " ".join("-" * x for x in sizes))
94100

95101
for row in vuln_strings:
96102
if columns_string:
97103
columns_string += "\n"
98104
columns_string += row
99105

100106
# Now display the skipped dependencies
101-
skip_data: list[list[Any]] = []
102-
skip_header = ["Name", "Skip Reason"]
103-
104-
skip_data.append(skip_header)
105-
for dep, _ in result.items():
106-
if dep.is_skipped():
107-
dep = cast(service.SkippedDependency, dep)
108-
skip_data.append(self._format_skipped_dep(dep))
109-
110-
# If we only have the header, that means that we haven't skipped any dependencies
111-
# In that case, don't bother printing the header
112-
if len(skip_data) <= 1:
113-
return columns_string
114-
115-
skip_strings, sizes = tabulate(skip_data)
107+
skip_data = [
108+
self._format_skipped_dep(cast(service.SkippedDependency, dep))
109+
for dep in result.keys()
110+
if dep.is_skipped()
111+
]
116112

117-
# Create separator for skipped dependencies columns
118-
skip_strings.insert(1, " ".join(map(lambda x: "-" * x, sizes)))
113+
if skip_data:
114+
skip_data.insert(0, ["Name", "Skip Reason"])
115+
skip_strings, sizes = tabulate(skip_data)
116+
skip_strings.insert(1, " ".join("-" * x for x in sizes))
119117

120-
for row in skip_strings:
121-
if columns_string:
122-
columns_string += "\n"
123-
columns_string += row
118+
for row in skip_strings:
119+
if columns_string:
120+
columns_string += "\n"
121+
columns_string += row
124122

125123
return columns_string
126124

pip_audit/_format/cyclonedx.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -35,17 +35,17 @@ def _pip_audit_result_to_bom(
3535
dep = cast(service.ResolvedDependency, dep)
3636

3737
c = Component(name=dep.name, version=str(dep.version))
38-
for vuln in vulns:
39-
vulnerabilities.append(
40-
Vulnerability(
41-
id=vuln.id,
42-
description=vuln.description,
43-
recommendation="Upgrade",
44-
# BomTarget expects str in type hints, but accepts BomRef at runtime
45-
affects=[BomTarget(ref=c.bom_ref)], # type: ignore[arg-type]
46-
)
38+
vuln_list = [
39+
Vulnerability(
40+
id=vuln.id,
41+
description=vuln.description,
42+
recommendation="Upgrade",
43+
# BomTarget expects str in type hints, but accepts BomRef at runtime
44+
affects=[BomTarget(ref=c.bom_ref)], # type: ignore[arg-type]
4745
)
48-
46+
for vuln in vulns
47+
]
48+
vulnerabilities.extend(vuln_list)
4949
components.append(c)
5050

5151
return Bom(components=components, vulnerabilities=vulnerabilities)

pip_audit/_format/json.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -50,15 +50,10 @@ def format(
5050
5151
See `VulnerabilityFormat.format`.
5252
"""
53-
output_json = {}
54-
dep_json = []
55-
for dep, vulns in result.items():
56-
dep_json.append(self._format_dep(dep, vulns))
57-
output_json["dependencies"] = dep_json
58-
fix_json = []
59-
for f in fixes:
60-
fix_json.append(self._format_fix(f))
61-
output_json["fixes"] = fix_json
53+
output_json = {
54+
"dependencies": [self._format_dep(dep, vulns) for dep, vulns in result.items()],
55+
"fixes": [self._format_fix(f) for f in fixes],
56+
}
6257
return json.dumps(output_json)
6358

6459
def _format_dep(

pip_audit/_format/markdown.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -77,14 +77,16 @@ def _format_vuln_results(
7777
header += " | Description"
7878
border += " | ---"
7979

80-
vuln_rows: list[str] = []
81-
for dep, vulns in result.items():
82-
if dep.is_skipped():
83-
continue
84-
dep = cast(service.ResolvedDependency, dep)
85-
applied_fix = next((f for f in fixes if f.dep == dep), None)
86-
for vuln in vulns:
87-
vuln_rows.append(self._format_vuln(dep, vuln, applied_fix))
80+
vuln_rows = [
81+
self._format_vuln(
82+
cast(service.ResolvedDependency, dep),
83+
vuln,
84+
next((f for f in fixes if f.dep == dep), None),
85+
)
86+
for dep, vulns in result.items()
87+
if not dep.is_skipped()
88+
for vuln in vulns
89+
]
8890

8991
if not vuln_rows:
9092
return ""
@@ -137,7 +139,7 @@ def _format_skipped_deps(
137139
border = "--- | ---"
138140

139141
skipped_dep_rows: list[str] = []
140-
for dep, _ in result.items():
142+
for dep in result.keys():
141143
if dep.is_skipped():
142144
dep = cast(service.SkippedDependency, dep)
143145
skipped_dep_rows.append(self._format_skipped_dep(dep))

pip_audit/_util.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def assert_never(x: NoReturn) -> NoReturn: # pragma: no cover
1212
"""
1313
A hint to the typechecker that a branch can never occur.
1414
"""
15-
assert False, f"unhandled type: {type(x).__name__}"
15+
raise AssertionError(f"unhandled type: {type(x).__name__}")
1616

1717

1818
def python_version() -> Version:

pyproject.toml

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,15 @@ reset = true
109109
line-length = 100
110110

111111
[tool.ruff.lint]
112+
select = [
113+
"E", # pycodestyle (errors)
114+
"W", # pycodestyle (warnings)
115+
"F", # pyflakes
116+
"I", # isort (imports ordering)
117+
"UP", # pyupgrade
118+
"C4", # comprehensions
119+
"PERF", # perflint
120+
]
121+
112122
# Never enforce `E501` (line length violations).
113123
ignore = ["E501"]
114-
select = ["E", "F", "I", "W", "UP"]

0 commit comments

Comments
 (0)