Skip to content

Commit 4aa4f09

Browse files
committed
introduce regular expressions instead of plain string matching
1 parent 8124396 commit 4aa4f09

File tree

1 file changed

+15
-16
lines changed

1 file changed

+15
-16
lines changed

scripts/lint_model_usage_in_views.py

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
"""Simple linter to spot denylisted model usage within Django view modules."""
33

44
import argparse
5+
import re
56
import sys
67
from dataclasses import dataclass
78
from pathlib import Path
@@ -15,7 +16,10 @@
1516
"Symptom",
1617
"BreastCancerHistoryItem",
1718
)
18-
DENYLISTED_HELPERS = ("get_object_or_404(",)
19+
TARGETS = {
20+
"model.objects": re.compile(r"(?P<model_name>\w+)\.objects"),
21+
"model.get_object_or_404": re.compile(r"(?P<model_name>\w+)\.get_object_or_404"),
22+
}
1923

2024

2125
@dataclass
@@ -61,28 +65,23 @@ def find_view_modules(base_dir):
6165

6266

6367
def find_matches(paths):
64-
targets = {
65-
f"{model_name}.objects": f"{model_name}.objects"
66-
for model_name in DENYLISTED_MODELS
67-
}
68-
for helper in DENYLISTED_HELPERS:
69-
targets[helper] = helper
70-
7168
for path in paths:
7269
try:
7370
text = path.read_text(encoding="utf-8")
7471
except UnicodeDecodeError:
7572
continue
7673

7774
for line_number, line in enumerate(text.splitlines(), start=1):
78-
for needle, label in targets.items():
79-
if needle in line:
80-
yield Match(
81-
path=path,
82-
line_number=line_number,
83-
target=label,
84-
line=line.strip(),
85-
)
75+
for label, regex in TARGETS.items():
76+
if match := regex.search(line):
77+
model_name = match.group("model_name")
78+
if model_name in DENYLISTED_MODELS:
79+
yield Match(
80+
path=path,
81+
line_number=line_number,
82+
target=label,
83+
line=line.strip(),
84+
)
8685

8786

8887
def main():

0 commit comments

Comments
 (0)