diff --git a/.gitattributes b/.gitattributes index 5c826c1..084ed5f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,4 +4,4 @@ internal/deps/testdata/** -text # Keep vendored SDK files byte-identical to the checksums in sdk.lock.json. internal/lithesdk/lithe/*.go text eol=lf -vendor/LICENSE text eol=lf +licenses/lithe-sdk-LICENSE text eol=lf diff --git a/README.md b/README.md index cf7fb62..8c52028 100644 --- a/README.md +++ b/README.md @@ -2,13 +2,13 @@ [Java Support](https://github.com/Lithe-IDEA/lithe-plugin-java) 的轻量版(插件 ID 仍是 `io.github.lithe-idea.java-navigation`,0.0.2 及以前叫 Java Navigation)。 为 [Lithe](https://github.com/1lck/Lithe-IDEA) 提供**不依赖 JDT LS 的轻量 Java 跳转**:跳转到定义、查找引用和文档结构, -能跳进 JDK 和 Maven 依赖库。插件自带一个用 Go 写的小型语言服务器,不需要 JDK 运行时、不运行 Maven, +能跳进 JDK、Maven 和 Gradle 依赖库。插件自带一个用 Go 写的小型语言服务器,不需要 JDK 运行时、不运行 Maven 或 Gradle, 打开项目后第一次跳转约 0.2–0.5 秒就能用,常驻内存 60–90 MiB(同一个项目 JDT LS 要 3 GB,导入要 1 分钟)。 这是一个**社区插件**,按插件契约 v0 编写。 > English: Java Support Lite, the lightweight edition of Java Support (plugin ID `io.github.lithe-idea.java-navigation`, > named Java Navigation up to 0.0.2): lightweight Java navigation for Lithe without JDT LS — go to definition, find references and the -> document outline, into the JDK and Maven dependency jars, served by a small Go language server that keeps +> document outline, into the JDK and Maven or Gradle dependency jars, served by a small Go language server that keeps > an index of declarations only. No JDK runtime, no build import, 60–90 MiB of memory. > **预发布**:按插件契约 v0(`schemaVersion: 0`、`pluginAPIVersion: 0`)编写,只能装进新版 Lithe 桌面端 @@ -22,7 +22,7 @@ | 实现 / 父类双向跳转 | 接口/父类向下跳转到实现类与重写方法(`textDocument/implementation`),实现类/重写方法向上跳回接口与父类声明(`javaNavigation/superDeclarations`),并在行首绘制绿色 `I↓`/`I↑` 与蓝色 `O↓`/`O↑` 导航图标 | | Lombok | `@Data`/`@Getter`/`@Setter` 生成的访问器跳到字段,`@Builder`、`@Slf4j`、构造器注解跳到注解本身(与 JDT LS 一致) | | 跳进 JDK | 项目里找不到的名字到本机 JDK 的 `src.zip` 里找,`String`、`List`、`hashCode()` 等都能跳,并能在 JDK 源码里继续跳 | -| 跳进依赖库 | Maven 项目的依赖(含传递依赖)从本地仓库读:下载过 `-sources.jar` 的打开源码,否则打开从 `.class` 生成的签名存根(类、成员类、字段、构造器、方法,参数名取自调试信息),并能在里面继续跳;`@Schema(description = ...)`、`log.info(...)`、`StrUtil.isEmpty(...)` 都能跳 | +| 跳进依赖库 | Maven 和 Gradle 的依赖(含传递依赖)从本地仓库或缓存读取:下载过 `-sources.jar` 的打开源码,否则打开从 `.class` 生成的签名存根(类、成员类、字段、构造器、方法,参数名取自调试信息),并能在里面继续跳;`@Schema(description = ...)`、`log.info(...)`、`StrUtil.isEmpty(...)` 都能跳 | | 老项目的 jar | 读 Eclipse `.classpath`、Ant `build.xml` 的静态类路径,以及 `lib/`、`libs/`、`WEB-INF/lib` 里的 jar | | Eclipse 容器 | `.classpath` 里的服务器运行时容器(Tomcat、Jetty、WildFly 等)和 JUnit 容器换成本机已有的 jar,`HttpServletRequest`、`@WebServlet`、`@Test` 都能跳;没有 pom 的 `WEB-INF/web.xml` Web 项目同样补上 Servlet/JSP API | | 生成代码 | 模块的 `target/generated-sources`(protobuf、注解处理器)和 Gradle 的 `build/generated` 也进索引,即使被 `.gitignore` 忽略 | @@ -43,6 +43,8 @@ 只预先列出每个 jar 的目录(Nacos 265 个 jar、4.4 万个类;ruoyi-vue-pro 824 个 jar、15 万个类,约 0.3 秒), 某个类第一次被查到时才读它的源码或生成存根;跳进去时把那一个文件写成只读副本,放在 `${stateDir}/dependency-sources`, 不写本地仓库。 +- Gradle 项目从 `build.gradle`、`build.gradle.kts` 的 `dependencies` 块读取常用 Java 配置中的字面量坐标和 `libs.*` 引用。别名来自工作区根的 `gradle/libs.versions.toml`。 + 在 `${GRADLE_USER_HOME:-~/.gradle}/caches/modules-2/files-2.1` 查找 JAR、源码包和传递依赖的 POM。按构建脚本分别解析,常规子目录项目会继承上层脚本的字面量 `subprojects`/`allprojects` 声明,测试编译配置在同一组内选版本。自定义项目目录映射和运行时计算的配置不解析。主编译配置优先进入工作区的共享索引,测试和运行时配置补充索引。相同类名优先使用先进入索引的版本,目前不会根据光标所在模块或源集切换类路径。普通版本请求冲突时取较高版本,再按该版本的 POM 选取传递依赖。支持版本目录中的 `strictly` 和 `require`,以及从缓存选择满足单个版本区间的最高版本。省略版本时取本地缓存的最高版本,选定版本未下载时跳过。仅有 Gradle Module Metadata、没有 POM 的依赖目前只能索引自身。 - 工作区里的 jar:先按每个 Eclipse `.classpath` 的 `lib` 条目和 `M2_REPO` 变量条目的顺序,再加上路径往上三层内 有 `lib` 或 `libs` 目录的 jar(`WEB-INF/lib`、`lib/optional` 都算;测试资源里的 jar、`gradle-wrapper.jar`、 `target`/`build` 里的不算);工作区根目录和每个 `build.xml`、`.classpath`、`.project` 所在目录下的 `lib`、 @@ -59,7 +61,7 @@ Servlet API 和 JSP API;`JUNIT_CONTAINER/3`、`/4`、`/5` 取本地仓库里对应大版本的最新 JUnit(4 加上 hamcrest-core)。 项目自己已经带了 Servlet 或 JUnit 的 jar 时不再补。没有 `pom.xml`/Gradle 构建文件、但有 `WEB-INF/web.xml` 的 项目按 Servlet 容器处理(web.xml 用 Jakarta EE 命名空间时取 `jakarta.servlet`)。不联网下载,本机都没有就跳过。 -- `pom.xml`、`.classpath` 或上面任一个 jar 变了、或距上次读取超过 5 分钟,下一次扫描重新读取依赖。 +- 构建脚本、Gradle 版本目录、`pom.xml`、`.classpath` 或工作区内的 jar 变了、或距上次读取超过 5 分钟,下一次扫描重新读取依赖。 - JDK:按 `JAVA_HOME` → 系统默认 JDK(macOS 的 `/usr/libexec/java_home`,其他系统 `PATH` 上的 `java`)→ 常见安装目录 (含 IntelliJ 的 `~/.jdks`、SDKMAN!)的顺序找第一个带 `src.zip` 的 JDK。只预先列出 zip 目录,某个类第一次被查到时才解析。 跳进 JDK 时把那一个源码文件解压成只读副本,放在 Lithe 为插件分配的状态目录(`${stateDir}`)里,卸载插件时一起删除; @@ -114,11 +116,22 @@ | [OpenCms](https://github.com/alkacon/opencms-core) | 2000 年起的 JSP CMS,Gradle | 94.1% | 0.20 ms / 2.0 ms | 0.13 s | 54 MiB | 剩下没跳到的主要是:依赖没在项目里声明或本地仓库没有(JFinal 的 Servlet 依赖在 pom 里被注释掉了,Struts 的 -JSF 依赖没下载过,OpenCms 的 Gradle 依赖读不了)、数组的 `.length`(JDT LS 也不跳)、`java.util.Date` 这种全限定名里的包名段,以及 lambda 参数。 +JSF 依赖没下载过,这轮 OpenCms 基准早于 Gradle 缓存支持)、数组的 `.length`(JDT LS 也不跳)、`java.util.Date` 这种全限定名里的包名段,以及 lambda 参数。 + +### Spring Boot Gradle 项目(Linux x64) + +取 Spring 官方 REST 示例的 `complete` 目录,仅保留 Gradle 构建与 Java 源码。Gradle 9.3.1 的 `testClasses` 已预热依赖缓存。使用 `cmd/nav-bench -seed 2` 对相同的 33 个位置交替测量三轮,每轮启动新语言服务器并使用独立状态目录。两组均未加载 JDK 源码。[示例工程固定版本](https://github.com/spring-guides/gs-rest-service/tree/e15fec6773dc1eb6028055630e3e68cbd8653240/complete) + +| 依赖解析 | 命中 | 首次跳转 | 跳转 p50 | 查询结束 RSS | +| --- | --- | --- | --- | --- | +| 修复前(`4750015`) | 18/33(54.5%) | 4 ms | 0.14–0.15 ms | 8 MiB | +| 读取 Gradle 缓存 | 25/33(75.8%) | 53–56 ms | 0.18–0.21 ms | 12–13 MiB | + +新增的 7 个命中全部指向依赖声明,包括 `SpringApplication.run`、`@RestController` 和 `@GetMapping`。索引载入了 65 个 JAR 的 9,458 个类,查询结束时 RSS 增加 4–5 MiB。 ## 限制 -- **依赖库只读 Maven 和工作区里的 jar**:Gradle 项目的依赖还读不了(Gradle 的生成代码可以);Ant 目标执行时 +- **依赖库使用静态声明和本地缓存**。Gradle 脚本计算出的坐标、自定义版本目录、bundle 和变体选择不参与解析;Ant 目标执行时 才能得到的类路径也会跳过。只用本地仓库里已有的 jar, 从没构建过、依赖还没下载的项目跳不进依赖库。没有 `-sources.jar` 时打开签名存根,没有方法体和注释; 编译时没带调试信息的接口和抽象方法,参数名是 `arg0`、`arg1`。 @@ -151,7 +164,7 @@ go run ./cmd/nav-bench -h # 在真实项目上测命中率、延迟和 `dist/` 里每个平台一个 zip(`darwin-arm64`、`darwin-x64`、`windows-x64`、`windows-arm64`),包内只有 `plugin.json`、`bin/java-navigation`(Windows 是 `bin/java-navigation.exe`,对应平台包的 `plugin.json` 为语言服务器与 `--backend` 后端均写这个路径)、 -`LICENSE`、`THIRD_PARTY_NOTICES.md` 和 `vendor/LICENSE`。 +`LICENSE`、`THIRD_PARTY_NOTICES.md` 和 `licenses/` 下的第三方许可证。 语言服务器和后端都可以单独运行调试: diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 99c0f07..6cdf8d4 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -40,4 +40,10 @@ SOFTWARE. - Source: https://github.com/Lithe-IDEA/Lithe-core-rust (`shared/plugins/sdk/go/lithe`, revision `0d79e17fde389f559bcb3eeeb11baace13895576`) - Used in: `internal/lithesdk/lithe/` (copied verbatim from upstream without modifications; checksums pinned in `sdk.lock.json`) -- License: see `vendor/LICENSE` +- License: see `licenses/lithe-sdk-LICENSE` + +## BurntSushi/toml + +- Source: https://github.com/BurntSushi/toml +- Used to read Gradle version catalogs. +- License: MIT (see `licenses/BurntSushi-toml-LICENSE`). diff --git a/cmd/java-navigation/main.go b/cmd/java-navigation/main.go index 0925821..fccd3ff 100644 --- a/cmd/java-navigation/main.go +++ b/cmd/java-navigation/main.go @@ -36,7 +36,7 @@ func main() { state := flag.String("state-dir", "", "writable directory for extracted JDK sources (the host's ${stateDir})") printVersion := flag.Bool("version", false, "print the version and exit") noJDK := flag.Bool("no-jdk", false, "do not navigate into the JDK's sources") - noDeps := flag.Bool("no-dependencies", false, "do not navigate into dependency jars (Maven dependencies and the jars the project keeps)") + noDeps := flag.Bool("no-dependencies", false, "do not navigate into dependency jars (Maven, Gradle and the jars the project keeps)") runBackend := flag.Bool("backend", false, "run as a Lithe plugin backend over stdio") flag.Bool("stdio", true, "speak LSP over standard input and output (the only transport)") flag.Parse() diff --git a/go.mod b/go.mod index 35b82eb..b2651b4 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module github.com/Lithe-IDEA/lithe-plugin-java-navigation go 1.27.3 + +require github.com/BurntSushi/toml v1.4.0 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..8bc10f6 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0= +github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= diff --git a/internal/deps/gradle.go b/internal/deps/gradle.go new file mode 100644 index 0000000..20e1515 --- /dev/null +++ b/internal/deps/gradle.go @@ -0,0 +1,352 @@ +package deps + +import ( + "context" + "io" + "maps" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + + "github.com/BurntSushi/toml" +) + +// GradleJars reads literal dependency declarations and the default version +// catalog. Gradle scripts are executable code; navigation only reads them. +// Published POMs in the cache supply the transitive dependencies. +func GradleJars(ctx context.Context, scripts []string, catalogPath string, logf func(string, ...any)) ([]Jar, error) { + home := os.Getenv("GRADLE_USER_HOME") + if home == "" { + userHome, err := os.UserHomeDir() + if err != nil { + return nil, nil + } + home = filepath.Join(userHome, ".gradle") + } + repo := &localRepo{root: filepath.Join(home, "caches", "modules-2", "files-2.1"), gradle: true, versions: map[string][]string{}} + m := newMaven(ctx, repo, logf) + catalog := readGradleCatalog(catalogPath, m.logf) + projects := make(map[string]gradleProject) + var directories []string + for _, p := range scripts { + if err := ctx.Err(); err != nil { + return nil, err + } + dir := filepath.Dir(p) + if _, ok := projects[dir]; !ok { + directories = append(directories, dir) + projects[dir] = gradleDeclarations(readGradleFile(p), catalog) + } + } + var primary, extra []*model + for _, dir := range directories { + groups := projects[dir].own + for child := dir; filepath.Dir(child) != child; child = filepath.Dir(child) { + // A nested build with its own settings does not inherit the + // outer build's subprojects declarations. + if _, err := os.Stat(filepath.Join(child, "settings.gradle")); err == nil { + break + } + if _, err := os.Stat(filepath.Join(child, "settings.gradle.kts")); err == nil { + break + } + for group, shared := range projects[filepath.Dir(child)].children { + groups[group] = append(groups[group], shared...) + } + } + if base := groups[""]; len(base) > 0 { + primary = append(primary, &model{deps: base}) + } + delete(groups, "") + for _, configuration := range slices.Sorted(maps.Keys(groups)) { + extra = append(extra, &model{deps: groups[configuration]}) + } + } + // The workspace uses one ordered index. Keep production compile jars + // first, then add jars from other configurations without evicting them. + var jars []Jar + seen := make(map[string]bool) + for _, root := range append(primary, extra...) { + resolved, err := m.resolveGradle(root) + if err != nil { + return nil, err + } + for _, jar := range resolved { + if !seen[jar.Path] { + jars = append(jars, jar) + seen[jar.Path] = true + } + } + } + return jars, nil +} + +// A higher request can be discovered after the lower version's POM has +// already been walked. Walk again with the winners so dependencies unique +// to an evicted version disappear too. +func (m *maven) resolveGradle(root *model) ([]Jar, error) { + type selection struct { + version string + strict bool + } + better := func(a, b selection) bool { + if a.strict != b.strict { + return a.strict + } + return compareVersions(a.version, b.version) > 0 + } + var previous, beforePrevious map[string]selection + const maxConflictPasses = 32 + for pass := 1; ; pass++ { + requests := map[string]selection{} + used := map[string]selection{} + choose := func(dep pomDep, version string) string { + key := gaOf(dep) + want := selection{version, dep.strict} + old, ok := requests[key] + if !ok || better(want, old) { + requests[key] = want + } + if _, ok := used[key]; !ok { + chosen, ok := previous[key] + if !ok { + chosen = want + } + used[key] = chosen + } + return used[key].version + } + jars, err := m.resolve([]*model{root}, choose) + if err != nil || maps.Equal(used, requests) { + return jars, err + } + if pass == maxConflictPasses || maps.Equal(beforePrevious, requests) { + // Cross-upgrading POMs may remove the requests that selected + // them. Pin the winners of both walks for one final traversal. + for key, chosen := range used { + if better(chosen, requests[key]) { + requests[key] = chosen + } + } + m.logf("Gradle version requests did not stabilize; indexing the selected cached versions") + return m.resolve([]*model{root}, func(dep pomDep, version string) string { + if winner, ok := requests[gaOf(dep)]; ok { + return winner.version + } + return version + }) + } + beforePrevious, previous = previous, requests + } +} + +// Gradle accepts both Maven-style open bounds and the reversed-bracket form. +func gradleRangeVersion(selector string, versions []string) string { + if len(selector) < 3 { + return "" + } + left, right := selector[0], selector[len(selector)-1] + if !strings.ContainsRune("[(]", rune(left)) || !strings.ContainsRune("])[", rune(right)) { + return "" + } + lower, upper, interval := strings.Cut(selector[1:len(selector)-1], ",") + if strings.ContainsAny(lower+upper, "[](),") || lower == "" && upper == "" { + return "" + } + if !interval { + if left != '[' || right != ']' { + return "" + } + upper = lower + } + for i := len(versions) - 1; i >= 0; i-- { + v := versions[i] + lo, hi := compareVersions(v, lower), compareVersions(v, upper) + if lower != "" && (lo < 0 || lo == 0 && left != '[') { + continue + } + if upper == "" || hi < 0 || hi == 0 && right == ']' { + return v + } + } + return "" +} + +func readGradleFile(path string) string { + if info, err := os.Stat(path); err != nil || !info.Mode().IsRegular() || info.Size() > maxPOMSize { + return "" + } + f, err := os.Open(path) + if err != nil { + return "" + } + defer f.Close() + b, err := io.ReadAll(io.LimitReader(f, maxPOMSize+1)) + if err != nil || len(b) > maxPOMSize { + return "" + } + return string(b) +} + +// Consume comments and quoted strings as whole tokens so neither contributes +// declarations. The parser only inspects the direct body of dependencies {}. +var gradleToken = regexp.MustCompile(`(?s)/\*.*?(?:\*/|$)|//[^\n]*|""".*?(?:"""|$)|'''.*?(?:'''|$)|"(?:\\.|[^"\\])*(?:"|$)|'(?:\\.|[^'\\])*(?:'|$)|[a-zA-Z0-9_.$]+|[^\s]`) +var gradleConfiguration = regexp.MustCompile(`^(?:[a-zA-Z0-9_]*(?:Implementation|Api|CompileOnly|RuntimeOnly|AnnotationProcessor)|implementation|api|compileOnly|runtimeOnly|annotationProcessor|compile|runtime|testCompile|testRuntime)$`) + +type gradleTokens string + +func (s *gradleTokens) next() string { + for { + i := gradleToken.FindStringIndex(string(*s)) + if i == nil { + return "" + } + tok := string((*s)[i[0]:i[1]]) + *s = (*s)[i[1]:] + if !strings.HasPrefix(tok, "//") && !strings.HasPrefix(tok, "/*") { + return tok + } + } +} + +type gradleProject struct { + own, children map[string][]pomDep +} + +func gradleDeclarations(script string, catalog map[string]pomDep) gradleProject { + tokens := gradleTokens(script) + var blocks []string + out := gradleProject{own: make(map[string][]pomDep), children: make(map[string][]pomDep)} + buildscript := 0 + prev := "" + for tok := tokens.next(); tok != ""; tok = tokens.next() { + switch tok { + case "{": + blocks = append(blocks, prev) + if prev == "buildscript" { + buildscript++ + } + case "}": + if n := len(blocks); n > 0 { + if blocks[n-1] == "buildscript" { + buildscript-- + } + blocks = blocks[:n-1] + } + default: + inDeps := buildscript == 0 && len(blocks) > 0 && blocks[len(blocks)-1] == "dependencies" + if inDeps && gradleConfiguration.MatchString(tok) { + if dep := gradleArgument(tokens, catalog); dep.ArtifactID != "" { + group := tok + switch tok { + case "api", "implementation", "compileOnly", "compile": + group = "" + case "testCompile", "testApi", "testCompileOnly", "testImplementation": + group = "testCompileClasspath" + } + sub := slices.Contains(blocks, "subprojects") + if !sub { + out.own[group] = append(out.own[group], dep) + } + if sub || slices.Contains(blocks, "allprojects") { + out.children[group] = append(out.children[group], dep) + } + } + } + } + prev = tok + } + return out +} + +func gradleArgument(tokens gradleTokens, catalog map[string]pomDep) pomDep { + arg := tokens.next() + if arg == "(" { + arg = tokens.next() + } + if tokens.next() == "+" { + return pomDep{} + } + if name, ok := strings.CutPrefix(arg, "libs."); ok { + return catalog[name] + } + if len(arg) >= 2 && (arg[0] == '"' || arg[0] == '\'') && arg[len(arg)-1] == arg[0] { + return gradleCoordinate(arg[1 : len(arg)-1]) + } + return pomDep{} +} + +func gradleCoordinate(s string) pomDep { + parts := strings.Split(s, ":") + if len(parts) < 2 || len(parts) > 4 || strings.ContainsAny(s, "$@ \t\n\"'") { + return pomDep{} + } + for _, part := range parts { + if !safeSegment(part) { + return pomDep{} + } + } + d := pomDep{GroupID: parts[0], ArtifactID: parts[1]} + if len(parts) >= 3 { + d.Version = parts[2] + } + if len(parts) == 4 { + d.Classifier = parts[3] + } + return d +} + +// Catalog aliases are indexed by the dotted accessor Gradle generates. Only +// aliases used by a build script become roots of the dependency graph. +func readGradleCatalog(path string, logf func(string, ...any)) map[string]pomDep { + src := readGradleFile(path) + if src == "" { + return nil + } + var catalog struct { + Libraries map[string]any + Versions map[string]any + } + if _, err := toml.Decode(src, &catalog); err != nil { + logf("skipping Gradle version catalog %s: %v", path, err) + return nil + } + aliases := make(map[string]pomDep, len(catalog.Libraries)) + accessor := strings.NewReplacer("-", ".", "_", ".") + for alias, lib := range catalog.Libraries { + var dep pomDep + switch value := lib.(type) { + case string: + dep = gradleCoordinate(value) + case map[string]any: + strict := false + module, ok := value["module"].(string) + if !ok { + group, _ := value["group"].(string) + name, _ := value["name"].(string) + module = group + ":" + name + } + if v, exists := value["version"]; exists { + if ref, ok := v.(map[string]any); ok { + if key, ok := ref["ref"].(string); ok { + v = catalog.Versions[key] + } + } + version, _ := v.(string) + if rich, ok := v.(map[string]any); ok { + version, strict = rich["strictly"].(string) + if !strict { + version, _ = rich["require"].(string) + } + } + module += ":" + version + } + dep = gradleCoordinate(module) + dep.strict = strict + } + aliases[accessor.Replace(alias)] = dep + } + return aliases +} diff --git a/internal/deps/gradle_test.go b/internal/deps/gradle_test.go new file mode 100644 index 0000000..f84b1d9 --- /dev/null +++ b/internal/deps/gradle_test.go @@ -0,0 +1,111 @@ +package deps + +import ( + "os" + "path/filepath" + "reflect" + "testing" +) + +func TestGradleJarsFollowOnlyDeclaredDependencies(t *testing.T) { + home := t.TempDir() + t.Setenv("GRADLE_USER_HOME", home) + cache := filepath.Join(home, "caches", "modules-2", "files-2.1", "org.example") + put := func(artifact, version, suffix, content string) string { + t.Helper() + dir := filepath.Join(cache, artifact, version, "hash-"+suffix) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + p := filepath.Join(dir, artifact+"-"+version+suffix) + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + return p + } + put("starter", "1.9", ".jar", "") + starter := put("starter", "1.10", ".jar", "") + put("starter", "1.10", ".pom", ` + org.examplenested2 + `) + nested := put("nested", "2", ".jar", "") + put("nested", "1", ".jar", "") + put("nested", "1", ".pom", ` + org.exampleevicted-child1 + `) + put("evicted-child", "1", ".jar", "") + testNested := put("nested", "3", ".jar", "") + put("assertions", "1", ".jar", "") + assertions := put("assertions", "2", ".jar", "") + put("shared", "1", ".jar", "") + shared := put("shared", "2", ".jar", "") + for _, pair := range [][2]string{{"a", "b"}, {"b", "a"}} { + put(pair[0], "1", ".jar", "") + put(pair[0], "1", ".pom", `org.example`+pair[1]+`2`) + } + a := put("a", "2", ".jar", "") + b := put("b", "2", ".jar", "") + sources := put("nested", "2", "-sources.jar", "") + put("unused", "1", ".jar", "") + put("pinned", "2", ".jar", "") + put("ranged", "1.2", ".jar", "") + ranged := put("ranged", "1.9", ".jar", "") + put("ranged", "2.0", ".jar", "") + strict := put("strict", "2", ".jar", "") + put("strict", "3", ".jar", "") + catalog := filepath.Join(t.TempDir(), "libs.versions.toml") + if err := os.WriteFile(catalog, []byte(`[versions] + pin = { strictly = "2" } + [libraries] + strict = { module = "org.example:strict", version.ref = "pin" } + `), 0o644); err != nil { + t.Fatal(err) + } + root := t.TempDir() + rootScript := filepath.Join(root, "build.gradle") + if err := os.WriteFile(rootScript, []byte("subprojects { dependencies { implementation 'org.example:shared:1' } }"), 0o644); err != nil { + t.Fatal(err) + } + module := filepath.Join(root, "service") + if err := os.Mkdir(module, 0o755); err != nil { + t.Fatal(err) + } + script := filepath.Join(module, "build.gradle") + body := `buildscript { dependencies { implementation 'org.example:unused:1' } } + dependencies { + implementation 'org.example:starter' + implementation 'org.example:nested:1' + api 'org.example:ranged:[1.0,2.0)' + implementation libs.strict + testRuntimeOnly 'org.example:nested:3' + api 'org.example:a:1' + api 'org.example:b:1' + implementation 'org.example:shared:2' + testCompileOnly 'org.example:assertions:1' + testImplementation 'org.example:assertions:2' + testImplementation("org.example:pinned:1") + // runtimeOnly 'org.example:unused:1' + /* compileOnly("org.example:unused:1") */ + constraints { api("org.example:unused:1") } + implementation("org.example:unused:" + version) + } + ` + if err := os.WriteFile(script, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + got, err := GradleJars(ctx(t), []string{rootScript, script}, catalog, t.Logf) + want := []Jar{ + {Coord: "org.example:starter:1.10", Path: starter}, + {Coord: "org.example:nested:2", Path: nested, Sources: sources}, + {Coord: "org.example:ranged:1.9", Path: ranged}, + {Coord: "org.example:strict:2", Path: strict}, + {Coord: "org.example:a:2", Path: a}, + {Coord: "org.example:b:2", Path: b}, + {Coord: "org.example:shared:2", Path: shared}, + {Coord: "org.example:assertions:2", Path: assertions}, + {Coord: "org.example:nested:3", Path: testNested}, + } + if err != nil || !reflect.DeepEqual(got, want) { + t.Fatalf("GradleJars = %+v, %v; want %+v", got, err, want) + } +} diff --git a/internal/deps/jars.go b/internal/deps/jars.go index 144426d..8ddfc92 100644 --- a/internal/deps/jars.go +++ b/internal/deps/jars.go @@ -1,6 +1,6 @@ // Package deps lets navigation follow names into a project's dependency -// jars. It finds the jars of the Maven projects in a working tree in the -// local repository (MavenJars) and the jars a tree keeps itself (TreeJars), +// jars. It finds declared jars in the local Maven repository (MavenJars) +// and Gradle cache (GradleJars), plus the jars a tree keeps itself (TreeJars), // lists the classes each one declares and, // for a class a lookup needs, returns Java source: the entry of the jar's // -sources.jar when it was downloaded, else a stub of signatures written diff --git a/internal/deps/maven.go b/internal/deps/maven.go index d68a538..b4002b2 100644 --- a/internal/deps/maven.go +++ b/internal/deps/maven.go @@ -44,6 +44,7 @@ type Jar struct { } type pomDep struct { + strict bool // an exact or bounded Gradle strictly selector GroupID string `xml:"groupId"` ArtifactID string `xml:"artifactId"` Version string `xml:"version"` @@ -131,11 +132,7 @@ type maven struct { // the modules' own dependencies first, then theirs. repo is the local // repository; a module of the working tree is never one of the jars. func MavenJars(ctx context.Context, poms []string, repo string, logf func(string, ...any)) ([]Jar, error) { - if logf == nil { - logf = func(string, ...any) {} - } - m := &maven{ctx: ctx, repo: &localRepo{root: repo, versions: map[string][]string{}}, raw: map[string]*pomXML{}, - models: map[string]*model{}, building: map[string]bool{}, tree: map[string]string{}, logf: logf} + m := newMaven(ctx, &localRepo{root: repo, versions: map[string][]string{}}, logf) sort.Strings(poms) var roots []*model for _, p := range poms { @@ -144,7 +141,20 @@ func MavenJars(ctx context.Context, poms []string, repo string, logf func(string roots = append(roots, mo) } } - if err := ctx.Err(); err != nil { + return m.resolve(roots, nil) +} + +func newMaven(ctx context.Context, repo *localRepo, logf func(string, ...any)) *maven { + if logf == nil { + logf = func(string, ...any) {} + } + return &maven{ctx: ctx, repo: repo, raw: map[string]*pomXML{}, models: map[string]*model{}, + building: map[string]bool{}, tree: map[string]string{}, logf: logf} +} + +// resolve follows the POMs of the direct dependencies supplied by the build files. +func (m *maven) resolve(roots []*model, chooseGradleVersion func(pomDep, string) string) ([]Jar, error) { + if err := m.ctx.Err(); err != nil { return nil, err } type item struct { @@ -161,16 +171,16 @@ func MavenJars(ctx context.Context, poms []string, repo string, logf func(string seen := map[string]bool{} var out []Jar for len(queue) > 0 && len(out) < maxArtifacts { - if err := ctx.Err(); err != nil { + if err := m.ctx.Err(); err != nil { return nil, err } it := queue[0] queue = queue[1:] d := it.dep - if d.GroupID == "" || d.ArtifactID == "" || seen[gaOf(d)+":"+d.Classifier] { + key := gaOf(d) + ":" + d.Classifier + if d.GroupID == "" || d.ArtifactID == "" || (chooseGradleVersion == nil && seen[key]) { continue } - seen[gaOf(d)+":"+d.Classifier] = true if _, own := m.tree[gaOf(d)]; own { continue // a module of the working tree: its sources are indexed } @@ -179,6 +189,13 @@ func MavenJars(ctx context.Context, poms []string, repo string, logf func(string version = md.Version } version = m.repo.pick(d.GroupID, d.ArtifactID, version) + if chooseGradleVersion != nil { + version = chooseGradleVersion(d, version) + if seen[key] { + continue + } + } + seen[key] = true if version == "" { continue } @@ -395,7 +412,8 @@ func (m *maven) parentOf(path string, p *pomXML) *model { if p.Parent.RelativePath != nil { rel = strings.TrimSpace(*p.Parent.RelativePath) } - if rel != "" { + // Gradle's hash directories never contain a source tree's relative parent. + if rel != "" && !m.repo.gradle { cand := filepath.Join(filepath.Dir(path), filepath.FromSlash(rel)) if fi, err := os.Stat(cand); err == nil && fi.IsDir() { cand = filepath.Join(cand, "pom.xml") @@ -529,10 +547,14 @@ func LocalRepository(home string) string { // localRepo reads a Maven repository layout. type localRepo struct { root string + gradle bool // Gradle files-2.1 layout: literal group ID, one hash directory per file versions map[string][]string // listed version directories by "group:artifact" } func (r *localRepo) dir(group, artifact string) string { + if r.gradle { + return filepath.Join(r.root, group, artifact) + } return filepath.Join(r.root, filepath.FromSlash(strings.ReplaceAll(group, ".", "/")), artifact) } @@ -546,7 +568,21 @@ func (r *localRepo) file(group, artifact, version, classifier, ext string) (stri if classifier != "" { name += "-" + classifier } - p := filepath.Join(r.dir(group, artifact), version, name+"."+ext) + dir := filepath.Join(r.dir(group, artifact), version) + name += "." + ext + if r.gradle { + entries, _ := os.ReadDir(dir) + for _, hash := range entries { + if hash.IsDir() { + p := filepath.Join(dir, hash.Name(), name) + if fi, err := os.Stat(p); err == nil && fi.Mode().IsRegular() { + return p, true + } + } + } + return "", false + } + p := filepath.Join(dir, name) fi, err := os.Stat(p) if err != nil || !fi.Mode().IsRegular() { return "", false @@ -562,7 +598,13 @@ func (r *localRepo) jar(group, artifact, version, classifier string) (string, bo // its POM or jar, else the highest version it has (a range, an unresolved // property or a version that was never downloaded). func (r *localRepo) pick(group, artifact, version string) string { + if r.gradle && strings.ContainsAny(version, "[](),") { + return gradleRangeVersion(version, r.list(group, artifact)) + } if version != "" && !strings.ContainsAny(version, "${[(,") { + if r.gradle { + return version // look up the declared version, including classifier-only jars + } if _, ok := r.file(group, artifact, version, "", "pom"); ok { return version } diff --git a/internal/workspace/deps_test.go b/internal/workspace/deps_test.go index f095f47..004f9fd 100644 --- a/internal/workspace/deps_test.go +++ b/internal/workspace/deps_test.go @@ -82,6 +82,51 @@ const depsPOM = `com.acmeappcom.examplelib1.0 ` +func TestDefinitionIntoGradleDependencyAfterCatalogEdit(t *testing.T) { + root, home := t.TempDir(), t.TempDir() + t.Setenv("GRADLE_USER_HOME", home) + cache := filepath.Join(home, "caches", "modules-2", "files-2.1") + for hash, file := range map[string]string{"a": "helper-2.0.jar", "b": "helper-2.0-sources.jar"} { + dir := filepath.Join(cache, "com.example", "helper", "2.0", hash) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + copyFile(t, filepath.Join("..", "deps", "testdata", "fixture", file), filepath.Join(dir, file)) + } + before := treeHash(t, cache) + src := "import com.example.helper.Helper;\nclass A { String text = Helper.shout(\"x\"); }" + catalog := "gradle/libs.versions.toml" + write(t, root, map[string]string{ + "app/A.java": src, "app/build.gradle.kts": "dependencies { implementation(libs.example.helper) }", + catalog: "[libraries]\nexample-helper = 'com.example:missing:1.0'", + }) + w := New(Options{Root: root, State: t.TempDir(), Dependencies: true, ListFiles: walkFiles, Freshness: -1}) + doc := w.DocOf(filepath.Join(root, "app", "A.java")) + lookup := func() (Target, bool) { + t.Helper() + target, ok, err := w.Definition(ctx(t), doc, []byte(src), at(t, src, "shout", 0, 1)) + if err != nil { + t.Fatal(err) + } + return target, ok + } + if _, ok := lookup(); ok { + t.Fatal("resolved a cached library that the project did not declare") + } + write(t, root, map[string]string{catalog: "[versions]\nv = '2.0'\n[libraries]\nexample-helper = { module = 'com.example:helper', version.ref = 'v' }"}) + target, ok := lookup() + if !ok { + t.Fatal("Gradle catalog edit did not make Helper.shout navigable") + } + body, err := os.ReadFile(target.File) + if err != nil || !strings.Contains(string(body), "return text.toUpperCase();") { + t.Errorf("expected the cached sources JAR: %s, %v", body, err) + } + if treeHash(t, cache) != before { + t.Error("the Gradle cache changed") + } +} + const useDeps = `package com.acme; import com.example.lib.Container; diff --git a/internal/workspace/workspace.go b/internal/workspace/workspace.go index ea45427..434819e 100644 --- a/internal/workspace/workspace.go +++ b/internal/workspace/workspace.go @@ -14,8 +14,8 @@ // text again. // // Names the folder does not declare resolve into the JDK's sources when a JDK -// with sources is installed, and into the jars of the folder's Maven -// dependencies that the local repository holds (package deps). Their +// with sources is installed, and into the locally cached jars of the folder's Maven +// and Gradle dependencies (package deps). Their // declarations are extracted, one file at a time, into read-only copies // under the state directory, which the editor opens as ordinary files; a // query from such a copy is answered as a library source. @@ -71,9 +71,8 @@ type Options struct { // FindJDK locates the JDK whose sources are used; nil disables them. FindJDK func(context.Context) (jdk.JDK, bool) // Dependencies enables navigation into the folder's dependency jars; - // it needs State. They are the Maven dependencies its pom.xml files - // declare, read from MavenRepo, and the jars the tree keeps itself - // (deps.TreeJars). + // it needs State. This includes dependencies from MavenRepo, the Gradle + // cache and the jars the tree keeps itself (deps.TreeJars). Dependencies bool // MavenRepo is the local Maven repository; "" leaves Maven dependencies // out. @@ -588,21 +587,19 @@ func (w *Workspace) runScan(run *scanRun) { if err != nil { err = fmt.Errorf("list source files: %w", err) } - var poms []string - var tree []deps.Jar - var inputs map[string]stamp + var inputs dependencyInputs useDeps := err == nil && w.opt.Dependencies && w.opt.State != "" if useDeps { - poms, tree, inputs = w.depInputs(all) + inputs = w.depInputs(all) } - lookDeps := useDeps && (oldInputs == nil || !sameStamps(oldInputs, inputs) || time.Since(depsAt) > depsRefresh) + lookDeps := useDeps && (oldInputs == nil || !sameStamps(oldInputs, inputs.stamps) || time.Since(depsAt) > depsRefresh) var depSet *deps.Set var depsErr error depsDone := make(chan struct{}) if lookDeps { go func() { defer close(depsDone) - depSet, depsErr = w.readDeps(ctx, poms, tree) + depSet, depsErr = w.readDeps(ctx, inputs) }() } else { close(depsDone) @@ -632,7 +629,7 @@ func (w *Workspace) runScan(run *scanRun) { if depsErr != nil { w.opt.Logf("dependency jars unavailable: %v", depsErr) } else { - w.deps, w.inputs, w.depsAt = depSet, inputs, started + w.deps, w.inputs, w.depsAt = depSet, inputs.stamps, started changed = true } } @@ -692,23 +689,33 @@ func (w *Workspace) library() *codenav.Library { }) } -// depInputs returns the absolute paths of the folder's pom.xml files, the -// jars its tree keeps, and the stamps of the jars and their build inputs. -func (w *Workspace) depInputs(all []string) (poms []string, tree []deps.Jar, inputs map[string]stamp) { - inputs = map[string]stamp{} +type dependencyInputs struct { + poms, gradleScripts []string + catalog string + tree []deps.Jar + stamps map[string]stamp +} + +// depInputs tracks the build inputs whose changes invalidate the classpath. +func (w *Workspace) depInputs(all []string) dependencyInputs { + inputs := dependencyInputs{stamps: map[string]stamp{}} note := func(p string) bool { fi, err := os.Stat(p) if err != nil || !fi.Mode().IsRegular() { return false } - inputs[p] = stamp{size: fi.Size(), mod: fi.ModTime()} + inputs.stamps[p] = stamp{size: fi.Size(), mod: fi.ModTime()} return true } for _, p := range all { switch path.Base(p) { case "pom.xml": if w.opt.MavenRepo != "" && note(w.abs(p)) { - poms = append(poms, w.abs(p)) + inputs.poms = append(inputs.poms, w.abs(p)) + } + case "build.gradle", "build.gradle.kts": + if note(w.abs(p)) { + inputs.gradleScripts = append(inputs.gradleScripts, w.abs(p)) } case ".classpath": note(w.abs(p)) @@ -718,14 +725,18 @@ func (w *Workspace) depInputs(all []string) (poms []string, tree []deps.Jar, inp note(w.abs(path.Join(path.Dir(p), "build.properties"))) } } - tree = deps.TreeJars(w.opt.Root, all, w.opt.MavenRepo) - for _, j := range tree { + if len(inputs.gradleScripts) > 0 { + inputs.catalog = w.abs("gradle/libs.versions.toml") + note(inputs.catalog) + } + inputs.tree = deps.TreeJars(w.opt.Root, all, w.opt.MavenRepo) + for _, j := range inputs.tree { note(j.Path) if j.Sources != "" { note(j.Sources) } } - return poms, tree, inputs + return inputs } func sameStamps(a, b map[string]stamp) bool { @@ -740,21 +751,28 @@ func sameStamps(a, b map[string]stamp) bool { return true } -// readDeps lists the jars of the Maven dependencies the poms declare, then -// the jars the tree keeps. -func (w *Workspace) readDeps(ctx context.Context, poms []string, tree []deps.Jar) (*deps.Set, error) { +// readDeps resolves declared dependencies before adding the jars in the tree. +func (w *Workspace) readDeps(ctx context.Context, inputs dependencyInputs) (*deps.Set, error) { var jars []deps.Jar - if len(poms) > 0 { + if len(inputs.poms) > 0 { var err error - if jars, err = deps.MavenJars(ctx, poms, w.opt.MavenRepo, w.opt.Logf); err != nil { + if jars, err = deps.MavenJars(ctx, inputs.poms, w.opt.MavenRepo, w.opt.Logf); err != nil { return nil, err } } maven := len(jars) - jars = append(jars, tree...) + if len(inputs.gradleScripts) > 0 { + gradle, err := deps.GradleJars(ctx, inputs.gradleScripts, inputs.catalog, w.opt.Logf) + if err != nil { + return nil, err + } + jars = append(jars, gradle...) + } + gradle := len(jars) - maven + jars = append(jars, inputs.tree...) set := deps.Open(jars, w.opt.Logf) - w.opt.Logf("dependency jars: %d of %d resolved (%d Maven, %d in the working tree), %d classes", - set.Len(), len(jars), maven, len(tree), set.Classes()) + w.opt.Logf("dependency jars: %d of %d resolved (%d Maven, %d Gradle, %d in the working tree), %d classes", + set.Len(), len(jars), maven, gradle, len(inputs.tree), set.Classes()) return set, nil } diff --git a/licenses/BurntSushi-toml-LICENSE b/licenses/BurntSushi-toml-LICENSE new file mode 100644 index 0000000..01b5743 --- /dev/null +++ b/licenses/BurntSushi-toml-LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013 TOML authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/LICENSE b/licenses/lithe-sdk-LICENSE similarity index 100% rename from vendor/LICENSE rename to licenses/lithe-sdk-LICENSE diff --git a/scripts/package.mjs b/scripts/package.mjs index 8c0a405..afd8bb7 100644 --- a/scripts/package.mjs +++ b/scripts/package.mjs @@ -29,7 +29,7 @@ const TARGETS = [ { platform: "windows-arm64", goos: "windows", goarch: "arm64" }, ]; // Files copied next to plugin.json in every archive. -const INCLUDED = ["LICENSE", "THIRD_PARTY_NOTICES.md", "vendor/LICENSE"]; +const INCLUDED = ["LICENSE", "THIRD_PARTY_NOTICES.md", "licenses/lithe-sdk-LICENSE", "licenses/BurntSushi-toml-LICENSE"]; const manifest = JSON.parse(readFileSync(`${PACKAGE_DIR}/plugin.json`, "utf8")); const problems = []; diff --git a/sdk.lock.json b/sdk.lock.json index 6b69f03..9fa89ff 100644 --- a/sdk.lock.json +++ b/sdk.lock.json @@ -7,7 +7,7 @@ "files": [ { "upstream": "shared/plugins/LICENSE", - "path": "vendor/LICENSE", + "path": "licenses/lithe-sdk-LICENSE", "sha256": "93ff573f89d32394501fcc82767e73b1824add861f088bbd3eec9e0afae20d21" }, {