-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathscaffold_rule.py
More file actions
220 lines (191 loc) · 6.49 KB
/
scaffold_rule.py
File metadata and controls
220 lines (191 loc) · 6.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
#!/usr/bin/env python3
"""Scaffold a new sql-sop rule from one-line description.
Generates copy-paste-ready snippets for every file that needs an edit when
adding a new rule:
1. The new rule class for sql_guard/rules/{warnings,errors,structural}.py
2. The rule registration in sql_guard/rules/__init__.py
3. The fixture line in tests/fixtures/{warnings,errors}.sql
4. The two tests in tests/test_new_rules.py
5. The README rule table row
6. The CHANGELOG entry under [Unreleased]
The output mirrors the W019 (CountDistinctUnbounded) shape, which is the
canonical template referenced in CONTRIBUTING.md and the v0.7 milestone.
Severity and target file are inferred from the rule code prefix:
E -> error, errors.py
W -> warning, warnings.py
T -> warning, warnings.py (T-SQL family)
S -> warning, structural.py
P -> error, python_source.py
Example:
python scripts/scaffold_rule.py \\
--code W024 \\
--name negate-of-equality \\
--description "WHERE NOT col = x defeats index seek access" \\
--regex "WHERE\\s+NOT\\s+\\w+\\s*=" \\
--bad "SELECT * FROM t WHERE NOT id = 1;" \\
--good "SELECT * FROM t WHERE id != 1;"
"""
import argparse
import re
import sys
SEVERITY_BY_PREFIX = {
"E": ("error", "errors.py"),
"W": ("warning", "warnings.py"),
"T": ("warning", "warnings.py"),
"S": ("warning", "structural.py"),
"P": ("error", "python_source.py"),
}
def class_name_from_kebab(kebab: str) -> str:
return "".join(word.capitalize() for word in kebab.split("-"))
CLASS_TEMPLATE = '''\
class {klass}(Rule):
"""{code}: {description}.
{description}.
"""
id = "{code}"
name = "{name}"
severity = "{severity}"
description = "{description}"
_pattern = Rule._compile(r"{regex}")
def check_line(self, line: str, line_number: int, file: str):
if self._pattern.search(line):
return Finding(
rule_id=self.id,
severity=self.severity,
file=file,
line=line_number,
message="{message}",
suggestion="{suggestion}",
)
return None
'''
TEST_TEMPLATE = '''\
def test_{code_lower}_fires_on_bad_sql():
rule = {klass}()
finding = _line(rule, {bad!r})
assert finding is not None
assert finding.rule_id == "{code}"
def test_{code_lower}_passes_on_safe_sql():
rule = {klass}()
assert _line(rule, {good!r}) is None
'''
def main() -> int:
parser = argparse.ArgumentParser(
description="Scaffold a new sql-sop rule.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__.split("Example:")[1] if "Example:" in __doc__ else "",
)
parser.add_argument("--code", required=True, help="Rule code, e.g. W024 (must match [EWTSP]NNN)")
parser.add_argument("--name", required=True, help="Rule name in kebab-case, e.g. negate-of-equality")
parser.add_argument("--description", required=True, help="One-line description for the rule")
parser.add_argument("--regex", default="YOUR_PATTERN_HERE", help="Regex pattern to match")
parser.add_argument("--message", help="Finding message (defaults to description)")
parser.add_argument(
"--suggestion",
default="Refactor for clarity and performance",
help="Suggested fix shown alongside the finding",
)
parser.add_argument("--bad", default="-- TODO: bad SQL example", help="SQL example that should fire")
parser.add_argument("--good", default="-- TODO: safe SQL example", help="SQL example that should not fire")
args = parser.parse_args()
code = args.code.upper()
if not re.fullmatch(r"[EWTSP]\d{3}", code):
sys.exit(f"error: rule code {code!r} must match [EWTSP]NNN, e.g. W024")
prefix = code[0]
severity, target_file = SEVERITY_BY_PREFIX[prefix]
klass = class_name_from_kebab(args.name)
message = args.message or args.description
ctx = {
"code": code,
"code_lower": code.lower(),
"name": args.name,
"klass": klass,
"severity": severity,
"target_file": target_file,
"description": args.description,
"regex": args.regex,
"message": message,
"suggestion": args.suggestion,
"bad": args.bad,
"good": args.good,
}
fixture_file = "errors.sql" if severity == "error" else "warnings.sql"
out: list[str] = []
out += [
f"# Scaffold for {code} `{args.name}`",
"",
"Generated by `scripts/scaffold_rule.py`. Mirrors the W019 shape.",
f"Severity: **{severity}**. Target rule file: `sql_guard/rules/{target_file}`.",
"",
"---",
f"## 1. Append to `sql_guard/rules/{target_file}`",
"",
"```python",
CLASS_TEMPLATE.format(**ctx).rstrip(),
"```",
"",
"---",
"## 2. Register in `sql_guard/rules/__init__.py`",
"",
"Add to the import block:",
"",
f" {klass},",
"",
"Add to `ALL_RULES`:",
"",
f" {klass}(),",
"",
"---",
f"## 3. Append to `tests/fixtures/{fixture_file}`",
"",
"```sql",
f"-- {code} {args.name}",
args.bad,
"```",
"",
"---",
"## 4. Append tests to `tests/test_new_rules.py`",
"",
"Move this import to the **top of the file** with the other rule imports (E402 fires otherwise):",
"",
"```python",
f"from sql_guard.rules.{target_file.removesuffix('.py')} import {klass}",
"```",
"",
"Then append the test functions:",
"",
"```python",
TEST_TEMPLATE.format(**ctx).rstrip(),
"```",
"",
"---",
"## 5. README rule table row",
"",
f"| {code} | `{args.name}` | {severity} | {args.description} |",
"",
"---",
"## 6. CHANGELOG entry",
"",
"Under `## [Unreleased]` -> `### Added`:",
"",
f"- **{code} `{args.name}`** - {args.description}.",
"",
"---",
"## 7. README Key Numbers",
"",
f"Bump total rule count by 1; bump {severity} count by 1.",
"",
"---",
"## Validate before opening the PR",
"",
"```bash",
"pytest -q",
"ruff check . && ruff format .",
"```",
"",
f"Commit with `feat(rules): add {code} {args.name}` and push.",
]
print("\n".join(out))
return 0
if __name__ == "__main__":
sys.exit(main())