Skip to content

Commit ed8d4f0

Browse files
authored
Ruff: Add PTH123, merge PTH, fix in /dojo (#12025)
1 parent c593fe3 commit ed8d4f0

File tree

12 files changed

+35
-29
lines changed

12 files changed

+35
-29
lines changed

dojo/api_v2/views.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import logging
33
import mimetypes
44
from datetime import datetime
5+
from pathlib import Path
56

67
import tagulous
78
from crum import get_current_user
@@ -724,12 +725,12 @@ def download_proof(self, request, pk=None):
724725
status=status.HTTP_404_NOT_FOUND,
725726
)
726727
# Get the path of the file in media root
727-
file_path = f"{settings.MEDIA_ROOT}/{file_object.name}"
728-
file_handle = open(file_path, "rb")
728+
file_path = Path(settings.MEDIA_ROOT) / file_object.name
729+
file_handle = file_path.open("rb")
729730
# send file
730731
response = FileResponse(
731732
file_handle,
732-
content_type=f"{mimetypes.guess_type(file_path)}",
733+
content_type=f"{mimetypes.guess_type(str(file_path))}",
733734
status=status.HTTP_200_OK,
734735
)
735736
response["Content-Length"] = file_object.size

dojo/engagement/views.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import re
66
from datetime import datetime
77
from functools import reduce
8+
from pathlib import Path
89
from tempfile import NamedTemporaryFile
910
from time import strftime
1011

@@ -1462,7 +1463,7 @@ def download_risk_acceptance(request, eid, raid):
14621463
raise PermissionDenied
14631464
response = StreamingHttpResponse(
14641465
FileIterWrapper(
1465-
open(settings.MEDIA_ROOT + "/" + risk_acceptance.path.name, mode="rb")))
1466+
(Path(settings.MEDIA_ROOT) / "risk_acceptance.path.name").open(mode="rb")))
14661467
response["Content-Disposition"] = f'attachment; filename="{risk_acceptance.filename()}"'
14671468
mimetype, _encoding = mimetypes.guess_type(risk_acceptance.path.name)
14681469
response["Content-Type"] = mimetype

dojo/finding/views.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import mimetypes
88
from collections import OrderedDict, defaultdict
99
from itertools import chain
10+
from pathlib import Path
1011

1112
from django.conf import settings
1213
from django.contrib import messages
@@ -2460,7 +2461,7 @@ class Original(ImageSpec):
24602461
except Exception:
24612462
raise PermissionDenied
24622463

2463-
with open(access_token.file.file.file.name, "rb") as file:
2464+
with Path(access_token.file.file.file.name).open("rb") as file:
24642465
file_name = file.name
24652466
image = size_map[size](source=file).generate()
24662467
response = StreamingHttpResponse(FileIterWrapper(image))

dojo/jira_link/helper.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1225,7 +1225,7 @@ def jira_attachment(finding, jira, issue, file, jira_filename=None):
12251225
issue=issue, attachment=attachment, filename=jira_filename)
12261226
else:
12271227
# read and upload a file
1228-
with open(file, "rb") as f:
1228+
with Path(file).open("rb") as f:
12291229
jira.add_attachment(issue=issue, attachment=f)
12301230
except JIRAError as e:
12311231
logger.exception("Unable to add attachment")

dojo/management/commands/csv_findings_export.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import csv
2+
from pathlib import Path
23

34
from django.core.management.base import BaseCommand
45
from pytz import timezone
@@ -21,12 +22,12 @@ def add_arguments(self, parser):
2122
parser.add_argument("file_path")
2223

2324
def handle(self, *args, **options):
24-
file_path = options["file_path"]
25+
file_path = Path(options["file_path"])
2526

2627
findings = Finding.objects.filter(verified=True,
2728
active=True).select_related(
2829
"test__engagement__product")
29-
writer = csv.writer(open(file_path, "w", encoding="utf-8"))
30+
writer = csv.writer(file_path.open("w", encoding="utf-8"))
3031

