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.stream.Collectors; import java.util.stream.Stream; /** 源码扫描式护栏的取文助手。路径解析照抄 {@code common/security/InternalTokenSingleOutletTest} 的 * moduleRoot()/mainSources() 两支——surefire 的 cwd 是模块目录,从仓库根或 IDE 跑时要退到 backend-java/, * 定位不到必须 fail 而不是静默跳过(静默跳过 = 整支护栏恒绿)。 */ public final class SourceScan { private SourceScan() { } /** 按文件名(不含目录)取 {@code src/main/java} 下那份源码的全文字符串。 * ⚠️ 返回 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 + " —— 文件改名/挪目录了,护栏要红在这里")); } /** * 剥掉注释,偏移不变:注释字符换成空格、换行原样保留,所以 {@link #methodBody} 这类 * 按位置切片的助手在剥前剥后切出同一段。 * *

为什么护栏必须打在它上面:源码守卫的两种断言都会被文字喂到—— * 「必须不存在」那一形会被注释里提一句顶红(假红,还能忍), * 「必须存在/次数等于 N」那一形会被 javadoc 里提一句喂饱(假绿,等于护栏没写)。 * 2026-10-07 实测:{@code AdminTaskCenterController} 的类注释里有 1 处 {@code readScope(}, * 整份原文 {@code readScope(} 数=1、剥完=0——文件级判据吃原文就会读出这种数。

* *

口径:{@code //} 到行尾、{@code /* … *}{@code /} 整段、字符串与字符字面量里的斜杠不算注释、 * 三个双引号的文本块按字面量整段保留。

*/ 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(); } /** 大括号配平切出「某个方法」的源码:从它的签名行往前一直含到注解,到方法收尾的 `}` 为止。 * *

两条它必须自己防住的坑,都写在用例里过:

* */ public static String methodBody(String source, String methodName) { var matcher = java.util.regex.Pattern .compile("(? 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 mainSources() { Path root = moduleRoot().resolve("src/main/java"); try (Stream 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); } } }