mtkit 1.16.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mtkit/__init__.py +36 -0
- mtkit/__main__.py +6 -0
- mtkit/asset.py +101 -0
- mtkit/audit.py +220 -0
- mtkit/builder.py +100 -0
- mtkit/cli.py +885 -0
- mtkit/conf.py +63 -0
- mtkit/coverage.py +175 -0
- mtkit/db.py +676 -0
- mtkit/evolve.py +142 -0
- mtkit/extract/__init__.py +17 -0
- mtkit/extract/code_facts.py +631 -0
- mtkit/extract/docx_loader.py +115 -0
- mtkit/extract/xmind_loader.py +125 -0
- mtkit/generate/__init__.py +10 -0
- mtkit/generate/llm.py +360 -0
- mtkit/generate/prompts.py +178 -0
- mtkit/generate/skeleton.py +59 -0
- mtkit/normalize.py +480 -0
- mtkit/parsers.py +318 -0
- mtkit/review.py +274 -0
- mtkit/selfheal.py +110 -0
- mtkit/tb.py +191 -0
- mtkit/track.py +309 -0
- mtkit/validator.py +174 -0
- mtkit/writer.py +137 -0
- mtkit-1.16.1.dist-info/METADATA +150 -0
- mtkit-1.16.1.dist-info/RECORD +31 -0
- mtkit-1.16.1.dist-info/WHEEL +5 -0
- mtkit-1.16.1.dist-info/entry_points.txt +2 -0
- mtkit-1.16.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,631 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
Code repo scanner: extract structured facts from source code, for case generation and coverage diff.
|
|
4
|
+
|
|
5
|
+
Extracted content:
|
|
6
|
+
1. interfaces : Java controller interface list (url/method/permission/name)
|
|
7
|
+
2. sqls : MyBatis mapper.xml SQL dictionary (id -> SQL text)
|
|
8
|
+
3. stored_procs: stored procedure files (.sql files under the repo, CREATE PROCEDURE definitions)
|
|
9
|
+
|
|
10
|
+
scan rules (based on Java Spring Boot + MyBatis project conventions):
|
|
11
|
+
- @RequestMapping("/base") class-level path + @GetMapping/@PostMapping method-level path
|
|
12
|
+
- @PermissionFunction(code=..., name=...) permission points
|
|
13
|
+
- mapper.xml <select|update|insert|delete id="..."> ... SQL
|
|
14
|
+
"""
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
|
|
19
|
+
# Java annotation matching
|
|
20
|
+
_CLASS_MAPPING_PATTERN = re.compile(r'@RequestMapping\s*\(\s*"([^"]+)"')
|
|
21
|
+
_METHOD_MAPPING_PATTERN = re.compile(r'@(Get|Post|Put|Delete|Patch)Mapping')
|
|
22
|
+
_SUBPATH_PATTERN = re.compile(r'@(?:Get|Post|Put|Delete|Patch)Mapping\s*\(\s*"([^"]*)"')
|
|
23
|
+
_PERMISSION_CODE_PATTERN = re.compile(r'code\s*=\s*"([^"]+)"')
|
|
24
|
+
# method signature: Java public return-type name( and Kotlin fun name(
|
|
25
|
+
_METHOD_SIGNATURE_PATTERN = re.compile(r'(?:public\s+[\w<>,?.\[\] ]+|fun)\s+(\w+)\s*\(')
|
|
26
|
+
# pure annotation line (annotation only, no code)
|
|
27
|
+
_ANNOTATION_LINE_PATTERN = re.compile(r'^@\w+')
|
|
28
|
+
_OTHER_MAPPING_PATTERN = re.compile(r'@RequestMapping\s*\(\s*"([^"]*)"')
|
|
29
|
+
|
|
30
|
+
# mapper.xml statement matching
|
|
31
|
+
_SQL_STATEMENT_PATTERN = re.compile(
|
|
32
|
+
r"<(select|update|insert|delete)\s[^>]*?\bid\s*=\s*\"([^\"]+)\"[^>]*>(.*?)</\1>",
|
|
33
|
+
re.DOTALL | re.IGNORECASE,
|
|
34
|
+
)
|
|
35
|
+
_SQL_COMMENT_PATTERN = re.compile(r"<!--.*?-->", re.DOTALL)
|
|
36
|
+
# stored procedure definition matching
|
|
37
|
+
_PROC_PATTERN = re.compile(
|
|
38
|
+
r"CREATE\s+(?:OR\s+REPLACE\s+)?(?:PROC(?:EDURE)?|FUNCTION)\s+(\[?\w+\]?\.)?\[?(\w+)\]?",
|
|
39
|
+
re.IGNORECASE,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
# frontend api call matching: string literals starting with / (e.g. "/customer/expense/applypay")
|
|
43
|
+
_FRONT_API_PATTERN = re.compile(r"['\"](/[A-Za-z][A-Za-z0-9_/{}\-.]*)")
|
|
44
|
+
# frontend permission string matching (A.B.C style permission codes)
|
|
45
|
+
_FRONT_PERM_PATTERN = re.compile(r"['\"]([A-Za-z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9.\-]*)")
|
|
46
|
+
|
|
47
|
+
# ----------------------------------------------------------------- multi-language interface detection
|
|
48
|
+
# Go: gin/Gorilla/Chi/stdlib route registration (any var name + verb function)
|
|
49
|
+
_GO_ROUTE_PATTERN = re.compile(
|
|
50
|
+
r'\.\s*(GET|POST|PUT|DELETE|PATCH|Any|HandleFunc)\s*\(\s*"([^"]+)"\s*(?:,\s*([\w.]+))?',
|
|
51
|
+
re.IGNORECASE,
|
|
52
|
+
)
|
|
53
|
+
# Python: Flask/FastAPI short decorators (@app.get / @router.post) and route decorator
|
|
54
|
+
_FLASK_SHORT_PATTERN = re.compile(r'@\w+\.(get|post|put|delete|patch)\s*\(\s*["\']([^"\']+)["\']', re.IGNORECASE)
|
|
55
|
+
_FLASK_ROUTE_PATTERN = re.compile(r'@\w+\.route\s*\(\s*["\']([^"\']+)["\']')
|
|
56
|
+
# Django urls.py:path("...", view) / re_path
|
|
57
|
+
_DJANGO_PATH_PATTERN = re.compile(r'\b(?:path|re_path)\s*\(\s*["\']([^"\']+)["\']')
|
|
58
|
+
# Node.js: Express/Koa (app.get / router.post), exclude HTTP client calls (axios/http etc)
|
|
59
|
+
_NODE_ROUTE_PATTERN = re.compile(
|
|
60
|
+
r'\b(?!(?:axios|http|https|client|request|fetch|got)\b)(\w+)\.(get|post|put|delete|patch|all)\s*\(\s*["\'](/[^"\']*)["\']',
|
|
61
|
+
re.IGNORECASE,
|
|
62
|
+
)
|
|
63
|
+
# NestJS (TS): @Controller("base") + @Get("sub")/@Post() decorators (subpath optional)
|
|
64
|
+
_NEST_CONTROLLER_PATTERN = re.compile(r'@Controller\s*\(\s*["\']([^"\']*)["\']')
|
|
65
|
+
_NEST_DECORATOR_PATTERN = re.compile(r'@(Get|Post|Put|Delete|Patch)\s*(?:\(\s*["\']([^"\']*)["\']\s*\))?')
|
|
66
|
+
# C#:ASP.NET Core [HttpGet("p")] / [Route("...")] / MapGet("p")
|
|
67
|
+
_CS_ATTR_PATTERN = re.compile(r'\[Http(Get|Post|Put|Delete|Patch)(?:\s*\(\s*"([^"]*)"\s*\))?\]', re.IGNORECASE)
|
|
68
|
+
_CS_ROUTE_PATTERN = re.compile(r'\[Route\s*\(\s*"([^"]+)"\s*\)\]')
|
|
69
|
+
_CS_MAP_PATTERN = re.compile(r'\bMap(Get|Post|Put|Delete)\s*\(\s*"([^"]+)"', re.IGNORECASE)
|
|
70
|
+
# PHP:Laravel Route::get('/p', ...) / Route::match([...], '/p') / Symfony #[Route]
|
|
71
|
+
_PHP_LARAVEL_PATTERN = re.compile(r'Route::(get|post|put|delete|patch|any)\s*\(\s*["\']([^"\']+)["\']', re.IGNORECASE)
|
|
72
|
+
_PHP_LARAVEL_MATCH_PATTERN = re.compile(r'Route::match\s*\(\s*\[[^\]]*\]\s*,\s*["\']([^"\']+)["\']', re.IGNORECASE)
|
|
73
|
+
_PHP_SYMFONY_PATTERN = re.compile(
|
|
74
|
+
r'#\[Route\s*\(\s*["\']([^"\']+)["\'](?:\s*,\s*methods:\s*\[([^\]]*)\])?',
|
|
75
|
+
re.IGNORECASE,
|
|
76
|
+
)
|
|
77
|
+
# Ruby: Rails routes.rb (get/post/resources strings or symbols) / Sinatra (get '/p' do)
|
|
78
|
+
_RUBY_ROUTE_PATTERN = re.compile(
|
|
79
|
+
r'^\s*(get|post|put|delete|patch|match|root|resources)\s+(?:"([^"]+)"|\'([^\']+)\'|:(\w+))',
|
|
80
|
+
)
|
|
81
|
+
# Rust: axum .route("/p", get(handler)) / actix #[get("/p")] and web::resource
|
|
82
|
+
_RUST_AXUM_PATTERN = re.compile(r'\.route\s*\(\s*"([^"]+)"\s*,\s*(get|post|put|delete|patch)\s*\(', re.IGNORECASE)
|
|
83
|
+
_RUST_ACTIX_ATTR_PATTERN = re.compile(r'#\[(get|post|put|delete|patch)\s*\(\s*"([^"]+)"\s*\)\]', re.IGNORECASE)
|
|
84
|
+
_RUST_ACTIX_RES_PATTERN = re.compile(
|
|
85
|
+
r'web::resource\s*\(\s*"([^"]+)"\s*\)\.route\s*\(\s*web::(get|post|put|delete|patch)\s*\(',
|
|
86
|
+
re.IGNORECASE,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
# ----------------------------------------------------------------- generic SQL string extraction
|
|
90
|
+
# SQL keyword (matched at string content start)
|
|
91
|
+
_SQL_KEYWORD = re.compile(r'(SELECT|INSERT|UPDATE|DELETE)\s', re.IGNORECASE)
|
|
92
|
+
# concatenated fragments "x" + "y" normalized into a space
|
|
93
|
+
_SQL_CONCAT_PATTERN = re.compile(r'["\']\s*\+\s*["\']')
|
|
94
|
+
|
|
95
|
+
# default scan extensions
|
|
96
|
+
JAVA_EXT = ".java"
|
|
97
|
+
XML_EXT = ".xml"
|
|
98
|
+
SQL_EXT = ".sql"
|
|
99
|
+
PY_EXT = ".py"
|
|
100
|
+
TS_EXT = ".ts"
|
|
101
|
+
GO_EXT = ".go"
|
|
102
|
+
FRONT_EXTS = (".vue", ".js", ".ts", ".html", ".jsx", ".tsx")
|
|
103
|
+
# enum & middleware scan extensions
|
|
104
|
+
_ENUM_MW_EXTS = (JAVA_EXT, PY_EXT, TS_EXT, GO_EXT, ".kt", ".tsx", ".js", ".jsx", ".vue")
|
|
105
|
+
|
|
106
|
+
# backend language dispatch: extension -> interface scanner
|
|
107
|
+
_LANG_SCANNERS = {
|
|
108
|
+
".java": "_scan_java",
|
|
109
|
+
".kt": "_scan_java",
|
|
110
|
+
".go": "_scan_go",
|
|
111
|
+
".py": "_scan_python",
|
|
112
|
+
".js": "_scan_node",
|
|
113
|
+
".ts": "_scan_node",
|
|
114
|
+
".mjs": "_scan_node",
|
|
115
|
+
".cjs": "_scan_node",
|
|
116
|
+
".cs": "_scan_csharp",
|
|
117
|
+
".php": "_scan_php",
|
|
118
|
+
".rb": "_scan_ruby",
|
|
119
|
+
".rs": "_scan_rust",
|
|
120
|
+
}
|
|
121
|
+
# backend language extensions eligible for generic SQL string extraction
|
|
122
|
+
_SQL_CODE_EXTS = frozenset(_LANG_SCANNERS)
|
|
123
|
+
|
|
124
|
+
# scan cap (avoid huge repos dragging the scan)
|
|
125
|
+
MAX_FILES = 5000
|
|
126
|
+
|
|
127
|
+
# file line count cache (risk-driven: interface entries carry lines field)
|
|
128
|
+
_FILE_LINES_CACHE = {}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _file_lines(path):
|
|
132
|
+
"""File line count (cached, for risk-driven use)."""
|
|
133
|
+
if path not in _FILE_LINES_CACHE:
|
|
134
|
+
try:
|
|
135
|
+
with open(path, "r", encoding="utf-8", errors="replace") as fp:
|
|
136
|
+
_FILE_LINES_CACHE[path] = len(fp.readlines())
|
|
137
|
+
except OSError:
|
|
138
|
+
_FILE_LINES_CACHE[path] = 0
|
|
139
|
+
return _FILE_LINES_CACHE[path]
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _read_text(path, limit=200000):
|
|
143
|
+
"""Read a text file (multi-encoding fallback)."""
|
|
144
|
+
for encoding in ("utf-8", "gbk", "latin-1"):
|
|
145
|
+
try:
|
|
146
|
+
with open(path, "r", encoding=encoding) as fp:
|
|
147
|
+
return fp.read(limit)
|
|
148
|
+
except (UnicodeDecodeError, UnicodeError):
|
|
149
|
+
continue
|
|
150
|
+
return ""
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _walk_files(repo_path):
|
|
154
|
+
"""Walk repo files, skipping hidden dirs and build output dirs."""
|
|
155
|
+
skip_dirs = {".git", ".idea", ".venv", "target", "build", "node_modules", "__pycache__", "dist"}
|
|
156
|
+
count = 0
|
|
157
|
+
for root, dirs, files in os.walk(repo_path):
|
|
158
|
+
dirs[:] = [d for d in dirs if d not in skip_dirs]
|
|
159
|
+
for name in files:
|
|
160
|
+
if count >= MAX_FILES:
|
|
161
|
+
return
|
|
162
|
+
count += 1
|
|
163
|
+
yield os.path.join(root, name)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def scan_repo(repo_path):
|
|
167
|
+
"""Scan the code repo, return structured facts.
|
|
168
|
+
|
|
169
|
+
:param repo_path: repo root directory
|
|
170
|
+
:return: {"interfaces": [...], "sqls": [...], "stored_procs": [...]}
|
|
171
|
+
"""
|
|
172
|
+
if not os.path.isdir(repo_path):
|
|
173
|
+
raise ValueError("仓库路径不存在: %s" % repo_path)
|
|
174
|
+
|
|
175
|
+
interfaces = []
|
|
176
|
+
sqls = []
|
|
177
|
+
stored_procs = []
|
|
178
|
+
enums = []
|
|
179
|
+
middlewares = []
|
|
180
|
+
|
|
181
|
+
for path in _walk_files(repo_path):
|
|
182
|
+
ext = os.path.splitext(path)[1].lower()
|
|
183
|
+
scanner = _LANG_SCANNERS.get(ext)
|
|
184
|
+
if scanner:
|
|
185
|
+
interfaces.extend(globals()[scanner](path))
|
|
186
|
+
elif ext == XML_EXT:
|
|
187
|
+
sqls.extend(_scan_mapper_xml(path))
|
|
188
|
+
elif ext == SQL_EXT:
|
|
189
|
+
stored_procs.extend(_scan_sql_file(path))
|
|
190
|
+
if ext in _SQL_CODE_EXTS:
|
|
191
|
+
sqls.extend(_scan_sql_strings_file(path))
|
|
192
|
+
if ext in _ENUM_MW_EXTS:
|
|
193
|
+
enums.extend(_scan_enums(path, ext))
|
|
194
|
+
middlewares.extend(_scan_middlewares(path, ext))
|
|
195
|
+
|
|
196
|
+
return {"interfaces": interfaces, "sqls": sqls, "stored_procs": stored_procs,
|
|
197
|
+
"enums": enums, "middlewares": middlewares}
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _scan_java(path):
|
|
201
|
+
"""Scan a Java file, extract controller interface list (line-by-line state machine).
|
|
202
|
+
|
|
203
|
+
states: HTTP annotation (@GetMapping etc) -> optional @PermissionFunction multi-line annotation -> public method signature.
|
|
204
|
+
"""
|
|
205
|
+
text = _read_text(path)
|
|
206
|
+
if "@RestController" not in text and "@Controller" not in text:
|
|
207
|
+
return []
|
|
208
|
+
results = []
|
|
209
|
+
base = ""
|
|
210
|
+
# class-level path: @RequestMapping before the class declaration (value= spelling compatible)
|
|
211
|
+
class_idx = text.find("class ")
|
|
212
|
+
class_pattern = re.compile(
|
|
213
|
+
r'@RequestMapping\s*\(\s*(?:value\s*=\s*)?"([^"]+)"',
|
|
214
|
+
)
|
|
215
|
+
for match in class_pattern.finditer(text):
|
|
216
|
+
if class_idx == -1 or match.start() < class_idx:
|
|
217
|
+
base = match.group(1)
|
|
218
|
+
break
|
|
219
|
+
|
|
220
|
+
pending_method = None
|
|
221
|
+
pending_subpath = ""
|
|
222
|
+
pending_permission = ""
|
|
223
|
+
in_permission = False
|
|
224
|
+
perm_buffer = []
|
|
225
|
+
|
|
226
|
+
for line in text.split("\n"):
|
|
227
|
+
stripped = line.strip()
|
|
228
|
+
if in_permission:
|
|
229
|
+
perm_buffer.append(stripped)
|
|
230
|
+
if stripped.endswith(")"):
|
|
231
|
+
in_permission = False
|
|
232
|
+
joined = "\n".join(perm_buffer)
|
|
233
|
+
match = _PERMISSION_CODE_PATTERN.search(joined)
|
|
234
|
+
pending_permission = match.group(1) if match else ""
|
|
235
|
+
continue
|
|
236
|
+
if stripped.startswith("@PermissionFunction"):
|
|
237
|
+
if stripped.endswith(")"):
|
|
238
|
+
match = _PERMISSION_CODE_PATTERN.search(stripped)
|
|
239
|
+
pending_permission = match.group(1) if match else ""
|
|
240
|
+
else:
|
|
241
|
+
in_permission = True
|
|
242
|
+
perm_buffer = [stripped]
|
|
243
|
+
continue
|
|
244
|
+
mapping = _METHOD_MAPPING_PATTERN.match(stripped)
|
|
245
|
+
if mapping and not stripped.startswith("@RequestMapping"):
|
|
246
|
+
pending_method = mapping.group(1).upper()
|
|
247
|
+
sub = _SUBPATH_PATTERN.search(stripped)
|
|
248
|
+
pending_subpath = sub.group(1) if sub else ""
|
|
249
|
+
continue
|
|
250
|
+
signature = _METHOD_SIGNATURE_PATTERN.match(stripped)
|
|
251
|
+
if signature and pending_method:
|
|
252
|
+
# normalized URL join: exactly one / between base and subpath
|
|
253
|
+
if base and pending_subpath:
|
|
254
|
+
url = base.rstrip("/") + "/" + pending_subpath.lstrip("/")
|
|
255
|
+
else:
|
|
256
|
+
url = base or pending_subpath
|
|
257
|
+
results.append(_make_iface(
|
|
258
|
+
path, pending_method, url,
|
|
259
|
+
name=signature.group(1), permission=pending_permission,
|
|
260
|
+
))
|
|
261
|
+
pending_method = None
|
|
262
|
+
pending_subpath = ""
|
|
263
|
+
pending_permission = ""
|
|
264
|
+
return results
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _make_iface(path, method, url, name="", permission=""):
|
|
268
|
+
"""Build a unified interface entry (with file line count, for risk-driven use)."""
|
|
269
|
+
return {
|
|
270
|
+
"file": os.path.basename(path),
|
|
271
|
+
"method": method,
|
|
272
|
+
"url": url,
|
|
273
|
+
"name": name,
|
|
274
|
+
"permission": permission,
|
|
275
|
+
"lines": _file_lines(path),
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _scan_go(path):
|
|
280
|
+
"""Scan Go: gin/Gorilla/Chi/stdlib route registration."""
|
|
281
|
+
text = _read_text(path)
|
|
282
|
+
results = []
|
|
283
|
+
for match in _GO_ROUTE_PATTERN.finditer(text):
|
|
284
|
+
verb = match.group(1).upper()
|
|
285
|
+
method = verb if verb in ("GET", "POST", "PUT", "DELETE", "PATCH") else "*"
|
|
286
|
+
results.append(_make_iface(path, method, match.group(2), name=match.group(3) or ""))
|
|
287
|
+
return results
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _scan_python(path):
|
|
291
|
+
"""Scan Python: Flask/FastAPI decorators and Django urls."""
|
|
292
|
+
text = _read_text(path)
|
|
293
|
+
results = []
|
|
294
|
+
seen = set()
|
|
295
|
+
for match in _FLASK_SHORT_PATTERN.finditer(text):
|
|
296
|
+
url = match.group(2)
|
|
297
|
+
results.append(_make_iface(path, match.group(1).upper(), url))
|
|
298
|
+
seen.add((match.group(1).upper(), url))
|
|
299
|
+
for match in _FLASK_ROUTE_PATTERN.finditer(text):
|
|
300
|
+
url = match.group(1)
|
|
301
|
+
if ("*", url) not in seen:
|
|
302
|
+
results.append(_make_iface(path, "*", url))
|
|
303
|
+
seen.add(("*", url))
|
|
304
|
+
for match in _DJANGO_PATH_PATTERN.finditer(text):
|
|
305
|
+
url = match.group(1)
|
|
306
|
+
if ("*", url) not in seen:
|
|
307
|
+
results.append(_make_iface(path, "*", url))
|
|
308
|
+
seen.add(("*", url))
|
|
309
|
+
return results
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _scan_node(path):
|
|
313
|
+
"""Scan Node.js/TS: Express/Koa style and NestJS decorators."""
|
|
314
|
+
text = _read_text(path)
|
|
315
|
+
results = []
|
|
316
|
+
# NestJS: @Controller base path + @Get/@Post subpaths
|
|
317
|
+
controller = _NEST_CONTROLLER_PATTERN.search(text)
|
|
318
|
+
if controller:
|
|
319
|
+
base = (controller.group(1) or "").strip("/")
|
|
320
|
+
for match in _NEST_DECORATOR_PATTERN.finditer(text):
|
|
321
|
+
sub = (match.group(2) or "").strip("/")
|
|
322
|
+
url = ("/" + base + "/" + sub).rstrip("/") if sub else ("/" + base)
|
|
323
|
+
results.append(_make_iface(path, match.group(1).upper(), url))
|
|
324
|
+
# Express/Koa:app.get("/p", fn)
|
|
325
|
+
for match in _NODE_ROUTE_PATTERN.finditer(text):
|
|
326
|
+
results.append(_make_iface(path, match.group(2).upper(), match.group(3)))
|
|
327
|
+
return results
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _scan_csharp(path):
|
|
331
|
+
"""Scan C#: ASP.NET Core [HttpGet("p")]/[Route("...")]/MapGet("p")."""
|
|
332
|
+
text = _read_text(path)
|
|
333
|
+
results = []
|
|
334
|
+
# class-level Route prefix (first [Route] before the class declaration)
|
|
335
|
+
base = ""
|
|
336
|
+
class_idx = text.find("class ")
|
|
337
|
+
for match in _CS_ROUTE_PATTERN.finditer(text):
|
|
338
|
+
if class_idx == -1 or match.start() < class_idx:
|
|
339
|
+
base = match.group(1)
|
|
340
|
+
break
|
|
341
|
+
for match in _CS_ATTR_PATTERN.finditer(text):
|
|
342
|
+
method = match.group(1).upper()
|
|
343
|
+
sub = match.group(2) or ""
|
|
344
|
+
if sub:
|
|
345
|
+
url = (base.rstrip("/") + "/" + sub.lstrip("/")).rstrip("/")
|
|
346
|
+
else:
|
|
347
|
+
url = base
|
|
348
|
+
results.append(_make_iface(path, method, url))
|
|
349
|
+
for match in _CS_MAP_PATTERN.finditer(text):
|
|
350
|
+
results.append(_make_iface(path, match.group(1).upper(), match.group(2)))
|
|
351
|
+
return results
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _scan_php(path):
|
|
355
|
+
"""Scan PHP: Laravel Route::get/match and Symfony #[Route]."""
|
|
356
|
+
text = _read_text(path)
|
|
357
|
+
results = []
|
|
358
|
+
for match in _PHP_LARAVEL_PATTERN.finditer(text):
|
|
359
|
+
results.append(_make_iface(path, match.group(1).upper(), match.group(2)))
|
|
360
|
+
for match in _PHP_LARAVEL_MATCH_PATTERN.finditer(text):
|
|
361
|
+
results.append(_make_iface(path, "MATCH", match.group(1)))
|
|
362
|
+
for match in _PHP_SYMFONY_PATTERN.finditer(text):
|
|
363
|
+
method = "*"
|
|
364
|
+
methods = match.group(2) or ""
|
|
365
|
+
verb = re.search(r"['\"](\w+)['\"]", methods)
|
|
366
|
+
if verb:
|
|
367
|
+
method = verb.group(1).upper()
|
|
368
|
+
results.append(_make_iface(path, method, match.group(1)))
|
|
369
|
+
return results
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _scan_ruby(path):
|
|
373
|
+
"""Scan Ruby: Rails routes.rb and Sinatra style."""
|
|
374
|
+
text = _read_text(path)
|
|
375
|
+
results = []
|
|
376
|
+
for line in text.split("\n"):
|
|
377
|
+
match = _RUBY_ROUTE_PATTERN.search(line)
|
|
378
|
+
if not match:
|
|
379
|
+
continue
|
|
380
|
+
verb = match.group(1)
|
|
381
|
+
method = verb.upper() if verb not in ("resources", "root") else "*"
|
|
382
|
+
url = match.group(2) or match.group(3) or (":" + (match.group(4) or ""))
|
|
383
|
+
results.append(_make_iface(path, method, url))
|
|
384
|
+
return results
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _scan_rust(path):
|
|
388
|
+
"""Scan Rust: axum .route and actix #[get]/web::resource."""
|
|
389
|
+
text = _read_text(path)
|
|
390
|
+
results = []
|
|
391
|
+
for match in _RUST_AXUM_PATTERN.finditer(text):
|
|
392
|
+
results.append(_make_iface(path, match.group(2).upper(), match.group(1)))
|
|
393
|
+
for match in _RUST_ACTIX_ATTR_PATTERN.finditer(text):
|
|
394
|
+
results.append(_make_iface(path, match.group(1).upper(), match.group(2)))
|
|
395
|
+
for match in _RUST_ACTIX_RES_PATTERN.finditer(text):
|
|
396
|
+
results.append(_make_iface(path, match.group(2).upper(), match.group(1)))
|
|
397
|
+
return results
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _extract_sql_strings(text):
|
|
401
|
+
"""Extract string constants starting with a SQL keyword from source text (generic heuristic).
|
|
402
|
+
|
|
403
|
+
supports single/double quotes, Python triple quotes, Go/JS backticks and JS template strings;
|
|
404
|
+
simple string concatenation (+) fragments normalized to a space.
|
|
405
|
+
"""
|
|
406
|
+
results = []
|
|
407
|
+
seen_starts = set()
|
|
408
|
+
for match in _SQL_KEYWORD.finditer(text):
|
|
409
|
+
start = match.start()
|
|
410
|
+
# scan backward for the nearest string start quote
|
|
411
|
+
candidates = [text.rfind('"', 0, start), text.rfind("'", 0, start), text.rfind("`", 0, start)]
|
|
412
|
+
begin = max(candidates)
|
|
413
|
+
if begin < 0:
|
|
414
|
+
continue
|
|
415
|
+
# triple quotes / template triple backticks
|
|
416
|
+
triple = text[begin:begin + 3]
|
|
417
|
+
quote = text[begin]
|
|
418
|
+
if triple in ('"""', "'''", "```"):
|
|
419
|
+
end = text.find(triple, begin + 3)
|
|
420
|
+
content = text[begin + 3:end] if end >= 0 else ""
|
|
421
|
+
else:
|
|
422
|
+
end = text.find(quote, begin + 1)
|
|
423
|
+
content = text[begin + 1:end] if end >= 0 else ""
|
|
424
|
+
content = content.lstrip()
|
|
425
|
+
if not _SQL_KEYWORD.match(content):
|
|
426
|
+
continue
|
|
427
|
+
if begin in seen_starts:
|
|
428
|
+
continue
|
|
429
|
+
seen_starts.add(begin)
|
|
430
|
+
# concatenation normalization + whitespace squeeze
|
|
431
|
+
sql = _SQL_CONCAT_PATTERN.sub(" ", content)
|
|
432
|
+
sql = re.sub(r"\s+", " ", sql).strip()
|
|
433
|
+
if 10 < len(sql):
|
|
434
|
+
results.append(sql)
|
|
435
|
+
return results
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _scan_sql_strings_file(path):
|
|
439
|
+
"""扫描源码文件中的 SQL 字符串常量。"""
|
|
440
|
+
text = _read_text(path)
|
|
441
|
+
base = os.path.basename(path)
|
|
442
|
+
results = []
|
|
443
|
+
index = 0
|
|
444
|
+
for sql in _extract_sql_strings(text):
|
|
445
|
+
index += 1
|
|
446
|
+
results.append({"file": base, "id": "%s#%d" % (base, index), "sql": sql[:1500]})
|
|
447
|
+
return results
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def _scan_mapper_xml(path):
|
|
451
|
+
"""扫描 mapper.xml,抽取 SQL 字典(id -> 清洗后 SQL)。"""
|
|
452
|
+
text = _read_text(path)
|
|
453
|
+
if "<mapper" not in text:
|
|
454
|
+
return []
|
|
455
|
+
clean = _SQL_COMMENT_PATTERN.sub("", text)
|
|
456
|
+
results = []
|
|
457
|
+
for match in _SQL_STATEMENT_PATTERN.finditer(clean):
|
|
458
|
+
sql_id = match.group(2)
|
|
459
|
+
sql = re.sub(r"\s+", " ", match.group(3)).strip()
|
|
460
|
+
# 压缩参数占位,便于阅读
|
|
461
|
+
sql = sql.replace("#{", "{").replace("${", "{")
|
|
462
|
+
results.append({"file": os.path.basename(path), "id": sql_id, "sql": sql[:1500]})
|
|
463
|
+
return results
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _scan_sql_file(path):
|
|
467
|
+
"""扫描 .sql 文件,抽取存储过程定义。"""
|
|
468
|
+
text = _read_text(path)
|
|
469
|
+
results = []
|
|
470
|
+
for match in _PROC_PATTERN.finditer(text):
|
|
471
|
+
name = match.group(2)
|
|
472
|
+
start = match.start()
|
|
473
|
+
# 取定义开头 2000 字符(含签名与关键注释)
|
|
474
|
+
snippet = re.sub(r"\s+", " ", text[start:start + 2000]).strip()
|
|
475
|
+
results.append({"file": os.path.basename(path), "name": name, "sql": snippet})
|
|
476
|
+
return results
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def scan_frontend(repo_path):
|
|
480
|
+
"""扫描前端项目(.vue/.js/.ts/.html/.jsx/.tsx),抽取页面/接口调用/权限点事实。
|
|
481
|
+
|
|
482
|
+
:param repo_path: 前端项目根目录
|
|
483
|
+
:return: {"pages": [{"file": 相对路径, "api_calls": [url], "permissions": [权限点]}]}
|
|
484
|
+
"""
|
|
485
|
+
if not os.path.isdir(repo_path):
|
|
486
|
+
raise ValueError("前端项目路径不存在: %s" % repo_path)
|
|
487
|
+
pages = []
|
|
488
|
+
for path in _walk_files(repo_path):
|
|
489
|
+
ext = os.path.splitext(path)[1].lower()
|
|
490
|
+
if ext not in FRONT_EXTS:
|
|
491
|
+
continue
|
|
492
|
+
text = _read_text(path)
|
|
493
|
+
api_calls = []
|
|
494
|
+
seen_apis = set()
|
|
495
|
+
for match in _FRONT_API_PATTERN.finditer(text):
|
|
496
|
+
url = match.group(1)
|
|
497
|
+
if url not in seen_apis:
|
|
498
|
+
seen_apis.add(url)
|
|
499
|
+
api_calls.append(url)
|
|
500
|
+
permissions = []
|
|
501
|
+
seen_perms = set()
|
|
502
|
+
for match in _FRONT_PERM_PATTERN.finditer(text):
|
|
503
|
+
perm = match.group(1)
|
|
504
|
+
if perm not in seen_perms:
|
|
505
|
+
seen_perms.add(perm)
|
|
506
|
+
permissions.append(perm)
|
|
507
|
+
if api_calls or permissions:
|
|
508
|
+
pages.append(
|
|
509
|
+
{
|
|
510
|
+
"file": os.path.relpath(path, repo_path),
|
|
511
|
+
"api_calls": api_calls,
|
|
512
|
+
"permissions": permissions,
|
|
513
|
+
}
|
|
514
|
+
)
|
|
515
|
+
return {"pages": pages}
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def dump_facts(facts, output):
|
|
519
|
+
"""把扫描事实写入 JSON 文件。
|
|
520
|
+
|
|
521
|
+
:param facts: scan_repo 结果
|
|
522
|
+
:param output: 输出路径
|
|
523
|
+
"""
|
|
524
|
+
with open(output, "w", encoding="utf-8") as fp:
|
|
525
|
+
json.dump(facts, fp, ensure_ascii=False, indent=2, default=str)
|
|
526
|
+
return output
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
def load_facts(path):
|
|
530
|
+
"""读取扫描事实 JSON 文件。
|
|
531
|
+
|
|
532
|
+
:param path: JSON 文件路径
|
|
533
|
+
:return: 结构化事实 dict
|
|
534
|
+
"""
|
|
535
|
+
with open(path, "r", encoding="utf-8") as fp:
|
|
536
|
+
return json.load(fp)
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
# ---------------------------------------------------------------- enums & middlewares
|
|
540
|
+
|
|
541
|
+
_ENUM_BLOCK_PATTERN = re.compile(
|
|
542
|
+
r"enum\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]*)\}", re.DOTALL,
|
|
543
|
+
)
|
|
544
|
+
_PY_ENUM_PATTERN = re.compile(
|
|
545
|
+
r"class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*Enum[^)]*)\):\s*(?:[\s\S]*?)(?=class\s|def\s|$)",
|
|
546
|
+
)
|
|
547
|
+
_STATUS_CONST_PATTERN = re.compile(
|
|
548
|
+
"|".join([
|
|
549
|
+
r"public\s+static\s+final\s+\w+\s+(\w+)\s*=\s*(\d+)",
|
|
550
|
+
r"(\w+)\s*=\s*(\d+)\s*[,;]",
|
|
551
|
+
])
|
|
552
|
+
)
|
|
553
|
+
_MQ_PATTERNS = (
|
|
554
|
+
re.compile(r"@(?:RabbitListener|KafkaListener|JmsListener|SqsListener)", re.IGNORECASE),
|
|
555
|
+
re.compile(r"\.(?:produce|publish|send)\s*\(", re.IGNORECASE),
|
|
556
|
+
re.compile(r"(?:rabbitTemplate|kafkaTemplate|jmsTemplate|producer)\s*\.", re.IGNORECASE),
|
|
557
|
+
re.compile(r"\.(?:receive|subscribe|consume)\s*\(", re.IGNORECASE),
|
|
558
|
+
re.compile(r"@(?:Scheduled|cron)\s*\(", re.IGNORECASE),
|
|
559
|
+
re.compile(r"cron\s*=\s*[\"']([^\"']+)[\"']", re.IGNORECASE),
|
|
560
|
+
re.compile(r"@(?:Cacheable|CachePut|CacheEvict)", re.IGNORECASE),
|
|
561
|
+
re.compile(r"\.(?:cache|redisCache|put|setex|incr|decr)\s*\(", re.IGNORECASE),
|
|
562
|
+
re.compile(r"@(?:Transactional|Retryable)", re.IGNORECASE),
|
|
563
|
+
re.compile(r"(?<!\w)(?:CACHE_|REDIS_|MQ_|TOPIC_|QUEUE_)[A-Z0-9_]{2,}", re.IGNORECASE),
|
|
564
|
+
)
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def _scan_enums(path, ext):
|
|
568
|
+
"""提取状态枚举:enum 块 / Python Enum 类 / 状态常量组。"""
|
|
569
|
+
text = _read_text(path)
|
|
570
|
+
enums = []
|
|
571
|
+
for match in _ENUM_BLOCK_PATTERN.finditer(text):
|
|
572
|
+
body = match.group(2)
|
|
573
|
+
values = re.findall(r"([A-Z][A-Z0-9_]*)\s*[,(]", body)
|
|
574
|
+
if values:
|
|
575
|
+
enums.append({"name": match.group(1), "values": values,
|
|
576
|
+
"file": os.path.basename(path)})
|
|
577
|
+
for match in _PY_ENUM_PATTERN.finditer(text):
|
|
578
|
+
values = re.findall(r"^\s*([A-Z][A-Z0-9_]*)\s*=", text[match.end():], re.MULTILINE)
|
|
579
|
+
if values:
|
|
580
|
+
enums.append({"name": match.group(1), "values": values[:20],
|
|
581
|
+
"file": os.path.basename(path)})
|
|
582
|
+
return enums
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def _scan_middlewares(path, ext):
|
|
586
|
+
"""提取中间件证据:MQ 生产/消费、定时任务 cron、缓存与键常量。"""
|
|
587
|
+
text = _read_text(path)
|
|
588
|
+
results = []
|
|
589
|
+
for pattern in _MQ_PATTERNS:
|
|
590
|
+
for match in pattern.finditer(text):
|
|
591
|
+
value = ""
|
|
592
|
+
if match.lastindex and match.lastindex >= 1:
|
|
593
|
+
try:
|
|
594
|
+
value = match.group(1) or ""
|
|
595
|
+
except IndexError:
|
|
596
|
+
value = ""
|
|
597
|
+
entry = {"kind": _middleware_kind(pattern), "match": match.group(0)[:80],
|
|
598
|
+
"value": value, "file": os.path.basename(path)}
|
|
599
|
+
if entry not in results:
|
|
600
|
+
results.append(entry)
|
|
601
|
+
return results
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def _middleware_kind(pattern):
|
|
605
|
+
source = pattern.pattern
|
|
606
|
+
if "Listener" in source or "consume" in source or "subscribe" in source or "receive" in source:
|
|
607
|
+
return "MQ消费"
|
|
608
|
+
if "produce" in source or "publish" in source or "Template" in source or "producer" in source or "send" in source:
|
|
609
|
+
return "MQ生产"
|
|
610
|
+
if "Scheduled" in source or "cron" in source:
|
|
611
|
+
return "定时任务"
|
|
612
|
+
if "Cache" in source or "cache" in source or "redisCache" in source or "setex" in source:
|
|
613
|
+
return "缓存"
|
|
614
|
+
if "Transactional" in source or "Retryable" in source:
|
|
615
|
+
return "事务/重试"
|
|
616
|
+
return "键常量"
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def count_facts(facts):
|
|
620
|
+
"""统计事实条目数(输出摘要用)。
|
|
621
|
+
|
|
622
|
+
:param facts: 结构化事实 dict
|
|
623
|
+
:return: {"interfaces": n, "sqls": n, "stored_procs": n, "enums": n, "middlewares": n}
|
|
624
|
+
"""
|
|
625
|
+
return {
|
|
626
|
+
"interfaces": len(facts.get("interfaces") or []),
|
|
627
|
+
"sqls": len(facts.get("sqls") or []),
|
|
628
|
+
"stored_procs": len(facts.get("stored_procs") or []),
|
|
629
|
+
"enums": len(facts.get("enums") or []),
|
|
630
|
+
"middlewares": len(facts.get("middlewares") or []),
|
|
631
|
+
}
|