3132
headers = [
3233
"product_name",

dojo/management/commands/import_surveys.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,8 @@ def handle(self, *args, **options):
2727
row = cursor.fetchone()
2828
ctype_id = row[0]
2929
# Find the current id in the surveys file
30-
path = Path(__file__).parent.absolute()
31-
path = path[:-19] + "fixtures/initial_surveys.json"
32-
contents = open(path, encoding="utf-8").readlines()
30+
path = Path(__file__).parent.parent.parent / "fixtures" / "initial_surveys.json"
31+
contents = path.open(encoding="utf-8").readlines()
3332
for line in contents:
3433
if '"polymorphic_ctype": ' in line:
3534
matchedLine = line
@@ -38,7 +37,7 @@ def handle(self, *args, **options):
3837
old_id = "".join(c for c in matchedLine if c.isdigit())
3938
new_line = matchedLine.replace(old_id, str(ctype_id))
4039
# Replace the all lines in the file
41-
with open(path, "w", encoding="utf-8") as fout:
40+
with path.open("w", encoding="utf-8") as fout:
4241
fout.writelines(line.replace(matchedLine, new_line) for line in contents)
4342
# Delete the temp question
4443
created_question.delete()

dojo/tools/blackduck/importer.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,13 @@ def parse_findings(self, report: Path) -> Iterable[BlackduckFinding]:
2626
return self._process_zipfile(report)
2727
return self._process_csvfile(report)
2828

29-
def _process_csvfile(self, report):
29+
def _process_csvfile(self, report: Path):
3030
"""
3131
If passed in a regular security.csv, process it.
3232
No file information then.
3333
"""
3434
security_issues = {}
35-
with open(str(report), encoding="utf-8") as f:
35+
with report.open(encoding="utf-8") as f:
3636
security_issues = self.__partition_by_key(f)
3737

3838
project_ids = set(security_issues.keys())

dojo/tools/blackduck_binary_analysis/importer.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@ def parse_findings(self, report: Path) -> Iterable[BlackduckBinaryAnalysisFindin
2222

2323
return self._process_csvfile(report, orig_report_name)
2424

25-
def _process_csvfile(self, report, orig_report_name):
25+
def _process_csvfile(self, report: Path, orig_report_name):
2626
"""If passed a CSV file, process."""
2727
vulnerabilities = {}
28-
with open(str(report), encoding="utf-8") as f:
28+
with report.open(encoding="utf-8") as f:
2929
vulnerabilities = self.__partition_by_key(f)
3030

3131
sha1_hash_keys = set(vulnerabilities.keys())

dojo/utils.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1377,23 +1377,24 @@ def handle_uploaded_threat(f, eng):
13771377
path = Path(f.name)
13781378
extension = path.suffix
13791379
# Check if threat folder exist.
1380-
if not Path(settings.MEDIA_ROOT + "/threat/").is_dir():
1380+
threat_dir = Path(settings.MEDIA_ROOT) / "threat"
1381+
if not threat_dir.is_dir():
13811382
# Create the folder
1382-
Path(settings.MEDIA_ROOT + "/threat/").mkdir()
1383-
with open(settings.MEDIA_ROOT + f"/threat/{eng.id}{extension}",
1384-
"wb+") as destination:
1383+
threat_dir.mkdir()
1384+
eng_path = threat_dir / f"{eng.id}{extension}"
1385+
with eng_path.open("wb+") as destination:
13851386
destination.writelines(chunk for chunk in f.chunks())
1386-
eng.tmodel_path = settings.MEDIA_ROOT + f"/threat/{eng.id}{extension}"
1387+
eng.tmodel_path = str(eng_path)
13871388
eng.save()
13881389

13891390

13901391
def handle_uploaded_selenium(f, cred):
13911392
path = Path(f.name)
13921393
extension = path.suffix
1393-
with open(settings.MEDIA_ROOT + f"/selenium/{cred.id}{extension}",
1394-
"wb+") as destination:
1394+
sel_path = Path(settings.MEDIA_ROOT) / "selenium" / f"{cred.id}{extension}"
1395+
with sel_path.open("wb+") as destination:
13951396
destination.writelines(chunk for chunk in f.chunks())
1396-
cred.selenium_script = settings.MEDIA_ROOT + f"/selenium/{cred.id}{extension}"
1397+
cred.selenium_script = str(sel_path)
13971398
cred.save()
13981399

13991400

@@ -2694,7 +2695,7 @@ def generate_file_response_from_file_path(
26942695
# Generate the FileResponse
26952696
full_file_name = f"{file_name}{file_extension}"
26962697
response = FileResponse(
2697-
open(file_path, "rb"),
2698+
path.open("rb"),
26982699
filename=full_file_name,
26992700
content_type=f"{mimetypes.guess_type(file_path)}",
27002701
)

ruff.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ select = [
6868
"TC",
6969
"INT",
7070
"ARG003", "ARG004", "ARG005",
71-
"PTH2", "PTH10", "PTH11", "PTH120", "PTH121", "PTH122", "PTH124",
71+
"PTH",
7272
"TD001", "TD004", "TD005", "TD007",
7373
"FIX",
7474
"PD",
@@ -113,6 +113,7 @@ preview = true
113113
"unittests/**" = [
114114
"S105", # hardcoded passwords in tests are fine
115115
"S108", # tmp paths mentioned in tests are fine
116+
"PTH123", # Fix is needed in unittests as well but there are too many problematic files, let's do it per partes
116117
]
117118

118119
[lint.flake8-boolean-trap]

0 commit comments

Comments
 (0)