Files
crawler-plugin/backend-java/src/test/java/com/nanri/aiimage/testutil/SourceScan.java
T

297 lines
13 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.nanri.aiimage.testutil;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/** 源码扫描式护栏的取文助手。<b>路径解析照抄 {@code common/security/InternalTokenSingleOutletTest} 的
* moduleRoot()/mainSources() 两支</b>——surefire 的 cwd 是模块目录,从仓库根或 IDE 跑时要退到 backend-java/,
* 定位不到必须 fail 而不是静默跳过(静默跳过 = 整支护栏恒绿)。 */
public final class SourceScan {
private SourceScan() {
}
/** 一处 {@code sourceText("<裸名>")} 字面量点名。 */
public record CallSite(String bareName, String relativeFile, int line) {
}
private static final Pattern CALL_SITE = Pattern.compile("sourceText\\(\\s*\"([^\"]+)\"\\s*\\)");
/** {@code src/test/java} 的绝对根,与 {@link #mainSources()} 同一条定位分支。 */
public static Path testSourcesRoot() {
Path root = moduleRoot().resolve("src/test/java");
if (!Files.isDirectory(root)) {
throw new IllegalStateException("语料根不存在: " + root + "(cwd=" + Path.of("").toAbsolutePath() + ")");
}
return root;
}
/** 点名普查:列出 {@code src/test/java} 里每一处 {@code sourceText("<裸名>")} 字面量调用。 */
public static List<CallSite> censusSourceTextCallSites() {
return censusSourceTextCallSites(testSourcesRoot());
}
/**
* 点名普查(可指定语料根)。三条设计决定都是被坑逼出来的:
* <ol>
* <li><b>数的是代码不是文字</b>:判据打在 {@link #withoutComments} 上,注释里提一句
* {@code sourceText("Fake.java")} 不计入——否则台账的 15 会被 javadoc 喂成任意大的数。</li>
* <li><b>只配字面量</b>:正则要求紧跟一对引号,所以 {@code SourceScan.java:22} 那行
* 被调方自己的声明(参数是 {@code String fileName})天然不算调用点。plan 原文的「9 支文件」
* 正是 {@code grep -rl 'sourceText('} 把声明也算了进去;真实调用点是 15 处/8 支文件。</li>
* <li><b>语料根不存在必须抛</b>,不许返回空表:空表会被读成「已经没人用裸名口径了」。
* 目录存在且确实没有 {@code .java} 才返回空——那是"语料真的没了",与"尺子架错地方"是两回事。</li>
* </ol>
*/
public static List<CallSite> censusSourceTextCallSites(Path corpusRoot) {
Path root = corpusRoot.toAbsolutePath();
if (!Files.isDirectory(root)) {
throw new IllegalStateException("语料根不存在: " + root + "(cwd=" + Path.of("").toAbsolutePath() + ")");
}
Path base = moduleRoot();
List<CallSite> sites = new java.util.ArrayList<>();
try (Stream<Path> walk = Files.walk(root)) {
List<Path> files = walk.filter(Files::isRegularFile)
.filter(p -> p.getFileName().toString().endsWith(".java"))
.sorted(java.util.Comparator.comparing(p -> relativizeForCensus(p, root, base).replace('\\', '/')))
.toList();
for (Path file : files) {
String code = withoutComments(read(file));
String relative = relativizeForCensus(file, root, base).replace('\\', '/');
Matcher matcher = CALL_SITE.matcher(code);
while (matcher.find()) {
sites.add(new CallSite(matcher.group(1), relative, lineAt(code, matcher.start())));
}
}
} catch (IOException e) {
throw new IllegalStateException("遍历 " + root + " 失败: " + e.getMessage(), e);
}
return List.copyOf(sites);
}
private static String relativizeForCensus(Path file, Path corpusRoot, Path moduleRoot) {
Path absolute = file.toAbsolutePath();
if (absolute.startsWith(moduleRoot)) {
return moduleRoot.relativize(absolute).toString();
}
return corpusRoot.relativize(absolute).toString();
}
/** 偏移不变的 {@link #withoutComments} 保证:剥完再数换行,行号仍等于原文件行号。 */
private static int lineAt(String code, int offset) {
int line = 1;
for (int i = 0; i < offset; i++) {
if (code.charAt(i) == '\n') {
line++;
}
}
return line;
}
/** 按文件名(不含目录)取 {@code src/main/java} 下那份源码的<b>全文字符串</b>。
* ⚠️ 返回 String,与 InternalTokenSingleOutletTest 里那个返回 Path 的私有 {@code sourceOf} 不是一回事,
* 别指望复用它的——那个是 private。 */
public static String sourceText(String fileName) {
return mainSources().stream()
.filter(p -> p.getFileName().toString().equals(fileName))
.findFirst()
.map(SourceScan::read)
.orElseThrow(() -> new IllegalStateException(
"src/main/java 下找不到 " + fileName + " —— 文件改名/挪目录了,护栏要红在这里"));
}
/**
* 剥掉注释,<b>偏移不变</b>:注释字符换成空格、换行原样保留,所以 {@link #methodBody} 这类
* 按位置切片的助手在剥前剥后切出同一段。
*
* <p>为什么护栏必须打在它上面:源码守卫的两种断言都会被<b>文字</b>喂到——
* 「必须不存在」那一形会被注释里提一句顶红(假红,还能忍),
* 「必须存在/次数等于 N」那一形会被 javadoc 里提一句<b>喂饱</b>(假绿,等于护栏没写)。
* 2026-10-07 实测:{@code AdminTaskCenterController} 的类注释里有 1 处 {@code readScope(},
* 整份原文 {@code readScope(} 数=1、剥完=0——文件级判据吃原文就会读出这种数。</p>
*
* <p>口径:{@code //} 到行尾、{@code /* … *}{@code /} 整段、字符串与字符字面量里的斜杠不算注释、
* 三个双引号的文本块按字面量整段保留。</p>
*/
public static String withoutComments(String java) {
StringBuilder out = new StringBuilder(java.length());
int i = 0;
int n = java.length();
while (i < n) {
char c = java.charAt(i);
char next = i + 1 < n ? java.charAt(i + 1) : '\0';
if (c == '/' && next == '/') {
while (i < n && java.charAt(i) != '\n') {
out.append(' ');
i++;
}
} else if (c == '/' && next == '*') {
out.append(" ");
i += 2;
while (i < n) {
if (java.charAt(i) == '*' && i + 1 < n && java.charAt(i + 1) == '/') {
out.append(" ");
i += 2;
break;
}
out.append(java.charAt(i) == '\n' ? '\n' : ' ');
i++;
}
} else if (java.startsWith("\"\"\"", i)) {
out.append("\"\"\"");
i += 3;
while (i < n && !java.startsWith("\"\"\"", i)) {
out.append(java.charAt(i));
i++;
}
out.append("\"\"\"");
i += 3;
} else if (c == '"' || c == '\'') {
out.append(c);
i++;
while (i < n) {
if (java.charAt(i) == '\\' && i + 1 < n) {
out.append(java.charAt(i)).append(java.charAt(i + 1));
i += 2;
continue;
}
if (java.charAt(i) == '\n') {
break;
}
out.append(java.charAt(i));
boolean closing = java.charAt(i) == c;
i++;
if (closing) {
break;
}
}
} else {
out.append(c);
i++;
}
}
return out.toString();
}
/** 大括号配平切出「某个方法」的源码:<b>从它的签名行往前一直含到注解</b>,到方法收尾的 `}` 为止。
*
* <p>两条它必须自己防住的坑,都写在用例里过:</p>
* <ul>
* <li><b>名字必须是完整词</b>:{@code delete} 是 {@code deleteGroup} 的前缀。用 {@code indexOf(name)}
* 会先撞上那个更长的方法 ⇒ "切出来的是隔壁",而断言仍然绿。所以下面用 {@code (?<![A-Za-z0-9_])} 卡左边界,
* 并且要求紧跟 {@code (}(构造器/局部变量名同前缀也不算方法)。</li>
* <li><b>找不到必须抛</b>,不许返回空串:返回 "" 的话 {@code doesNotContain("company_id")} 恒真,
* 反向钉会因为方法被改名而悄悄失效(memory「字符串断言必须排他、解析断言必须可匹配」)。
* 配套要求:每个用它的反向钉都要带一条"该做的确实做了"的取样自检。</li>
* </ul>
*/
public static String methodBody(String source, String methodName) {
var matcher = java.util.regex.Pattern
.compile("(?<![A-Za-z0-9_])" + java.util.regex.Pattern.quote(methodName) + "\\s*\\(")
.matcher(source);
while (matcher.find()) {
int open = matcher.end() - 1;
int signatureStart = findSignatureStart(source, matcher.start());
int bodyEnd = matchBraces(source, nextBrace(source, open));
if (bodyEnd < 0) {
continue;
}
return source.substring(signatureStart, bodyEnd + 1);
}
throw new AssertionError("源码里没有方法「" + methodName + "」——它被改名或删掉了。"
+ "反向钉宁可红在这里,也不许因为切不到方法而恒绿。");
}
/** 从签名的左括号往前退到上一条 `{`/`}`/`;` 之后,再退回到第一行注解的起始(注解属于这个方法,必须含进来)。 */
private static int findSignatureStart(String source, int nameStart) {
int boundary = 0;
for (int i = nameStart; i-- > 0; ) {
char c = source.charAt(i);
if (c == '{' || c == '}' || c == ';') {
boundary = i + 1;
break;
}
}
String head = source.substring(boundary, nameStart);
int firstMeaningful = head.length();
for (String raw : head.split("\n", -1)) {
if (!raw.isBlank()) {
firstMeaningful = head.indexOf(raw.stripLeading());
break;
}
}
return boundary + firstMeaningful;
}
private static int nextBrace(String source, int from) {
for (int i = from; i < source.length(); i++) {
if (source.charAt(i) == '{') {
return i;
}
if (source.charAt(i) == ';') {
return -1; // 抽象方法/接口声明,不是我们要切的东西
}
}
return -1;
}
/** 朴素配平:源码里的 `{` 与 `}` 若出现在字符串字面量里会算错。本仓库 controller 没有这种写法,
* 但这条限制必须写在脸上——将来有人往方法体里塞一段带花括号的字符串,这个助手会悄悄切短。 */
private static int matchBraces(String source, int open) {
if (open < 0) {
return -1;
}
int depth = 0;
for (int i = open; i < source.length(); i++) {
char c = source.charAt(i);
if (c == '{') {
depth++;
} else if (c == '}') {
if (--depth == 0) {
return i;
}
}
}
return -1;
}
private static List<Path> mainSources() {
Path root = moduleRoot().resolve("src/main/java");
try (Stream<Path> walk = Files.walk(root)) {
return walk.filter(Files::isRegularFile)
.filter(p -> p.getFileName().toString().endsWith(".java"))
.collect(Collectors.toList());
} catch (IOException e) {
// 定位不到必须抛,不许静默返回空表:返回空 ⇒ sourceText 那支护栏扫不到任何文件而恒绿。
throw new IllegalStateException("遍历 " + root + " 失败: " + e.getMessage(), e);
}
}
private static Path moduleRoot() {
Path here = Path.of("").toAbsolutePath();
if (Files.isDirectory(here.resolve("src/main/java"))) {
return here;
}
Path nested = here.resolve("backend-java");
if (Files.isDirectory(nested.resolve("src/main/java"))) {
return nested;
}
throw new IllegalStateException("无法定位 backend-java 模块目录(cwd=" + here + ")");
}
private static String read(Path file) {
try {
return Files.readString(file, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new IllegalStateException("读取失败: " + file, e);
}
}
}