task-7: 递归语义 8 例落地(RED 实录:隐藏目录/链接重复计入/遍历失败三格真红);实测证伪 plan 假设——Files.walk 会钻进 Windows junction 读出 [One.java,One.java],且公开 NIO 无 isReparsePoint,改按 toRealPath 折叠
This commit is contained in:
@@ -2,8 +2,12 @@ package com.nanri.aiimage.testutil;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.FileVisitOption;
|
||||
import java.nio.file.FileVisitResult;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.SimpleFileVisitor;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
@@ -60,21 +64,14 @@ public final class SourceScan {
|
||||
}
|
||||
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())));
|
||||
}
|
||||
// N7 之后普查与聚合共用同一条遍历(含隐藏目录/重解析点排除),免得两套口径读出不一样多的文件
|
||||
for (Path file : collectJavaFiles(root)) {
|
||||
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);
|
||||
}
|
||||
@@ -188,17 +185,69 @@ public final class SourceScan {
|
||||
return List.copyOf(collectJavaFiles(module));
|
||||
}
|
||||
|
||||
private static List<Path> collectJavaFiles(Path root) {
|
||||
/**
|
||||
* 收集 {@code root} 下任意深度的 {@code .java}(N7 定递归语义)。用 {@code walkFileTree} 而不是
|
||||
* {@code Files.walk},因为三种失败模式必须在<b>进入之前</b>决定,事后 filter 来不及:
|
||||
* <ol>
|
||||
* <li><b>隐藏目录不进面</b>:{@code .git/}、{@code .idea/} 里的 {@code .java} 是工具生成的副本,
|
||||
* 进面等于同一份代码被数两遍,精确计数格(publish 恰 1)当场失真。</li>
|
||||
* <li><b>重解析点不进面</b>:本机实测 {@code Files.walk} <b>会</b>钻进 Windows 的 junction
|
||||
* (用例读出 {@code [One.java, One.java]}),"默认不 FOLLOW_LINKS 所以安全"这条假设已被证伪。
|
||||
* {@code dos:ReparsePoint} 属性是公开 API 里唯一的识别手段({@code DosFileAttributes} 接口上没有 isReparsePoint())。</li>
|
||||
* <li><b>遍历失败必须抛</b>:{@code visitFileFailed} 与"根本不存在"两条道都包成
|
||||
* {@code IllegalStateException} 并点名路径——吞成空表就是「读不到 = 没违规」。</li>
|
||||
* </ol>
|
||||
*/
|
||||
static List<Path> collectJavaFiles(Path root) {
|
||||
Path start = root.toAbsolutePath();
|
||||
java.util.Map<Path, Path> deduped = new java.util.LinkedHashMap<>();
|
||||
try {
|
||||
Files.walkFileTree(start, java.util.EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE,
|
||||
new SimpleFileVisitor<Path>() {
|
||||
@Override
|
||||
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
|
||||
return !dir.equals(start) && isExcludedDirectory(dir)
|
||||
? FileVisitResult.SKIP_SUBTREE
|
||||
: FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
try (Stream<Path> walk = Files.walk(root)) {
|
||||
return walk.filter(Files::isRegularFile)
|
||||
.filter(p -> p.getFileName().toString().endsWith(".java"))
|
||||
.sorted(java.util.Comparator.comparing(
|
||||
p -> root.relativize(p).toString().replace('\\', '/')))
|
||||
.toList();
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
|
||||
String name = file.getFileName().toString();
|
||||
if (name.endsWith(".java") && !name.startsWith(".")) {
|
||||
deduped.putIfAbsent(realPathOf(file), file);
|
||||
}
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult visitFileFailed(Path file, IOException exc) {
|
||||
throw new IllegalStateException("遍历 " + start + " 时在 " + file + " 失败: "
|
||||
+ exc.getMessage(), exc);
|
||||
}
|
||||
});
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("遍历 " + root + " 失败: " + e.getMessage(), e);
|
||||
throw new IllegalStateException("遍历 " + start + " 失败: " + e.getMessage(), e);
|
||||
}
|
||||
List<Path> found = new java.util.ArrayList<>(deduped.values());
|
||||
found.sort(java.util.Comparator.comparing(p -> start.relativize(p).toString().replace('\\', '/')));
|
||||
return List.copyOf(found);
|
||||
}
|
||||
|
||||
/** 链接折叠用的键;拿不到实路径(并发被删等)就退回绝对路径,宁可少折一次也不吞异常。 */
|
||||
private static Path realPathOf(Path file) {
|
||||
try {
|
||||
return file.toRealPath();
|
||||
} catch (IOException e) {
|
||||
return file.toAbsolutePath().normalize();
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isExcludedDirectory(Path dir) {
|
||||
if (dir.getFileName().toString().startsWith(".") || Files.isSymbolicLink(dir)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 按文件名(不含目录)取 {@code src/main/java} 下那份源码的<b>全文字符串</b>。
|
||||
|
||||
@@ -354,4 +354,137 @@ class SourceScanTest {
|
||||
.hasMessageContaining("cwd=")
|
||||
.hasMessageContaining(Path.of("").toAbsolutePath().toString());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- N7 递归语义
|
||||
|
||||
@Test
|
||||
void recursive_包含service下的直接件() {
|
||||
assertThat(SourceScan.moduleSources("modules/appearancepatent"))
|
||||
.as("模块根下第一层的 service/ 直接件必须在面里")
|
||||
.anyMatch(p -> p.toString().replace('\\', '/').endsWith(
|
||||
"service/AppearancePatentTaskService.java"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void recursive_包含service_support下的既有5件() {
|
||||
List<String> support = SourceScan.moduleSources("modules/appearancepatent").stream()
|
||||
.map(p -> p.toString().replace('\\', '/'))
|
||||
.filter(rel -> rel.contains("/service/support/"))
|
||||
.toList();
|
||||
|
||||
assertThat(support)
|
||||
.as("真实集成:对真仓 modules/appearancepatent/service/support 求值,实测 5 支。"
|
||||
+ "这一格就是聚合入口存在的理由——拆分出去的新文件必须自动进面")
|
||||
.hasSize(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
void recursive_包含model下两层dto与vo() {
|
||||
List<String> rel = SourceScan.moduleSources("modules/appearancepatent").stream()
|
||||
.map(p -> p.toString().replace('\\', '/'))
|
||||
.toList();
|
||||
|
||||
assertThat(rel.stream().filter(p -> p.contains("/model/dto/")).count())
|
||||
.as("model/dto 一层嵌套")
|
||||
.isEqualTo(7);
|
||||
assertThat(rel.stream().filter(p -> p.contains("/model/vo/")).count())
|
||||
.as("model/vo 一层嵌套")
|
||||
.isEqualTo(9);
|
||||
}
|
||||
|
||||
@Test
|
||||
void recursive_深度为1的目录不出现在面里() throws IOException {
|
||||
Path module = Files.createDirectories(tmp.resolve("N7深度树/src/main/java/modules/deep"));
|
||||
Path deep = Files.createDirectories(module.resolve("a/b/c"));
|
||||
Files.writeString(deep.resolve("D.java"), "class D {}", StandardCharsets.UTF_8);
|
||||
Files.writeString(module.resolve("Root.java"), "class Root {}", StandardCharsets.UTF_8);
|
||||
|
||||
List<Path> files = SourceScan.moduleSources(tmp.resolve("N7深度树/src/main/java"), "modules/deep");
|
||||
|
||||
assertThat(files)
|
||||
.as("三层嵌套里的 a/b/c/D.java 必须被计入:只爬一层的实现会静默漏掉它,"
|
||||
+ "而 support/ 恰恰就是这一层以下的位置")
|
||||
.extracting(p -> p.getFileName().toString())
|
||||
.containsExactlyInAnyOrder("D.java", "Root.java");
|
||||
assertThat(files)
|
||||
.as("面里只许有文件——目录本身不是元素,否则聚合文本会多出无内容条目")
|
||||
.allMatch(Files::isRegularFile);
|
||||
}
|
||||
|
||||
@Test
|
||||
void recursive_隐藏目录件被排除() throws IOException {
|
||||
Path module = Files.createDirectories(tmp.resolve("N7隐藏树/src/main/java/modules/vis"));
|
||||
Path hidden = Files.createDirectories(module.resolve(".git"));
|
||||
Files.writeString(hidden.resolve("Ghost.java"), "class Ghost {}", StandardCharsets.UTF_8);
|
||||
Files.writeString(module.resolve("Real.java"), "class Real {}", StandardCharsets.UTF_8);
|
||||
|
||||
assertThat(SourceScan.moduleSources(tmp.resolve("N7隐藏树/src/main/java"), "modules/vis"))
|
||||
.as(".git / .idea 这类目录里的 .java(IDE 与工具生成的副本)不许进面——"
|
||||
+ "否则同一份代码会被算两遍,精确计数格(publish 恰 1)当场失真")
|
||||
.extracting(p -> p.getFileName().toString())
|
||||
.containsExactly("Real.java");
|
||||
}
|
||||
|
||||
@Test
|
||||
void recursive_符号链接目录不被重复计入() throws IOException, InterruptedException {
|
||||
Path javaRoot = Files.createDirectories(tmp.resolve("N7链树/src/main/java"));
|
||||
Path real = Files.createDirectories(javaRoot.resolve("modules/linkreal"));
|
||||
Files.writeString(real.resolve("One.java"), "class One {}", StandardCharsets.UTF_8);
|
||||
// Windows 上建符号链接要特权,junction 不用:mklink /J 是本机的可复现路径。
|
||||
// ⚠ 这里刻意不用 Assumptions 跳过——跳过会新增一格 Skipped,直接违反 N99「一个新 skip 都不许有」,
|
||||
// 那是拿跳过换绿。建不出来就判红并点名环境缺口(plan N3 第 9 例同一条口径)。
|
||||
Process mk = new ProcessBuilder("cmd.exe", "/c", "mklink", "/J",
|
||||
javaRoot.resolve("modules").resolve("linkalias").toString(), real.toString())
|
||||
.redirectErrorStream(true).start();
|
||||
String out;
|
||||
try (var in = mk.getInputStream()) {
|
||||
out = new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
int mklink = mk.waitFor();
|
||||
assertThat(mklink)
|
||||
.as("junction 建不出来 ⇒ 本机环境不支持,这格判红而不是跳过(跳过会新增 Skipped,"
|
||||
+ "违反 N99「一个新 skip 都不许有」)。cmd 输出:%s", out)
|
||||
.isZero();
|
||||
|
||||
List<Path> files = SourceScan.moduleSources(javaRoot, "modules");
|
||||
|
||||
assertThat(files)
|
||||
.as("目录联接指回同一棵树:本机实测 Files.walk 会照钻 junction(改之前读出 [One.java, One.java]),"
|
||||
+ "所以「默认不 FOLLOW_LINKS 就安全」这条假设已被证伪。实现按 toRealPath() 折叠同一份文件"
|
||||
+ "(公开 NIO 读不到重解析点标志);重复计入会让精确计数格(publish 恰 1)假绿")
|
||||
.extracting(p -> p.getFileName().toString())
|
||||
.containsExactly("One.java");
|
||||
}
|
||||
|
||||
@Test
|
||||
void recursive_目录内全是非java时命中为空() throws IOException {
|
||||
Path module = Files.createDirectories(tmp.resolve("N7非java树/src/main/java/modules/docs"));
|
||||
Files.writeString(module.resolve("README.md"), "# 迁移说明", StandardCharsets.UTF_8);
|
||||
Files.createDirectories(module.resolve("sub"));
|
||||
Files.writeString(module.resolve("sub").resolve("notes.txt"), "x", StandardCharsets.UTF_8);
|
||||
|
||||
assertThat(SourceScan.moduleSources(tmp.resolve("N7非java树/src/main/java"), "modules/docs"))
|
||||
.as("整棵树没有 .java ⇒ 空表(N11 会把这条改成抛;本格先钉「非 java 不进面」)")
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void recursive_遍历失败抛IllegalStateException不吞() throws IOException {
|
||||
Path vanished = tmp.resolve("N7消失树"); // 刻意不创建:walk 必须在第一步就抛 IOException
|
||||
|
||||
// 正对照:先证明这里真的会抛 IOException —— 否则「没吞」这条断言是空的
|
||||
try (var raw = java.nio.file.Files.walk(vanished)) {
|
||||
raw.toList();
|
||||
org.junit.jupiter.api.Assertions.fail("JDK 的 Files.walk 在这条路径上没抛,正对照失效");
|
||||
} catch (java.io.IOException expected) {
|
||||
assertThat(expected).isInstanceOf(java.nio.file.NoSuchFileException.class);
|
||||
}
|
||||
|
||||
assertThatThrownBy(() -> SourceScan.collectJavaFiles(vanished))
|
||||
.as("遍历抛 IOException 时必须包成 IllegalStateException 并点名路径,不许吞成空表——"
|
||||
+ "「扫不到」被读成「没违规」是本族护栏的标准死法(10-15 §12 第一条)")
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("遍历")
|
||||
.hasMessageContaining(vanished.getFileName().toString());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user