Files
java-ai-agents/code-search-mcp/src/main/java/com/ankurm/codesearch/CodeIndexer.java
T

125 lines
5.4 KiB
Java

package com.ankurm.codesearch;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.body.CallableDeclaration;
import com.github.javaparser.ast.body.TypeDeclaration;
import com.github.javaparser.ast.nodeTypes.NodeWithJavadoc;
import com.github.javaparser.symbolsolver.JavaSymbolSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver;
/**
* Turns a monorepo into {@link CodeUnit}s with JavaParser. It finds every {@code src/main/java} folder under the
* root, parses each {@code .java} file once, and keeps the parsed trees so the usage finder can walk them later.
*/
public final class CodeIndexer {
private final Path root;
private final List<CompilationUnit> units = new ArrayList<>();
private final List<CodeUnit> codeUnits = new ArrayList<>();
private final List<String> parseProblems = new ArrayList<>();
public CodeIndexer(Path root) {
this.root = root.toAbsolutePath().normalize();
}
/** Parses everything. Call once; the result is read through the accessors. */
public CodeIndexer index() throws IOException {
List<Path> sourceRoots = findSourceRoots();
// One type solver for the whole monorepo: every module's source folder plus the JDK.
CombinedTypeSolver solver = new CombinedTypeSolver(new ReflectionTypeSolver());
for (Path sourceRoot : sourceRoots) {
solver.add(new JavaParserTypeSolver(sourceRoot));
}
ParserConfiguration config = new ParserConfiguration()
.setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_25)
.setSymbolResolver(new JavaSymbolSolver(solver));
JavaParser parser = new JavaParser(config);
for (Path sourceRoot : sourceRoots) {
try (Stream<Path> files = Files.walk(sourceRoot)) {
for (Path file : files.filter(f -> f.toString().endsWith(".java")).sorted().toList()) {
var result = parser.parse(file);
if (result.getResult().isEmpty() || !result.isSuccessful()) {
parseProblems.add(relative(file) + ": " + result.getProblems().size() + " problem(s)");
}
result.getResult().ifPresent(cu -> {
cu.setStorage(file);
units.add(cu);
cu.findAll(TypeDeclaration.class).forEach(t -> addType(cu, t));
});
}
}
}
return this;
}
private List<Path> findSourceRoots() throws IOException {
try (Stream<Path> walk = Files.walk(root)) {
return walk.filter(Files::isDirectory)
.filter(p -> p.endsWith(Path.of("src", "main", "java")))
.sorted().toList();
}
}
private void addType(CompilationUnit cu, TypeDeclaration<?> type) {
String qualified = type.getFullyQualifiedName().orElse(type.getNameAsString());
codeUnits.add(new CodeUnit(CodeUnit.Kind.TYPE, qualified, header(type), relative(cu), line(type),
javadoc(type), type.getNameAsString() + " (" + type.getMembers().size() + " members)"));
for (var member : type.getMembers()) {
if (member instanceof CallableDeclaration<?> callable) {
codeUnits.add(new CodeUnit(CodeUnit.Kind.METHOD, qualified + "#" + callable.getNameAsString(),
callable.getDeclarationAsString(true, false, true), relative(cu), line(callable),
javadoc(callable), callable.toString()));
}
}
}
private static String header(TypeDeclaration<?> type) {
String kind = switch (type) {
case com.github.javaparser.ast.body.ClassOrInterfaceDeclaration c -> c.isInterface() ? "interface" : "class";
case com.github.javaparser.ast.body.RecordDeclaration r -> "record";
case com.github.javaparser.ast.body.EnumDeclaration e -> "enum";
default -> "type";
};
return kind + " " + type.getNameAsString();
}
private static int line(Node node) {
return node.getRange().map(r -> r.begin.line).orElse(0);
}
private static String javadoc(Node node) {
if (node instanceof NodeWithJavadoc<?> documented) {
return documented.getJavadoc().map(j -> j.getDescription().toText().replaceAll("\\s+", " ").trim())
.orElse("");
}
return "";
}
private String relative(CompilationUnit cu) {
return relative(cu.getStorage().orElseThrow().getPath());
}
private String relative(Path file) {
return root.relativize(file.toAbsolutePath().normalize()).toString().replace('\\', '/');
}
public Path root() { return root; }
public List<CompilationUnit> compilationUnits() { return List.copyOf(units); }
public List<CodeUnit> codeUnits() { return List.copyOf(codeUnits); }
public List<String> parseProblems() { return List.copyOf(parseProblems); }
}