diff --git a/.gitignore b/.gitignore index a53e981..c358de7 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ extension/target/ .DS_Store .cache/ settings-backend/target/ +provider/target/ diff --git a/README.md b/README.md index 5b2ed5c..5828c97 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ | 彩色输出 | 每条 Maven 命令都带 `-Dstyle.color=always`,即使输出不是终端也保留 Maven 的颜色;Lithe 的构建、运行和测试控制台按颜色显示 `[INFO]`、`[WARNING]`、`[ERROR]` 和 `BUILD SUCCESS`,匹配诊断前会先去掉颜色转义 | | 依赖 | 显示整个反应堆或单个模块的依赖树(含作用域和传递依赖),反应堆内未安装的兄弟模块也能解析 | | 同步 | `pom.xml`、`.mvn/maven.config`、`.mvn/extensions.xml` 变化后重新读取项目 | +| 运行配置 | Spring Boot 应用和写明主类的 Java 应用自动出现在标题栏的运行配置里,可以运行和编辑参数,见下面的「运行应用」 | ## 设置和构建选项 @@ -65,6 +66,8 @@ JDK 是构建选项而不是插件设置,因为契约 v0 的插件设置不能 3. 环境变量 `MAVEN_HOME` 下的 `bin/mvn`; 4. `PATH` 里的 `mvn`。 +运行前的编译由构建提供者执行:它用 Lithe 按上面的顺序解析出的程序;只拿到命令名(例如 `mvn`)时,按 `PATH` 查找,Windows 上再按 `PATHEXT` 补扩展名(`mvn.cmd`),找不到时报 `maven.run.noMaven`。 + 要求 Maven 3.6.3 或更新版本、Java 8 或更新版本。没有 Maven 的话可以先安装: ```bash @@ -83,11 +86,39 @@ brew install maven 选中模块时用 `-Dlithe.dependenciesProject` 只导出这个模块,否则导出反应堆里的每个模块。 - 输出文件由 Lithe 在这个工作区的插件状态目录(插件包之外的可写目录)里分配,Maven 退出后读取并删除。 - 读取项目和依赖不会编译或打包,也不会生成 `target/`;解析依赖时只读 POM,不下载依赖 jar。 +- 准备运行时,扩展在构建结束后把类路径和主类写到 `-Dlithe.runOutput` 指定的临时文件(见「运行应用」), + 构建失败时不写。 - 没有 Lithe 的属性时扩展什么都不做;插件目录在运行时保持只读。 读取项目会执行 POM 中声明的 Maven 扩展和插件,首次读取还可能联网下载插件描述,所以这两条命令都声明了 `executesProjectCode` 和 `mayUseNetwork`,Lithe 会先确认你信任这个工作区。 +## 运行应用 + +读取项目时,扩展把能运行的应用列为构建模型里的 target,`plugin.json` 的 `run` 把它们变成运行配置: + +| 运行配置 | 来源 | 执行方式 | +| --- | --- | --- | +| `spring-boot` | 源码根里带 `@SpringBootApplication` 的类(每个一条);没有这样的类但用了 `spring-boot-maven-plugin` 的模块(一条,主类取插件的 `mainClass` 或 `start-class`) | 服务 | +| `application` | `exec-maven-plugin` 的 `mainClass` 或 jar 清单 `archive/manifest/mainClass` 写明主类的模块 | 应用 | + +列 target 只读源码开头和 POM,不编译。运行时 Lithe 启动随包的构建提供者 `lib/lithe-maven-provider.jar` +(源码在 `provider/`),由它准备运行: + +1. 用你的 Maven(Lithe 解析出的那个,否则按 `mvnw`、`MAVEN_HOME`、`PATH` 查找)和当前构建选项运行 + `-pl <模块> -am process-classes`,编译这个模块和它依赖的反应堆模块,输出显示在运行窗口。 +2. 扩展在构建结束后写出运行时类路径(模块输出目录加 compile/runtime/system 依赖,兄弟模块用反应堆里的 + `target/classes`,不需要 `install`)和编译出的主类。 +3. 返回 `java -cp <类路径> <主类>`,由 Lithe 用项目的 JDK 启动并管理这个进程。主类依次取运行配置的入口、 + target 的 `mainClass`、编译结果里唯一的主类(Spring Boot 优先带注解的类);有多个时报错并列出候选。 + 类路径超过 24 000 个字符时写进 `target/lithe-run/` 下只含清单的 jar,避开 Windows 命令行长度限制。 +4. 清单为 Spring Boot 运行声明了按配置类型连接的调试(`debug.configurationType: java`):宿主带着调试端口请求时, + 提供者加 `-agentlib:jdwp=…,suspend=y`,服务停在启动处等 Java 调试器连上。Lithe 桌面端还没有实现这段宿主流程 + ([1lck/Lithe-IDEA#2107](https://github.com/1lck/Lithe-IDEA/issues/2107)),目前点调试会提示这个配置不能调试。 + +不经过 `spring-boot:run`,Lithe 停止的就是应用进程本身。运行配置里的 JVM 参数、程序参数、环境变量和工作目录 +原样带到启动命令。 + ## 安装 1. 从 [Releases](https://github.com/Lithe-IDEA/lithe-plugin-maven/releases) 下载对应平台的包:macOS 用 @@ -167,6 +198,10 @@ node scripts/verify-scripts.mjs --host-bundle /Applications/Lithe.app - `TestOfficialMavenPluginBuildsAReactor`(宿主的 `desktop/internal/workbench` 包):读取两模块反应堆的模型和依赖树, 改 Maven executable 设置后重新读取并运行 `compile`,最后确认插件安装目录没有被写入。 +- `TestOfficialMavenPluginRunsASpringBootApplication`(`desktop/internal/workbench` 包):和 Java Support 插件包一起安装, + 打开一个真实的两模块 Spring Boot 3.5 项目(`spring-boot-starter-web`),确认运行配置下拉只列出 `ShopApplication`(服务), + 用运行配置编辑器保存 JVM 参数、程序参数和环境变量,运行后检查控制台里的 Maven 构建日志和 Spring Boot 启动日志, + 请求 `/hello` 确认三项设置都传到了进程;停止后确认服务不再响应、端口已释放,插件安装目录没有被写入。 - `TestMavenPluginProjectGeneratesABuildableMavenProject`、`TestMavenPluginArchetypeRunsRealMaven`(`desktop/internal/projectgen` 包): 用清单里的两个新建项目条目生成项目。 @@ -177,10 +212,15 @@ node scripts/verify-scripts.mjs --host-bundle /Applications/Lithe.app ```bash node scripts/package.mjs -LITHE_TEST_MAVEN_PLUGIN_ARCHIVE="$PWD/dist/maven-build-<版本>-darwin.zip" node scripts/e2e-host.mjs +gh release download --repo Lithe-IDEA/lithe-plugin-java --pattern 'Lithe-Java-Support-*-darwin-arm64.zip' --dir .artifacts/java-plugin +LITHE_TEST_MAVEN_PLUGIN_ARCHIVE="$PWD/dist/maven-build-<版本>-darwin.zip" \ +LITHE_TEST_JAVA_PLUGIN_ARCHIVE="$PWD/.artifacts/java-plugin/Lithe-Java-Support-<版本>-darwin-arm64.zip" \ +node scripts/e2e-host.mjs ``` -- `LITHE_TEST_MAVEN_PLUGIN_ARCHIVE` 必须设置,脚本不会因为缺少插件包而跳过测试。 +- `LITHE_TEST_MAVEN_PLUGIN_ARCHIVE` 和 `LITHE_TEST_JAVA_PLUGIN_ARCHIVE` 都必须设置,脚本不会因为缺少插件包而跳过测试。 + 运行计划用 `java` 工具启动应用,这个工具由 Java Support 插件定义,所以运行测试要装上它。 +- 运行测试使用本机 `~/.m2` 和 Maven 设置,第一次运行会下载 Spring Boot 3.5 的依赖,项目需要 JDK 17 及以上。 - 新建项目测试读取 `LITHE_PLUGIN_MAVEN_DIR` 里的 `plugin.json` 和模板,默认是本仓库的 `io.github.lithe-idea.maven-build/`。 - 原型测试要从 Maven Central 下载原型插件,只在设置了 `LITHE_INTEGRATION_NETWORK=1` 和 `JAVA_HOME` 时运行,否则跳过。 diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index c608d94..08b7c5d 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -31,8 +31,9 @@ CI 在 Windows x64 上用 `mvn.cmd` 运行声明的模型、依赖和测试命 | `java-maven-toolbar-tooltips` | 构建窗口里的 Maven 图标、工具栏开关和提示 | implemented / pending | implemented / pending | 没有自动化覆盖 | | `maven-user-settings-editing` | 编辑用户级 `~/.m2/settings.xml` 的本地仓库 | missing / not-applicable | missing / not-applicable | — | | `maven-project-generators` | 新建项目:Maven 和 Maven Archetype | implemented / pending | implemented / pending | 2026-11-14 宿主端到端测试通过(macOS) | +| `maven-run-applications` | 运行配置:Spring Boot 服务和 Java 应用的运行(调试待宿主支持) | implemented / pending | implemented / pending | 2026-11-17 宿主端到端测试和 `scripts/test.mjs` 通过(macOS);`scripts/test.mjs` 在 Windows CI 通过 | -前六条从主仓库迁移,最后一条是本仓库新增,用来记录随测试一起迁来的新建项目测试。 +前六条从主仓库迁移;`maven-project-generators` 是本仓库新增,用来记录随测试一起迁来的新建项目测试;`maven-run-applications` 随运行配置一起新增([1lck/Lithe-IDEA#2074](https://github.com/1lck/Lithe-IDEA/issues/2074))。 ## java-maven-project @@ -195,3 +196,37 @@ ArtifactId);Maven Archetype 用内置或自定义原型,由 `mvn archetype 包里只有声明资源和纯 Java 的扩展 JAR,ARM64 与 x64 的差别只在用户自己的 JDK 和 Maven,所以 ARM64 用同一份包, 但在原生 ARM64 CI 或手工验收通过前不宣称通过。 + +## maven-run-applications + +**能力**:读取项目时把 Spring Boot 应用(`@SpringBootApplication` 类或 `spring-boot-maven-plugin`)和写明主类的 +Java 应用(`exec-maven-plugin`、jar 清单)列为 target,`run` 声明把它们变成运行配置;构建提供者 +`lib/lithe-maven-provider.jar` 准备运行:编译模块及其反应堆依赖,导出运行时类路径和主类,返回 `java -cp … 主类`。 +Spring Boot 运行声明了按配置类型连接的调试:宿主带调试端口请求时,提供者加 `-agentlib:jdwp` 挂起到调试器连上;Lithe 桌面端尚未实现这段宿主流程([1lck/Lithe-IDEA#2107](https://github.com/1lck/Lithe-IDEA/issues/2107)),所以调试目前不可用。 + +**证据**:`plugin.json` 的 `buildSystems[0].provider` 和 `buildSystems[0].run`、`extension/.../Applications.java`、 +`extension/.../RunExport.java`、`provider/`、`scripts/test.mjs` 的运行准备检查、`test/fixtures/reactor/service/`。 + +**依赖的宿主能力**:`buildProviders`(独立提供者进程和 `lithe/build/prepareRun`)、运行配置解析(`fromTargets`)、 +注册表连接调试(`debug.configurationType: java`,需要启用一个提供 `java` 类型 `attach` 的调试适配器)。 + +**最近验证**:2026-11-17,macOS arm64,插件 1.0.0 打包产物,宿主 `75edb9674`(合入 1lck/Lithe-IDEA#2102 的 main),`node scripts/e2e-host.mjs`: + +- `TestOfficialMavenPluginRunsASpringBootApplication` PASS(6.2s):和 Java Support 4.0.1 发布包一起安装,打开真实的两模块 + Spring Boot 3.5.13 项目;运行配置下拉只列出服务 `ShopApplication`;编辑器保存的 JVM 参数、程序参数和环境变量传到了进程 + (`/hello` 返回 `Hello, Lithe from eu-west`);控制台有 Maven 构建日志(含兄弟模块 `common`)和 Spring Boot 启动日志; + 停止后服务不再响应、端口释放;插件安装目录不变。同一轮 `TestOfficialMavenPluginBuildsAReactor` PASS。 +- `node scripts/test.mjs`:提供者的运行准备、类路径、主类选择、调试参数和编译失败。 + +这次实测发现并在 #2102 修好了四个宿主问题:声明了提供者进程的构建系统读取写文件的依赖命令时缺少输出文件、设置页按提供者读取模型、 +未命名的运行配置带上了运行 ID 前缀、准备运行时的构建输出没有显示。调试没有验收(宿主尚未支持,见上)。Windows 没有运行。 + +**验证方法**(macOS): + +1. 安装插件包,打开含 Spring Boot 模块和 `exec-maven-plugin` 模块的多模块项目,信任工作区。 +2. 标题栏运行配置菜单列出每个应用;选中 Spring Boot 应用点运行,运行窗口先显示 Maven 编译输出,再显示应用输出; + 停止后应用进程退出。 +3. 在运行配置编辑器里改 JVM 参数、程序参数、环境变量和入口,再次运行时生效。 +4. 宿主支持后(1lck/Lithe-IDEA#2107):启用 Java 调试适配器,调试 Spring Boot 应用,断点命中。 +5. 制造编译错误后运行,看到“Maven 编译失败”的提示,没有启动残缺的应用。 +6. 整个过程中插件安装目录不被写入。 diff --git a/e2e/host/desktop/internal/workbench/official_maven_plugin_e2e_test.go b/e2e/host/desktop/internal/workbench/official_maven_plugin_e2e_test.go index 6b30272..6055976 100644 --- a/e2e/host/desktop/internal/workbench/official_maven_plugin_e2e_test.go +++ b/e2e/host/desktop/internal/workbench/official_maven_plugin_e2e_test.go @@ -36,7 +36,19 @@ func installOfficialPluginArchive(t *testing.T, h *harness, archive, id string) if err != nil { t.Fatal(err) } + // The app gives its service these resolvers when it opens it (app.go); a provider or backend + // that runs on a tool, such as a jar on java, cannot start without them. + service.Backend.SetToolResolver(h.app.resolveBackendTool) + service.Backend.SetToolEntryResolver(h.app.resolveBackendToolEntry) + service.LanguageTool = h.app.resolveLanguageTool h.app.plugins = service + return installPluginArchiveInto(t, service, archive, id) +} + +// installPluginArchiveInto installs and enables archive in service's plugin root, next to the +// plugins already there, and returns the installed package directory. +func installPluginArchiveInto(t *testing.T, service *pluginservice.Service, archive, id string) string { + t.Helper() ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() plan, err := service.Installer.Prepare(ctx, plugininstall.Request{ArchivePath: archive, Root: service.Root, Source: plugintrust.Disk}) @@ -154,11 +166,12 @@ func awaitBuildModel(t *testing.T, h *harness, p *project, buildSystemID string, func runBuildTaskToEnd(t *testing.T, h *harness, p *project, projectID, taskID string, limit time.Duration) string { t.Helper() p.build.projectID, p.build.targetID, p.build.taskID = projectID, "", taskID - if _, err := h.app.runBuildTask(p, projectID, "", taskID, nil); err != nil { + op, err := h.app.runBuildTask(p, projectID, "", taskID, nil) + if err != nil { t.Fatalf("start %s: %v", taskID, err) } awaitStateWithin(t, h, limit, "the "+taskID+" task", func() bool { return p.build.operation == nil }) - output := strings.Join(p.build.output, "") + output := op.session.output.all() if p.build.status != h.app.text.Build.Succeeded { t.Fatalf("%s did not succeed: status=%q output=%q", taskID, p.build.status, output) } diff --git a/e2e/host/desktop/internal/workbench/official_maven_plugin_run_e2e_test.go b/e2e/host/desktop/internal/workbench/official_maven_plugin_run_e2e_test.go new file mode 100644 index 0000000..45aa04a --- /dev/null +++ b/e2e/host/desktop/internal/workbench/official_maven_plugin_run_e2e_test.go @@ -0,0 +1,258 @@ +package workbench + +import ( + "io" + "net" + "net/http" + "os" + "os/exec" + "strconv" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// springBootReactor writes a two-module Spring Boot web application below root: a plain +// library module and a web module that depends on it. The web endpoint answers with what the +// run configuration passed in, so one request proves the JVM argument, the program argument +// and the environment variable reached the process. +func springBootReactor(t *testing.T, root string) { + t.Helper() + writePluginFixture(t, root, map[string]string{ + "pom.xml": ` + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.13 + + + demo + shop + 1.0.0-SNAPSHOT + pom + 17 + commonweb + +`, + "common/pom.xml": ` + 4.0.0 + demoshop1.0.0-SNAPSHOT + common + +`, + "common/src/main/java/demo/common/Greeting.java": `package demo.common; + +public final class Greeting { + private Greeting() {} + + public static String of(String name) { + return "Hello, " + name; + } +} +`, + "web/pom.xml": ` + 4.0.0 + demoshop1.0.0-SNAPSHOT + web + + democommon${project.version} + org.springframework.bootspring-boot-starter-web + + + + org.springframework.bootspring-boot-maven-plugin + + + +`, + "web/src/main/java/demo/web/ShopApplication.java": `package demo.web; + +import demo.common.Greeting; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@SpringBootApplication +@RestController +public class ShopApplication { + public static void main(String[] args) { + SpringApplication.run(ShopApplication.class, args); + } + + @GetMapping("/hello") + public String hello() { + return Greeting.of(System.getProperty("shop.name")) + " from " + System.getenv("SHOP_REGION"); + } +} +`, + }) +} + +// freePort returns a loopback TCP port nothing listens on right now. +func freePort(t *testing.T) int { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + port := listener.Addr().(*net.TCPAddr).Port + if err := listener.Close(); err != nil { + t.Fatal(err) + } + return port +} + +// TestOfficialMavenPluginRunsASpringBootApplication covers the Maven archive's run +// configurations with the released Java Support archive, which declares the java tool the +// launch plan names: the Spring Boot application of a real reactor appears as a run +// configuration, the options saved in its editor reach the process, the run compiles the +// module and its reactor dependency and serves HTTP, and Stop ends the application. It uses +// the user's mvn and local repository, so the first run may download Spring Boot. +func TestOfficialMavenPluginRunsASpringBootApplication(t *testing.T) { + archive := os.Getenv("LITHE_TEST_MAVEN_PLUGIN_ARCHIVE") + if archive == "" { + t.Skip("set LITHE_TEST_MAVEN_PLUGIN_ARCHIVE to a maven-build--darwin.zip") + } + javaArchive := os.Getenv("LITHE_TEST_JAVA_PLUGIN_ARCHIVE") + if javaArchive == "" { + t.Fatal("set LITHE_TEST_JAVA_PLUGIN_ARCHIVE to a Lithe-Java-Support--darwin-.zip: its java tool launches the run") + } + if _, err := exec.LookPath("mvn"); err != nil { + t.Fatalf("mvn is not on PATH: %v", err) + } + h := newHarness(t, &testKernel{Client: core.NewClient()}) + installed := installOfficialPluginArchive(t, h, archive, "io.github.lithe-idea.maven-build") + installPluginArchiveInto(t, h.app.plugins, javaArchive, "io.github.lithe-idea.java-support") + before := packageDigest(t, installed) + root := t.TempDir() + springBootReactor(t, root) + h.open(root) + p := h.app.project + if p == nil { + t.Fatal("the reactor did not open") + } + + h.app.post(func(a *App) { a.loadTitleRunConfigs(p) }) + awaitBuildModel(t, h, p, "maven", 5*time.Minute) + awaitStateWithin(t, h, time.Minute, "the run configurations", func() bool { + return p.runConfigsSettled() && p.runConfigs.generation > 0 + }) + if p.runConfigs.failure != "" { + t.Fatalf("the run configurations failed: %s", p.runConfigs.failure) + } + var configuration *core.RunConfiguration + for index := range p.runConfigs.list { + if p.runConfigs.list[index].Name == "ShopApplication" { + configuration = &p.runConfigs.list[index] + } + } + if configuration == nil || len(p.runConfigs.list) != 1 { + t.Fatalf("the run configurations are %+v, want only ShopApplication", p.runConfigs.list) + } + if configuration.Execution != "service" { + t.Fatalf("ShopApplication runs as %q, want service", configuration.Execution) + } + if notice := p.noRunConfigurationsNotice(h.app.language()); notice != "" { + t.Fatalf("a project with a configuration explains that it has none: %q", notice) + } + id := configuration.ID + + // The editor's Save writes the local layer through Core, as a user does. + port := freePort(t) + h.app.post(func(a *App) { a.openRunConfigEditor(p, id) }) + awaitStateWithin(t, h, 30*time.Second, "the run configuration editor", func() bool { + return p.runConfigs.editor.open && !p.runConfigs.editor.loading + }) + h.app.post(func(a *App) { + e := &p.runConfigs.editor + e.runtimeArguments = "-Dshop.name=Lithe" + e.arguments = "--server.port=" + strconv.Itoa(port) + " --server.address=127.0.0.1" + e.environment = "SHOP_REGION=eu-west" + a.saveRunConfigEditor(p) + }) + awaitStateWithin(t, h, 30*time.Second, "the saved run configuration", func() bool { + return !p.runConfigs.editor.open && !p.runConfigs.loading && p.runConfigs.configuration(id) != nil + }) + if failure := p.runConfigs.editor.failure; failure != "" { + t.Fatalf("saving the run configuration failed: %s", failure) + } + + var op *buildOperation + var startErr error + h.app.post(func(a *App) { op, startErr = a.startRunConfiguration(p, id) }) + awaitStateWithin(t, h, 10*time.Second, "the run operation", func() bool { return op != nil || startErr != nil }) + if startErr != nil { + t.Fatalf("start ShopApplication: %v", startErr) + } + // The Run window's console of this run; it stays readable after the run ends. + output := func() string { return op.session.output.all() } + t.Cleanup(func() { + if t.Failed() { + t.Logf("status %q, run console:\n%s", p.build.status, output()) + } + }) + + url := "http://127.0.0.1:" + strconv.Itoa(port) + "/hello" + client := &http.Client{Timeout: 2 * time.Second} + var body string + deadline := time.Now().Add(5 * time.Minute) + for body == "" { + if time.Now().After(deadline) { + t.Fatalf("ShopApplication did not answer within 5 minutes; status=%q output:\n%s", p.build.status, output()) + } + // Pump only: settle waits for every background task, and the running application is one. + if err := h.driver.Pump(); err != nil { + t.Fatal(err) + } + if p.build.operation == nil { + t.Fatalf("the run ended before the application answered; status=%q output:\n%s", p.build.status, output()) + } + response, err := client.Get(url) + if err != nil { + time.Sleep(500 * time.Millisecond) + continue + } + data, readErr := io.ReadAll(io.LimitReader(response.Body, 4096)) + _ = response.Body.Close() + if readErr != nil || response.StatusCode != http.StatusOK { + t.Fatalf("GET %s = %d %q (%v)", url, response.StatusCode, data, readErr) + } + body = string(data) + } + if body != "Hello, Lithe from eu-west" { + t.Fatalf("GET /hello = %q, want the JVM argument and the environment variable", body) + } + // The console shows the Maven build the provider ran before the launch, then the + // application's own log; the log line after the one that opened the port may still be + // on its way when the endpoint first answers. + wants := []string{"BUILD SUCCESS", "common", "Tomcat started on port " + strconv.Itoa(port), "Started ShopApplication"} + awaitStateWithin(t, h, time.Minute, "the run console", func() bool { + text := output() + for _, want := range wants { + if !strings.Contains(text, want) { + return false + } + } + return true + }) + + h.app.post(func(a *App) { a.stopBuildOperation(p) }) + awaitStateWithin(t, h, time.Minute, "the stopped run", func() bool { return p.build.operation == nil }) + if _, err := client.Get(url); err == nil { + t.Fatal("ShopApplication still answers after Stop") + } + listener, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(port)) + if err != nil { + t.Fatalf("the application's port is still taken after Stop: %v", err) + } + _ = listener.Close() + + h.app.closeProject() + awaitStateWithin(t, h, 30*time.Second, "the closed project", func() bool { return h.app.project == nil }) + h.settle() + assertPackageUnchanged(t, installed, before) +} diff --git a/e2e/host/lithe-host.json b/e2e/host/lithe-host.json index ab474c8..66524cb 100644 --- a/e2e/host/lithe-host.json +++ b/e2e/host/lithe-host.json @@ -1,13 +1,14 @@ { "repository": "https://github.com/1lck/Lithe-IDEA.git", - "revision": "059d878d4284e1a1fd218aeaa56c29d9753d4dfa", + "revision": "75edb9674b655eb151b35ed34518731cec9e9b8b", "packages": { - "./internal/workbench": "^TestOfficialMavenPluginBuildsAReactor$", + "./internal/workbench": "^TestOfficialMavenPlugin(BuildsAReactor|RunsASpringBootApplication)$", "./internal/projectgen": "^TestMavenPlugin" }, "requiredEnvironment": { "LITHE_TEST_MAVEN_PLUGIN_ARCHIVE": "maven-build--darwin.zip to install, for example dist/maven-build-0.0.1-darwin.zip", - "LITHE_PLUGIN_MAVEN_DIR": "directory holding the plugin.json and templates; defaults to this repository's" + "LITHE_PLUGIN_MAVEN_DIR": "directory holding the plugin.json and templates; defaults to this repository's", + "LITHE_TEST_JAVA_PLUGIN_ARCHIVE": "Lithe-Java-Support--darwin-.zip from Lithe-IDEA/lithe-plugin-java releases; its java tool launches the run" }, "repositoryEnvironment": { "LITHE_PLUGIN_MAVEN_DIR": "io.github.lithe-idea.maven-build" diff --git a/extension/src/main/java/io/github/litheidea/maven/Applications.java b/extension/src/main/java/io/github/litheidea/maven/Applications.java new file mode 100644 index 0000000..f3d1bb2 --- /dev/null +++ b/extension/src/main/java/io/github/litheidea/maven/Applications.java @@ -0,0 +1,249 @@ +package io.github.litheidea.maven; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.apache.maven.model.Plugin; +import org.apache.maven.project.MavenProject; +import org.codehaus.plexus.util.xml.Xpp3Dom; + +/** + * The applications of one Maven project that Lithe offers as run + * configurations, read without compiling anything: + * + *
    + *
  • Spring Boot applications: every top-level Java class annotated with + * {@code @SpringBootApplication} in the compile source roots, as IntelliJ + * IDEA lists them. A project that applies {@code spring-boot-maven-plugin} + * without such a class (Kotlin sources, a generated class) is one + * application named after the project, with the main class the plugin or + * {@code start-class} configures, or none; run preparation then finds it in + * the compiled classes as the plugin itself does.
  • + *
  • Plain applications whose main class the build already names: + * {@code exec-maven-plugin}'s {@code mainClass} or the jar manifest's + * {@code mainClass}.
  • + *
+ * + *

Sources are scanned within fixed bounds so a large project cannot make + * reading the model slow: only {@code .java} files, at most {@link #MAX_FILES} + * per project, and only the first {@link #HEAD_BYTES} bytes of each, where a + * class declaration and its annotations are. + */ +final class Applications { + /** Target tag of a Spring Boot application; plugin.json's spring-boot run selects it. */ + static final String SPRING_BOOT = "spring-boot"; + /** Target tag of an application with a configured main class. */ + static final String APPLICATION = "java-application"; + /** Target property holding the fully qualified main class, when known. */ + static final String MAIN_CLASS = "mainClass"; + + static final int MAX_FILES = 20_000; + static final int HEAD_BYTES = 64 * 1024; + + private static final Pattern ANNOTATION = Pattern.compile( + "@(?:org\\.springframework\\.boot\\.autoconfigure\\.)?SpringBootApplication\\b"); + private static final Pattern PACKAGE = Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE); + private static final Pattern BLOCK_COMMENT = Pattern.compile("/\\*.*?\\*/", Pattern.DOTALL); + private static final Pattern LINE_COMMENT = Pattern.compile("//[^\\n]*"); + + private Applications() {} + + /** One application: its target name, tag and main class (null when unknown). */ + static final class Application { + final String name; + final String tag; + final String mainClass; + + Application(String name, String tag, String mainClass) { + this.name = name; + this.tag = tag; + this.mainClass = mainClass; + } + + Map target(String project) { + Map target = new LinkedHashMap<>(); + target.put("project", project); + target.put("name", name); + List tags = new ArrayList<>(); + tags.add(tag); + target.put("tags", tags); + Map properties = new LinkedHashMap<>(); + if (mainClass != null) { + properties.put(MAIN_CLASS, mainClass); + } + target.put("properties", properties); + return target; + } + } + + /** The applications of project, in a stable order. */ + static List of(MavenProject project) { + List result = new ArrayList<>(); + if ("pom".equals(project.getPackaging())) { + return result; + } + List annotated = annotatedClasses(project); + for (String main : annotated) { + result.add(new Application(name(main, annotated), SPRING_BOOT, main)); + } + if (!annotated.isEmpty()) { + return result; + } + Plugin boot = plugin(project, "org.springframework.boot", "spring-boot-maven-plugin"); + if (boot != null) { + String main = configured(boot, "mainClass"); + if (main == null) { + main = valid(project.getProperties().getProperty("start-class")); + } + result.add(new Application(project.getArtifactId(), SPRING_BOOT, main)); + return result; + } + String main = configured(plugin(project, "org.codehaus.mojo", "exec-maven-plugin"), "mainClass"); + if (main == null) { + main = manifestMainClass(plugin(project, "org.apache.maven.plugins", "maven-jar-plugin")); + } + if (main != null) { + result.add(new Application(simpleName(main), APPLICATION, main)); + } + return result; + } + + /** + * The simple class name, or the full one when another application of + * the project has the same simple name: Lithe identifies a target by its + * project and name. + */ + private static String name(String main, List all) { + String simple = simpleName(main); + int same = 0; + for (String other : all) { + if (simpleName(other).equals(simple)) { + same++; + } + } + return same > 1 ? main : simple; + } + + static String simpleName(String className) { + return className.substring(className.lastIndexOf('.') + 1); + } + + /** Fully qualified names of the annotated top-level classes, sorted. */ + static List annotatedClasses(MavenProject project) { + Map found = new TreeMap<>(); + int[] budget = {MAX_FILES}; + for (String root : project.getCompileSourceRoots()) { + File directory = new File(root); + if (!directory.isAbsolute()) { + directory = new File(project.getBasedir(), root); + } + scan(directory.toPath(), found, budget); + } + return new ArrayList<>(found.keySet()); + } + + private static void scan(Path root, Map found, int[] budget) { + if (!Files.isDirectory(root)) { + return; + } + Deque pending = new ArrayDeque<>(); + pending.push(root.toFile()); + while (!pending.isEmpty() && budget[0] > 0) { + File[] children = pending.pop().listFiles(); + if (children == null) { + continue; + } + for (File child : children) { + if (child.isDirectory()) { + pending.push(child); + } else if (child.getName().endsWith(".java") && budget[0]-- > 0) { + String main = annotatedClass(child); + if (main != null) { + found.put(main, Boolean.TRUE); + } + } + } + } + } + + /** The class file declares, when its head carries the annotation. */ + static String annotatedClass(File file) { + String text; + try (InputStream input = Files.newInputStream(file.toPath())) { + byte[] head = new byte[HEAD_BYTES]; + int length = 0; + for (int read; length < head.length && (read = input.read(head, length, head.length - length)) > 0; ) { + length += read; + } + text = new String(head, 0, length, StandardCharsets.UTF_8); + } catch (IOException error) { + return null; + } + if (!text.contains("SpringBootApplication")) { + return null; + } + text = LINE_COMMENT.matcher(BLOCK_COMMENT.matcher(text).replaceAll(" ")).replaceAll(" "); + if (!ANNOTATION.matcher(text).find()) { + return null; + } + String simple = file.getName().substring(0, file.getName().length() - ".java".length()); + if (!Pattern.compile("\\b(?:class|record)\\s+" + Pattern.quote(simple) + "\\b").matcher(text).find()) { + return null; + } + Matcher pkg = PACKAGE.matcher(text); + return pkg.find() ? pkg.group(1) + "." + simple : simple; + } + + private static Plugin plugin(MavenProject project, String groupId, String artifactId) { + for (Plugin plugin : project.getBuildPlugins()) { + if (groupId.equals(plugin.getGroupId()) && artifactId.equals(plugin.getArtifactId())) { + return plugin; + } + } + return null; + } + + /** A plugin's top-level configuration value, when it is a plain class name. */ + private static String configured(Plugin plugin, String name) { + if (plugin == null || !(plugin.getConfiguration() instanceof Xpp3Dom)) { + return null; + } + Xpp3Dom child = ((Xpp3Dom) plugin.getConfiguration()).getChild(name); + return child == null ? null : valid(child.getValue()); + } + + private static String manifestMainClass(Plugin jar) { + if (jar == null || !(jar.getConfiguration() instanceof Xpp3Dom)) { + return null; + } + Xpp3Dom node = (Xpp3Dom) jar.getConfiguration(); + for (String name : new String[] {"archive", "manifest", "mainClass"}) { + node = node.getChild(name); + if (node == null) { + return null; + } + } + return valid(node.getValue()); + } + + /** A Java class name, or null for anything else, such as an unresolved ${property}. */ + static String valid(String value) { + if (value == null) { + return null; + } + String trimmed = value.trim(); + return trimmed.matches("[\\p{L}_$][\\p{L}\\p{N}_$]*(\\.[\\p{L}_$][\\p{L}\\p{N}_$]*)*") ? trimmed : null; + } +} diff --git a/extension/src/main/java/io/github/litheidea/maven/DependencyExport.java b/extension/src/main/java/io/github/litheidea/maven/DependencyExport.java index 82bf7ca..0b520a4 100644 --- a/extension/src/main/java/io/github/litheidea/maven/DependencyExport.java +++ b/extension/src/main/java/io/github/litheidea/maven/DependencyExport.java @@ -59,7 +59,7 @@ Map document(String projectPath) throws MavenExecutionException dependencies.add(node); } } else { - dependencies.addAll(children(graph(project(projectPath)))); + dependencies.addAll(children(graph(ModelExport.project(session, projectPath)))); } Map document = new LinkedHashMap<>(); document.put("format", "litheDependencies"); @@ -68,16 +68,6 @@ Map document(String projectPath) throws MavenExecutionException return document; } - private MavenProject project(String projectPath) throws MavenExecutionException { - String wanted = ModelExport.key(new File(session.getExecutionRootDirectory(), projectPath)); - for (MavenProject project : session.getProjects()) { - if (ModelExport.key(project.getBasedir()).equals(wanted)) { - return project; - } - } - throw new MavenExecutionException( - "Lithe found no project at " + projectPath + " in this reactor.", (File) null); - } private DependencyNode graph(MavenProject project) throws MavenExecutionException { DefaultDependencyResolutionRequest request = diff --git a/extension/src/main/java/io/github/litheidea/maven/LitheLifecycleParticipant.java b/extension/src/main/java/io/github/litheidea/maven/LitheLifecycleParticipant.java index b6d5a9c..432be50 100644 --- a/extension/src/main/java/io/github/litheidea/maven/LitheLifecycleParticipant.java +++ b/extension/src/main/java/io/github/litheidea/maven/LitheLifecycleParticipant.java @@ -18,7 +18,9 @@ /** * Writes what Lithe asked for once Maven has read the reactor, before any * goal runs. Lithe's commands pass {@code pre-clean}, a phase nothing is - * bound to by default, so the build that follows does no work. + * bound to by default, so the build that follows does no work. Run + * preparation is the exception: it compiles, and its document is written + * after the build, in {@link #afterSessionEnd}. * *

Without the properties below the extension does nothing, so loading it * into an ordinary build changes nothing. @@ -32,6 +34,10 @@ public final class LitheLifecycleParticipant extends AbstractMavenLifecycleParti static final String DEPENDENCIES_OUTPUT = "lithe.dependenciesOutput"; /** The project whose dependencies are listed; every project without it. */ static final String DEPENDENCIES_PROJECT = "lithe.dependenciesProject"; + /** Where the run document of {@link #RUN_PROJECT} goes once the build is done. */ + static final String RUN_OUTPUT = "lithe.runOutput"; + /** The project run preparation compiled, relative to the directory Maven runs in. */ + static final String RUN_PROJECT = "lithe.runProject"; private final MavenPluginManager pluginManager; private final PluginVersionResolver versionResolver; @@ -61,6 +67,21 @@ public void afterProjectsRead(MavenSession session) throws MavenExecutionExcepti } } + /** + * Writes the run document after the goals have run, so the classes it + * lists exist. A failed build writes nothing: Maven's own output says + * why, and run preparation reports the missing document. + */ + @Override + public void afterSessionEnd(MavenSession session) throws MavenExecutionException { + String runOutput = property(session, RUN_OUTPUT); + String runProject = property(session, RUN_PROJECT); + if (runOutput == null || runProject == null || session.getResult().hasExceptions()) { + return; + } + write(runOutput, Json.write(new RunExport(session, dependenciesResolver).document(runProject))); + } + private static String property(MavenSession session, String key) { String value = session.getUserProperties().getProperty(key); if (value == null) { diff --git a/extension/src/main/java/io/github/litheidea/maven/ModelExport.java b/extension/src/main/java/io/github/litheidea/maven/ModelExport.java index 1a685c9..431d0d3 100644 --- a/extension/src/main/java/io/github/litheidea/maven/ModelExport.java +++ b/extension/src/main/java/io/github/litheidea/maven/ModelExport.java @@ -10,6 +10,7 @@ import java.util.Map; import java.util.Set; import java.util.TreeSet; +import org.apache.maven.MavenExecutionException; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; @@ -27,8 +28,9 @@ /** * Builds the {@code litheBuildModel} document from the reactor Maven has * just read: every project with its coordinates and source folders, the - * goals of every build plugin as model tasks, and the profile IDs the - * Profiles option offers. + * goals of every build plugin as model tasks, the applications Lithe offers + * as run configurations (see {@link Applications}) as model targets, and the + * profile IDs the Profiles option offers. * *

Paths are absolute; Lithe makes them relative to the build root and * drops any outside the workspace. @@ -55,6 +57,7 @@ Map document() { List projects = new ArrayList<>(); List tasks = new ArrayList<>(); List contentRoots = new ArrayList<>(); + List targets = new ArrayList<>(); Map aggregators = aggregators(); for (MavenProject project : session.getProjects()) { String path = path(project.getBasedir()); @@ -84,6 +87,9 @@ Map document() { if (!"pom".equals(project.getPackaging())) { addContentRoots(project, path, contentRoots); } + for (Applications.Application application : Applications.of(project)) { + targets.add(application.target(path)); + } addGoals(project, path, tasks); } Map optionValues = new LinkedHashMap<>(); @@ -92,6 +98,7 @@ Map document() { document.put("format", "litheBuildModel"); document.put("version", 0); document.put("projects", projects); + document.put("targets", targets); document.put("tasks", tasks); document.put("contentRoots", contentRoots); document.put("optionValues", optionValues); @@ -311,6 +318,21 @@ private static File resolve(File basedir, String path) { return file.isAbsolute() ? file : new File(basedir, path); } + /** + * The reactor project at projectPath, relative to the directory Maven + * runs in. + */ + static MavenProject project(MavenSession session, String projectPath) throws MavenExecutionException { + String wanted = key(new File(session.getExecutionRootDirectory(), projectPath)); + for (MavenProject project : session.getProjects()) { + if (key(project.getBasedir()).equals(wanted)) { + return project; + } + } + throw new MavenExecutionException( + "Lithe found no project at " + projectPath + " in this reactor.", (File) null); + } + static String path(File file) { return file.toPath().toAbsolutePath().normalize().toString(); } diff --git a/extension/src/main/java/io/github/litheidea/maven/RunExport.java b/extension/src/main/java/io/github/litheidea/maven/RunExport.java new file mode 100644 index 0000000..885eef5 --- /dev/null +++ b/extension/src/main/java/io/github/litheidea/maven/RunExport.java @@ -0,0 +1,242 @@ +package io.github.litheidea.maven; + +import java.io.DataInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import org.apache.maven.MavenExecutionException; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.project.DefaultDependencyResolutionRequest; +import org.apache.maven.project.DependencyResolutionException; +import org.apache.maven.project.DependencyResolutionResult; +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.ProjectDependenciesResolver; +import org.eclipse.aether.graph.Dependency; +import org.eclipse.aether.graph.DependencyFilter; + +/** + * What Lithe needs to launch one project after Maven has compiled it: the + * runtime classpath, and the classes with a {@code main} method. + * + *

Run preparation runs {@code -pl -am process-classes}, so the + * project and the reactor modules it depends on are compiled in this + * session, and Maven's reactor resolves those modules to their output + * folders without installing them. The classpath is Maven's runtime one: + * the project's classes, then the {@code compile}, {@code runtime} and + * {@code system} dependencies, in the order Maven resolves them. + * + *

Main classes are read from the compiled class files, as + * {@code spring-boot-maven-plugin} finds its start class: every top-level + * class with {@code public static void main(String[])}, marked when its + * constant pool names {@code @SpringBootApplication}. At most + * {@link #MAX_CLASSES} class files are read. + */ +final class RunExport { + static final int MAX_CLASSES = 50_000; + private static final String SPRING_BOOT_APPLICATION = "Lorg/springframework/boot/autoconfigure/SpringBootApplication;"; + private static final int ACC_PUBLIC = 0x0001; + private static final int ACC_STATIC = 0x0008; + + private final MavenSession session; + private final ProjectDependenciesResolver resolver; + + RunExport(MavenSession session, ProjectDependenciesResolver resolver) { + this.session = session; + this.resolver = resolver; + } + + Map document(String projectPath) throws MavenExecutionException { + MavenProject project = ModelExport.project(session, projectPath); + File output = new File(project.getBuild().getOutputDirectory()); + List classpath = new ArrayList<>(); + classpath.add(ModelExport.path(output)); + classpath.addAll(dependencies(project)); + Map document = new LinkedHashMap<>(); + document.put("format", "litheMavenRun"); + document.put("version", 0); + document.put("outputDirectory", ModelExport.path(output)); + document.put("classpath", classpath); + document.put("mainClasses", mainClasses(output)); + return document; + } + + private List dependencies(MavenProject project) throws MavenExecutionException { + DefaultDependencyResolutionRequest request = + new DefaultDependencyResolutionRequest(project, session.getRepositorySession()); + DependencyFilter runtime = (node, parents) -> { + Dependency dependency = node.getDependency(); + if (dependency == null) { + return true; + } + String scope = dependency.getScope(); + return !"test".equals(scope) && !"provided".equals(scope); + }; + request.setResolutionFilter(runtime); + DependencyResolutionResult result; + try { + result = resolver.resolve(request); + } catch (DependencyResolutionException error) { + throw new MavenExecutionException( + "Lithe could not resolve the runtime classpath of " + project.getArtifactId() + ": " + error.getMessage(), + error); + } + Set paths = new LinkedHashSet<>(); + for (Dependency dependency : result.getDependencies()) { + String scope = dependency.getScope(); + if ("test".equals(scope) || "provided".equals(scope)) { + continue; + } + File file = dependency.getArtifact().getFile(); + if (file != null) { + paths.add(ModelExport.path(file)); + } + } + return new ArrayList<>(paths); + } + + /** The main classes under output, sorted by name. */ + static List mainClasses(File output) { + Map found = new TreeMap<>(); + if (!output.isDirectory()) { + return new ArrayList<>(); + } + Deque pending = new ArrayDeque<>(); + pending.push(output); + int budget = MAX_CLASSES; + while (!pending.isEmpty() && budget > 0) { + File[] children = pending.pop().listFiles(); + if (children == null) { + continue; + } + for (File child : children) { + if (child.isDirectory()) { + pending.push(child); + } else if (child.getName().endsWith(".class") && child.getName().indexOf('$') < 0 && budget-- > 0) { + ClassFacts facts = read(child); + if (facts != null && facts.main) { + found.put(facts.name, facts.springBoot); + } + } + } + } + List result = new ArrayList<>(); + for (Map.Entry entry : found.entrySet()) { + Map main = new LinkedHashMap<>(); + main.put("name", entry.getKey()); + main.put("springBoot", entry.getValue()); + result.add(main); + } + return result; + } + + static final class ClassFacts { + final String name; + final boolean main; + final boolean springBoot; + + ClassFacts(String name, boolean main, boolean springBoot) { + this.name = name; + this.main = main; + this.springBoot = springBoot; + } + } + + /** The facts of one class file, or null when it is not one. */ + static ClassFacts read(File file) { + try (InputStream stream = Files.newInputStream(file.toPath()); + DataInputStream in = new DataInputStream(new java.io.BufferedInputStream(stream))) { + if (in.readInt() != 0xCAFEBABE) { + return null; + } + in.readUnsignedShort(); + in.readUnsignedShort(); + int count = in.readUnsignedShort(); + String[] utf8 = new String[count]; + int[] classNames = new int[count]; + boolean springBoot = false; + for (int index = 1; index < count; index++) { + int tag = in.readUnsignedByte(); + switch (tag) { + case 1: + utf8[index] = in.readUTF(); + springBoot |= SPRING_BOOT_APPLICATION.equals(utf8[index]); + break; + case 7: + classNames[index] = in.readUnsignedShort(); + break; + case 8: case 16: case 19: case 20: + in.readUnsignedShort(); + break; + case 15: + in.readUnsignedByte(); + in.readUnsignedShort(); + break; + case 3: case 4: case 9: case 10: case 11: case 12: case 17: case 18: + in.readInt(); + break; + case 5: case 6: + in.readLong(); + index++; + break; + default: + return null; + } + } + in.readUnsignedShort(); + int self = in.readUnsignedShort(); + in.readUnsignedShort(); + skip(in, in.readUnsignedShort() * 2); + int fields = in.readUnsignedShort(); + for (int index = 0; index < fields; index++) { + skip(in, 6); + skipAttributes(in); + } + boolean main = false; + int methods = in.readUnsignedShort(); + for (int index = 0; index < methods; index++) { + int access = in.readUnsignedShort(); + String name = utf8[in.readUnsignedShort()]; + String descriptor = utf8[in.readUnsignedShort()]; + skipAttributes(in); + main |= (access & (ACC_PUBLIC | ACC_STATIC)) == (ACC_PUBLIC | ACC_STATIC) + && "main".equals(name) && "([Ljava/lang/String;)V".equals(descriptor); + } + String internal = self > 0 && self < count ? utf8[classNames[self]] : null; + return internal == null ? null : new ClassFacts(internal.replace('/', '.'), main, springBoot); + } catch (IOException | RuntimeException error) { + return null; + } + } + + private static void skipAttributes(DataInputStream in) throws IOException { + int attributes = in.readUnsignedShort(); + for (int index = 0; index < attributes; index++) { + in.readUnsignedShort(); + skip(in, in.readInt()); + } + } + + private static void skip(DataInputStream in, int bytes) throws IOException { + if (bytes < 0) { + throw new IOException("negative length"); + } + int left = bytes; + while (left > 0) { + int skipped = in.skipBytes(left); + if (skipped <= 0) { + throw new IOException("truncated class file"); + } + left -= skipped; + } + } +} diff --git a/io.github.lithe-idea.maven-build/plugin.json b/io.github.lithe-idea.maven-build/plugin.json index 8de588b..5f04510 100644 --- a/io.github.lithe-idea.maven-build/plugin.json +++ b/io.github.lithe-idea.maven-build/plugin.json @@ -4,9 +4,9 @@ "displayName": "Maven", "version": "1.0.0", "pluginAPIVersion": 0, - "requires": {"buildSystems": 0, "projectGenerators": 0, "settings": 0, "backend": 0, "sourceSettings": 0}, + "requires": {"buildSystems": 0, "buildProviders": 0, "projectGenerators": 0, "settings": 0, "backend": 0, "sourceSettings": 0}, "vendor": {"id": "io.github.lithe-idea", "displayName": "Lithe Community", "signatureRequirement": "none"}, - "permissions": ["process.build", "project.generate", "backend.launch", "workspace.metadata"], + "permissions": ["process.build", "project.generate", "backend.launch", "languageServer.launch", "workspace.metadata"], "activationEvents": ["onBuildSystem:maven"], "settings": [ { @@ -323,7 +323,16 @@ "sync": { "watch": [".mvn/extensions.xml", ".mvn/maven.config", "pom.xml"] }, - "layout": {"excluded": ["target"]} + "layout": {"excluded": ["target"]}, + "provider": { + "launch": {"kind": "runtime", "tool": "java", "minimumVersion": "8", "entry": "lib/lithe-maven-provider.jar", "runtimeArguments": ["-Xms16m", "-Xmx96m"]}, + "executesProjectCode": true, + "mayUseNetwork": true + }, + "run": [ + {"id": "spring-boot", "source": "provider", "fromTargets": {"tags": ["spring-boot"]}, "execution": "service", "debug": {"configurationType": "java"}}, + {"id": "application", "source": "provider", "fromTargets": {"tags": ["java-application"]}, "execution": "application"} + ] } ], "projectGenerators": [ diff --git a/provider/src/main/java/io/github/litheidea/maven/provider/Messages.java b/provider/src/main/java/io/github/litheidea/maven/provider/Messages.java new file mode 100644 index 0000000..4d4ecac --- /dev/null +++ b/provider/src/main/java/io/github/litheidea/maven/provider/Messages.java @@ -0,0 +1,51 @@ +package io.github.litheidea.maven.provider; + +import java.util.List; + +/** + * The provider's user-facing text in the interface language Lithe sends as + * {@code locale} in {@code initialize}: Chinese for {@code zh*}, English + * otherwise. Lithe shows a failed preparation's message as it is. + */ +final class Messages { + private final boolean chinese; + + Messages(String locale) { + chinese = locale != null && locale.toLowerCase(java.util.Locale.ROOT).startsWith("zh"); + } + + String compiling(String target) { + return chinese ? "正在编译 " + target + "…" : "Compiling " + target + "…"; + } + + String buildFailed(int exitCode) { + return chinese + ? "Maven 编译失败(退出码 " + exitCode + "),详见运行窗口中的 Maven 输出。" + : "The Maven build failed (exit code " + exitCode + "). See the Maven output in the Run window."; + } + + String noMaven(String command) { + return chinese + ? "在 PATH 中找不到 Maven(" + command + ")。请安装 Maven,或在 Maven 设置里填写 Maven executable 的完整路径。" + : "Maven (" + command + ") is not on PATH. Install Maven, or enter the full path of the Maven executable in the Maven settings."; + } + + String noRunDocument() { + return chinese + ? "Maven 没有写出运行信息,Lithe 的 Maven 扩展可能没有加载。" + : "Maven wrote no run information; Lithe's Maven extension may not have loaded."; + } + + String noMainClass(String target) { + return chinese + ? target + " 编译后没有带 main 方法的类。请在运行配置的“入口”里填写主类。" + : target + " has no class with a main method after compiling. Enter the main class as the run configuration's entry point."; + } + + String ambiguousMainClass(String target, List candidates) { + String list = String.join(", ", candidates.subList(0, Math.min(candidates.size(), 10))); + return chinese + ? target + " 有多个带 main 方法的类(" + list + ")。请在运行配置的“入口”里选定一个。" + : target + " has several classes with a main method (" + list + "). Enter one as the run configuration's entry point."; + } +} diff --git a/provider/src/main/java/io/github/litheidea/maven/provider/RunPreparation.java b/provider/src/main/java/io/github/litheidea/maven/provider/RunPreparation.java new file mode 100644 index 0000000..578ea21 --- /dev/null +++ b/provider/src/main/java/io/github/litheidea/maven/provider/RunPreparation.java @@ -0,0 +1,415 @@ +package io.github.litheidea.maven.provider; + +import io.github.litheidea.plugin.sdk.CallContext; +import io.github.litheidea.plugin.sdk.Json; +import io.github.litheidea.plugin.sdk.PluginError; +import io.github.litheidea.plugin.sdk.Processes; +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.jar.Attributes; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; + +/** + * Answers {@code lithe/build/prepareRun} for a Maven application target. + * + *

The user's Maven compiles the selected project and the reactor modules + * it depends on ({@code -pl -am process-classes}) with the + * packaged core extension loaded, which then writes the runtime classpath + * and the compiled main classes ({@code RunExport}). The answer is a plain + * {@code java -cp

} launch on the project's JDK; + * Lithe starts and owns that process. Nothing runs through + * {@code spring-boot:run}, so the process Lithe stops is the application + * itself and a debugger can attach to it. + * + *

A classpath longer than {@link #MAX_CLASSPATH_CHARS} goes into a + * manifest-only jar under the project's build directory, as IntelliJ IDEA's + * "JAR manifest" shortening does: one launch argument is limited to 64 KiB, + * and a Windows command line to 32 767 characters. The jar is build output + * Maven's {@code clean} removes, named by a hash of its classpath so equal + * launches reuse it. + */ +final class RunPreparation { + static final int MAX_CLASSPATH_CHARS = 24_000; + static final String SPRING_BOOT = "spring-boot"; + static final String JAVA_TOOL = "java"; + private static final int OUTPUT_CHUNK = 32 * 1024; + + private final Path workspace; + private final Path extensionJar; + private final Messages messages; + + RunPreparation(Path workspace, Path extensionJar, Messages messages) { + this.workspace = workspace; + this.extensionJar = extensionJar; + this.messages = messages; + } + + Map prepare(Map params, CallContext context) throws Exception { + Request request = Request.of(params); + Path instance = workspace.resolve(request.root).normalize(); + String project = relative(request.root, request.projectPath); + Map environment = environment(request.environment); + List command = new ArrayList<>(); + command.add(executable(maven(request.tool, instance), environment, File.separatorChar == '\\')); + command.add("-B"); + command.add("-ntp"); + command.addAll(request.optionArguments); + command.add("-Dmaven.ext.class.path=" + extensionJar); + Path output = Files.createTempFile("lithe-maven-run-", ".json"); + try { + command.add("-Dlithe.runOutput=" + output); + command.add("-Dlithe.runProject=./" + project); + if (!".".equals(project)) { + command.add("-pl"); + command.add("./" + project); + command.add("-am"); + } + command.add("process-classes"); + context.progress(messages.compiling(request.targetName), null, null); + Processes.Result result = context.run(command, new Processes.Options() + .directory(instance) + .environment(environment) + .cancellation(context.cancellation()) + .maxOutputBytes(64 * 1024) + .onStdout(text -> stream(context, text)) + .onStderr(text -> stream(context, text))); + if (result.exitCode() != 0) { + throw new PluginError("maven.run.buildFailed", messages.buildFailed(result.exitCode())); + } + String text = new String(Files.readAllBytes(output), StandardCharsets.UTF_8); + if (text.isEmpty()) { + throw new PluginError("maven.run.noRunDocument", messages.noRunDocument()); + } + Map document = Json.object(Json.parse(text)); + return launch(request, document); + } finally { + Files.deleteIfExists(output); + } + } + + /** The launch plan for the run document Maven wrote. */ + Map launch(Request request, Map document) throws IOException { + String main = mainClass(request, document); + List classpath = strings(document.get("classpath")); + List arguments = new ArrayList<>(request.runtimeArguments); + if (request.debugPort > 0) { + arguments.add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=" + request.debugHost + ":" + request.debugPort); + } + arguments.add("-cp"); + arguments.add(classpathArgument(classpath, Paths.get(String.valueOf(document.get("outputDirectory"))))); + arguments.add(main); + arguments.addAll(request.arguments); + arguments.addAll(request.userArguments); + Map executable = new LinkedHashMap<>(); + executable.put("kind", "toolchain"); + executable.put("value", JAVA_TOOL); + Map plan = new LinkedHashMap<>(); + plan.put("executable", executable); + plan.put("arguments", arguments); + plan.put("workingDirectory", request.workingDirectory != null ? request.workingDirectory : request.projectPath); + plan.put("environment", request.launchEnvironment); + return plan; + } + + /** + * The chosen entry point, the target's main class, or the one main class + * Maven compiled; Spring Boot targets prefer the annotated classes. + */ + String mainClass(Request request, Map document) { + if (request.entrypoint != null) { + return request.entrypoint; + } + if (request.mainClass != null) { + return request.mainClass; + } + List all = new ArrayList<>(); + List annotated = new ArrayList<>(); + Object listed = document.get("mainClasses"); + if (listed instanceof List) { + for (Object item : (List) listed) { + Map main = Json.object(item); + String name = String.valueOf(main.get("name")); + all.add(name); + if (Boolean.TRUE.equals(main.get("springBoot"))) { + annotated.add(name); + } + } + } + List candidates = request.tags.contains(SPRING_BOOT) && !annotated.isEmpty() ? annotated : all; + if (candidates.size() == 1) { + return candidates.get(0); + } + if (candidates.isEmpty()) { + throw new PluginError("maven.run.noMainClass", messages.noMainClass(request.targetName)); + } + Collections.sort(candidates); + throw new PluginError("maven.run.ambiguousMainClass", messages.ambiguousMainClass(request.targetName, candidates)); + } + + /** The classpath as one argument, or a manifest jar on it when that argument would be too long. */ + static String classpathArgument(List classpath, Path outputDirectory) throws IOException { + String joined = String.join(File.pathSeparator, classpath); + if (joined.length() <= MAX_CLASSPATH_CHARS) { + return joined; + } + StringBuilder entries = new StringBuilder(); + for (String entry : classpath) { + File file = new File(entry); + String uri = file.toURI().toString(); + if (file.isDirectory() && !uri.endsWith("/")) { + uri += "/"; + } + if (entries.length() > 0) { + entries.append(' '); + } + entries.append(uri); + } + Path directory = outputDirectory.getParent().resolve("lithe-run"); + Files.createDirectories(directory); + Path jar = directory.resolve("classpath-" + hash(entries.toString()) + ".jar"); + if (!Files.isRegularFile(jar)) { + Manifest manifest = new Manifest(); + manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); + manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, entries.toString()); + Path partial = Files.createTempFile(directory, "classpath-", ".tmp"); + try (OutputStream out = Files.newOutputStream(partial); JarOutputStream ignored = new JarOutputStream(out, manifest)) { + // A manifest is the whole jar. + } + try { + Files.move(partial, jar, java.nio.file.StandardCopyOption.ATOMIC_MOVE); + } catch (IOException raced) { + Files.deleteIfExists(partial); + if (!Files.isRegularFile(jar)) { + throw raced; + } + } + } + return jar.toString(); + } + + private static String hash(String text) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)); + StringBuilder hex = new StringBuilder(); + for (int index = 0; index < 8; index++) { + hex.append(String.format(Locale.ROOT, "%02x", digest[index])); + } + return hex.toString(); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + /** + * The Maven to run: the one Lithe resolved from the build system's + * invocation, otherwise the same order the manifest declares, without + * the user's override, which only Lithe can read. + */ + static String maven(String tool, Path instance) { + if (tool != null) { + return tool; + } + boolean windows = File.separatorChar == '\\'; + Path wrapper = instance.resolve(windows ? "mvnw.cmd" : "mvnw"); + if (Files.isRegularFile(wrapper) && Files.isRegularFile(instance.resolve(".mvn/wrapper/maven-wrapper.properties"))) { + return wrapper.toString(); + } + String home = System.getenv("MAVEN_HOME"); + if (home != null && !home.isEmpty()) { + Path candidate = Paths.get(home, "bin", windows ? "mvn.cmd" : "mvn"); + if (Files.isRegularFile(candidate)) { + return candidate.toString(); + } + } + return windows ? "mvn.cmd" : "mvn"; + } + + /** + * The path to start for {@code command}. A command without a directory is + * looked up on the {@code PATH} of {@code environment}, as a shell would: + * Java starts a bare name through the operating system, and on Windows + * that finds only {@code .exe} files, so {@code mvn}, which is + * {@code mvn.cmd} there, would fail to start. On Windows a name without + * an extension also tries each {@code PATHEXT} extension. A command that + * names a directory is returned as it is. + * + * @throws PluginError {@code maven.run.noMaven} when no {@code PATH} + * entry holds the command + */ + String executable(String command, Map environment, boolean windows) { + if (command.indexOf('/') >= 0 || (windows && (command.indexOf('\\') >= 0 || command.indexOf(':') >= 0))) { + return command; + } + List names = new ArrayList<>(); + String extensions = variable(environment, "PATHEXT", windows); + if (windows && command.indexOf('.') < 0) { + for (String extension : (extensions == null || extensions.isEmpty() ? ".COM;.EXE;.BAT;.CMD" : extensions).split(";")) { + if (!extension.isEmpty()) { + names.add(command + extension.toLowerCase(Locale.ROOT)); + } + } + } else { + names.add(command); + } + String path = variable(environment, "PATH", windows); + if (path != null) { + for (String directory : path.split(File.pathSeparator)) { + if (directory.isEmpty()) { + continue; + } + for (String name : names) { + Path candidate; + try { + candidate = Paths.get(directory.replace("\"", ""), name); + } catch (java.nio.file.InvalidPathException ignored) { + break; + } + if (Files.isRegularFile(candidate) && (windows || Files.isExecutable(candidate))) { + return candidate.toString(); + } + } + } + } + throw new PluginError("maven.run.noMaven", messages.noMaven(command)); + } + + /** The variable {@code name}, whose case Windows ignores. */ + private static String variable(Map environment, String name, boolean windows) { + if (!windows) { + return environment.get(name); + } + for (Map.Entry entry : environment.entrySet()) { + if (entry.getKey().equalsIgnoreCase(name)) { + return entry.getValue(); + } + } + return null; + } + + private static Map environment(Map overrides) { + Map environment = new LinkedHashMap<>(System.getenv()); + environment.putAll(overrides); + return environment; + } + + private static void stream(CallContext context, String text) { + for (int start = 0; start < text.length(); start += OUTPUT_CHUNK) { + context.progress(null, null, text.substring(start, Math.min(text.length(), start + OUTPUT_CHUNK))); + } + } + + /** path relative to root, both workspace-relative with forward slashes. */ + static String relative(String root, String path) { + if (".".equals(root) || root.isEmpty()) { + return path.isEmpty() ? "." : path; + } + if (path.equals(root)) { + return "."; + } + if (path.startsWith(root + "/")) { + return path.substring(root.length() + 1); + } + throw new PluginError("maven.run.invalidProject", "The project is outside the build root."); + } + + static List strings(Object value) { + List result = new ArrayList<>(); + if (value instanceof List) { + for (Object item : (List) value) { + result.add(String.valueOf(item)); + } + } + return result; + } + + private static Map stringMap(Object value) { + Map result = new LinkedHashMap<>(); + if (value instanceof Map) { + for (Map.Entry entry : ((Map) value).entrySet()) { + result.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())); + } + } + return result; + } + + private static String text(Object value) { + if (value == null) { + return null; + } + String text = value.toString().trim(); + return text.isEmpty() ? null : text; + } + + /** The fields of one prepareRun request this provider uses. */ + static final class Request { + String root = "."; + String projectPath = "."; + String targetName = ""; + List tags = new ArrayList<>(); + String mainClass; + String tool; + List optionArguments = new ArrayList<>(); + Map environment = new LinkedHashMap<>(); + List runtimeArguments = new ArrayList<>(); + List arguments = new ArrayList<>(); + List userArguments = new ArrayList<>(); + Map launchEnvironment = new LinkedHashMap<>(); + String entrypoint; + String workingDirectory; + String debugHost; + int debugPort; + + static Request of(Map params) { + Request request = new Request(); + String root = text(params.get("root")); + request.root = root == null ? "." : root; + Map project = params.get("project") instanceof Map ? Json.object(params.get("project")) : Collections.emptyMap(); + String projectPath = text(project.get("path")); + request.projectPath = projectPath == null ? request.root : projectPath; + Map target = params.get("target") instanceof Map ? Json.object(params.get("target")) : Collections.emptyMap(); + String name = text(target.get("name")); + request.targetName = name == null ? "" : name; + request.tags = strings(target.get("tags")); + Map properties = target.get("properties") instanceof Map ? Json.object(target.get("properties")) : Collections.emptyMap(); + request.mainClass = text(properties.get("mainClass")); + Map tool = params.get("tool") instanceof Map ? Json.object(params.get("tool")) : Collections.emptyMap(); + request.tool = text(tool.get("executable")); + request.optionArguments = strings(params.get("optionArguments")); + request.environment = stringMap(params.get("environment")); + request.userArguments = strings(params.get("userArguments")); + if (params.get("launchOptions") instanceof Map) { + Map options = Json.object(params.get("launchOptions")); + request.runtimeArguments = strings(options.get("runtimeArguments")); + request.arguments = strings(options.get("arguments")); + request.launchEnvironment = stringMap(options.get("environment")); + request.entrypoint = text(options.get("entrypoint")); + request.workingDirectory = text(options.get("workingDirectory")); + if (options.get("debug") instanceof Map) { + Map debug = Json.object(options.get("debug")); + Map endpoint = debug.get("target") instanceof Map ? Json.object(debug.get("target")) : Collections.emptyMap(); + request.debugHost = text(endpoint.get("host")); + Object port = endpoint.get("port"); + request.debugPort = port instanceof Number ? ((Number) port).intValue() : 0; + if (request.debugHost == null || request.debugPort < 1 || request.debugPort > 65535) { + throw new PluginError("maven.run.invalidDebug", "The debug target is not a local connection."); + } + } + } + return request; + } + } +} diff --git a/provider/src/main/java/io/github/litheidea/maven/provider/RunProvider.java b/provider/src/main/java/io/github/litheidea/maven/provider/RunProvider.java new file mode 100644 index 0000000..60dfa7b --- /dev/null +++ b/provider/src/main/java/io/github/litheidea/maven/provider/RunProvider.java @@ -0,0 +1,36 @@ +package io.github.litheidea.maven.provider; + +import io.github.litheidea.plugin.sdk.Backend; +import io.github.litheidea.plugin.sdk.PluginError; +import java.net.URI; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Map; + +/** + * The Maven build provider process: Lithe starts it on the first run of a + * Maven application and talks to it over stdio. It answers only + * {@code lithe/build/prepareRun}; the model, dependencies, tasks and tests + * stay commands Lithe runs itself. + */ +public final class RunProvider { + private RunProvider() {} + + public static void main(String[] args) throws Exception { + Path lib = Paths.get(RunProvider.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent(); + Path extension = lib.resolve("lithe-maven-extension.jar"); + Backend backend = Backend.create("lithe-maven-provider", RunProvider.class.getPackage().getImplementationVersion()); + backend.onPrepareRun((params, context) -> preparation(backend, extension).prepare(params, context)); + backend.listen(); + } + + private static RunPreparation preparation(Backend backend, Path extension) { + Map initialize = backend.initializeParams(); + Object root = initialize == null ? null : initialize.get("rootUri"); + if (!(root instanceof String)) { + throw new PluginError("maven.run.noWorkspace", "Lithe sent no workspace folder."); + } + Object locale = initialize.get("locale"); + return new RunPreparation(Paths.get(URI.create((String) root)), extension, new Messages(locale instanceof String ? (String) locale : null)); + } +} diff --git a/scripts/package.mjs b/scripts/package.mjs index 191792d..49c2ed2 100644 --- a/scripts/package.mjs +++ b/scripts/package.mjs @@ -2,11 +2,13 @@ // Packages the plugin into dist/--darwin.zip, the asset name // Lithe Store's release tracker recognizes (docs/publishing.md there). // -// The package is plain data plus one jar, built here with Maven and copied to -// lib/: the Maven core extension in extension/. Lithe never starts it; the -// model and dependency commands in plugin.json load it into the user's own -// Maven with -Dmaven.ext.class.path, and it writes the canonical documents -// Lithe decodes. It carries no native code, so one archive serves every Mac and both Linux and +// The package is plain data plus three jars in lib/: the Maven core extension +// in extension/, built here with Maven, and two Java processes built with +// javac: the settings backend (settings-backend/) and the build provider that +// prepares runs (provider/). Lithe never starts the extension itself; the +// model and dependency commands in plugin.json, and the provider's run +// preparation, load it into the user's own Maven with -Dmaven.ext.class.path, +// and it writes the documents they read. It carries no native code, so one archive serves every Mac and both Linux and // Windows architectures, copied as -linux.zip and -windows.zip. Packaging needs // POSIX zip, so it runs on macOS or Linux; scripts/test.mjs also runs on Windows. // The unpacked package stays in dist/package/ for installing a local @@ -85,12 +87,18 @@ const report = createReport("package"); const timeoutMs = mavenTimeout(); await withInterrupts(async (signal) => { await verifySdk(); - const build = "settings-backend/target"; function sources(path) {return readdirSync(path,{withFileTypes:true}).flatMap(e=>e.isDirectory()?sources(join(path,e.name)):e.name.endsWith(".java")?[join(path,e.name)]:[]);} - rmSync(build,{recursive:true,force:true});mkdirSync(join(build,"classes"),{recursive:true}); - await runCommand("javac",["--release","8","-encoding","UTF-8","-d",join(build,"classes"),...sources("settings-backend/src/main/java"),...sources("vendor/lithe-plugin-sdk-java/src/main/java")],{timeoutMs,signal}); - writeFileSync(join(build,"MANIFEST.MF"),`Main-Class: io.github.litheidea.maven.settings.MavenSettings\nImplementation-Version: ${manifest.version}\n`); - await runCommand("jar",["--create","--file",join(build,"lithe-maven-settings.jar"),"--manifest",join(build,"MANIFEST.MF"),"--date","2026-11-15T00:00:00Z","-C",join(build,"classes"),"."],{timeoutMs,signal}); + // Both Java processes Lithe starts are built the same way, with the vendored SDK, for Java 8: + // the settings backend and the build provider that prepares runs. + async function backendJar(directory, mainClass, jarName) { + const build = `${directory}/target`; + rmSync(build,{recursive:true,force:true});mkdirSync(join(build,"classes"),{recursive:true}); + await runCommand("javac",["--release","8","-encoding","UTF-8","-d",join(build,"classes"),...sources(`${directory}/src/main/java`),...sources("vendor/lithe-plugin-sdk-java/src/main/java")],{timeoutMs,signal}); + writeFileSync(join(build,"MANIFEST.MF"),`Main-Class: ${mainClass}\nImplementation-Version: ${manifest.version}\n`); + await runCommand("jar",["--create","--file",join(build,jarName),"--manifest",join(build,"MANIFEST.MF"),"--date","2026-11-15T00:00:00Z","-C",join(build,"classes"),"."],{timeoutMs,signal}); + } + await backendJar("settings-backend", "io.github.litheidea.maven.settings.MavenSettings", "lithe-maven-settings.jar"); + await backendJar("provider", "io.github.litheidea.maven.provider.RunProvider", "lithe-maven-provider.jar"); try { await report.step("build the Maven extension", async () => { await runCommand(process.env.MVN ?? "mvn", ["-B", "-ntp", "-q", "-f", "extension/pom.xml", "clean", "package"], { timeoutMs, signal }); @@ -105,6 +113,7 @@ await withInterrupts(async (signal) => { mkdirSync(join(packageRoot, "lib"), { recursive: true }); cpSync(EXTENSION_JAR, join(packageRoot, "lib", "lithe-maven-extension.jar")); cpSync("settings-backend/target/lithe-maven-settings.jar",join(packageRoot,"lib","lithe-maven-settings.jar")); + cpSync("provider/target/lithe-maven-provider.jar",join(packageRoot,"lib","lithe-maven-provider.jar")); cpSync("vendor/LICENSE",join(packageRoot,"SDK-LICENSE")); cpSync("LICENSE", join(packageRoot, "LICENSE")); cpSync("NOTICE", join(packageRoot, "NOTICE")); diff --git a/scripts/test.mjs b/scripts/test.mjs index 012472e..754c013 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -21,9 +21,11 @@ import assert from "node:assert/strict"; import { mavenTimeout, runCommand, withInterrupts } from "./process.mjs"; import { createReport } from "./report.mjs"; +import { BackendClient } from "./compiler/backend-client.mjs"; +import { execFileSync } from "node:child_process"; import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join, resolve } from "node:path"; +import { delimiter, join, resolve } from "node:path"; const PACKAGE_DIR = "io.github.lithe-idea.maven-build"; const pluginDir = resolve(process.env.LITHE_TEST_PLUGIN_DIR || join("dist", "package", PACKAGE_DIR)); @@ -115,6 +117,80 @@ async function document(name, declaration, signal, values = {}) { return JSON.parse(readFileSync(outputFile, "utf8")); } +/** + * Starts the packaged build provider the way Lithe does and asks it to prepare runs, then + * launches the plans it returns with the java on PATH, as Lithe launches them with the + * project's JDK. + */ +async function prepareRuns(signal) { + const client = new BackendClient({ jar: join(pluginDir, "lib", "lithe-maven-provider.jar"), args: [], timeoutMs: timeoutMs }); + try { + await report.step("start the build provider", () => client.initialize(root)); + let operation = 0; + const request = (target, extra = {}) => client.request("lithe/build/prepareRun", { + operationID: `run-${++operation}`, buildSystemID: "maven", root: ".", options: {}, optionArguments: [], environment: {}, + tool: { executable: maven }, run: target.tags.includes("spring-boot") ? "spring-boot" : "application", + project: { name: target.path, path: target.path }, target, userArguments: ["typed"], ...extra, + }); + const prepare = (target, extra) => report.step(`prepare ${target.name}`, () => request(target, extra)); + const launch = (plan) => { + assert.deepEqual(plan.executable, { kind: "toolchain", value: "java" }); + return execFileSync("java", plan.arguments, { + cwd: join(root, plan.workingDirectory), env: { ...process.env, ...plan.environment }, encoding: "utf8", timeout: timeoutMs, + }); + }; + + const service = await prepare({ name: "ServiceApplication", path: "service", tags: ["spring-boot"], properties: { mainClass: "demo.service.ServiceApplication" } }, { + launchOptions: { execution: "service", runtimeArguments: ["-Dgreeting=hi there"], arguments: ["--port=0"], environment: { LITHE_FIXTURE: "set" } }, + }); + await check("a service run compiles its reactor dependencies and launches its main class", () => { + assert.equal(service.workingDirectory, "service"); + assert.deepEqual(service.environment, { LITHE_FIXTURE: "set" }); + const classpath = service.arguments[service.arguments.indexOf("-cp") + 1].split(delimiter); + assert.equal(classpath[0], join(root, "service", "target", "classes")); + assert.ok(classpath.includes(join(root, "core", "target", "classes")), "the uninstalled sibling comes from the reactor"); + assert.ok(!classpath.some((entry) => entry.includes("junit")), "test dependencies stay off the runtime classpath"); + assert.equal(launch(service).trim(), "Hello, service greeting=hi there arguments=--port=0,typed env=set"); + }); + + // Without a main class in the model, the compiled classes decide, as spring-boot-maven-plugin does. + const discovered = await prepare({ name: "Main", path: "app", tags: ["java-application"], properties: {} }); + await check("a target without a main class runs the one the build compiled", () => { + assert.equal(discovered.arguments[discovered.arguments.indexOf("-cp") + 2], "demo.app.Main"); + assert.equal(launch(discovered).trim(), "Hello, Maven"); + }); + + const debug = await prepare({ name: "ServiceApplication", path: "service", tags: ["spring-boot"], properties: { mainClass: "demo.service.ServiceApplication" } }, { + launchOptions: { execution: "service", runtimeArguments: [], arguments: [], environment: {}, + debug: { adapterID: "dev.example/java", configurationType: "java", target: { kind: "connection", host: "127.0.0.1", port: 51235 } } }, + }); + await check("a debug run suspends the service until the debugger attaches on the host's port", () => { + assert.ok(debug.arguments.includes("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:51235")); + assert.ok(debug.arguments.indexOf("-cp") > debug.arguments.findIndex((argument) => argument.startsWith("-agentlib:jdwp"))); + }); + + await check("a failed build ends preparation with the provider's error", async () => { + writeFileSync(join(root, "service", "src", "main", "java", "demo", "service", "Broken.java"), "package demo.service; class Broken {"); + try { + await assert.rejects(request({ name: "ServiceApplication", path: "service", tags: ["spring-boot"], properties: {} }, { + launchOptions: { execution: "service", runtimeArguments: [], arguments: [], environment: {} }, + }), (error) => error.response?.data?.pluginErrorCode === "maven.run.buildFailed" || /Maven build failed/.test(error.message)); + } finally { + rmSync(join(root, "service", "src", "main", "java", "demo", "service", "Broken.java")); + } + }); + await check("a Maven command that is not on PATH ends preparation with a clear error", async () => { + await assert.rejects(request({ name: "Main", path: "app", tags: ["java-application"], properties: {} }, { + tool: { executable: "lithe-no-such-maven" }, + }), (error) => error.response?.data?.pluginErrorCode === "maven.run.noMaven" || /not on PATH/.test(error.message)); + }); + await report.step("stop the build provider", () => client.close()); + } catch (error) { + client.kill(); + throw error; + } +} + async function test(signal) { try { cpSync(resolve("test", "fixtures", "reactor"), root, { recursive: true }); @@ -127,7 +203,7 @@ async function test(signal) { await check("the model lists the reactor and its aggregator tree", () => { assert.equal(model.format, "litheBuildModel"); assert.equal(model.version, 0); - assert.deepEqual(model.projects.map((project) => project.name), ["reactor", "core", "app"]); + assert.deepEqual(model.projects.map((project) => project.name), ["reactor", "core", "app", "service"]); assert.equal(byName("reactor").displayName, "Demo Reactor"); assert.equal(byName("core").parent, byName("reactor").path); assert.deepEqual(Object.fromEntries(["groupId","artifactId","version","packaging"].map(key=>[key,byName("app").properties[key]])), { @@ -164,6 +240,19 @@ async function test(signal) { assert.ok(!model.contentRoots.some((entry) => entry.project === byName("reactor").path)); }); + await check("applications become the targets the run declarations select", () => { + const targets = model.targets.map((target) => [target.project, target.name, target.tags, target.properties]); + assert.deepEqual(targets, [ + [byName("app").path, "Main", ["java-application"], { mainClass: "demo.app.Main" }], + [byName("service").path, "ServiceApplication", ["spring-boot"], { mainClass: "demo.service.ServiceApplication" }], + ]); + const runs = Object.fromEntries(buildSystem.run.map((run) => [run.id, run])); + assert.deepEqual(runs["spring-boot"].fromTargets.tags, ["spring-boot"]); + assert.equal(runs["spring-boot"].execution, "service"); + assert.deepEqual(runs.application.fromTargets.tags, ["java-application"]); + assert.ok(buildSystem.run.every((run) => run.source === "provider")); + }); + const projectDependencies = await document("read project dependencies", buildSystem.dependencies, signal, { project: "app" }); capture("app-dependencies.json", projectDependencies); await check("a project's tree resolves an uninstalled sibling from the reactor", () => { @@ -177,18 +266,20 @@ async function test(signal) { capture("dependencies.json", workspaceDependencies); await check("the workspace tree has one node per project with transitive children", () => { const tree = workspaceDependencies; - assert.deepEqual(tree.dependencies.map((node) => node.name), ["reactor", "core", "app"]); + assert.deepEqual(tree.dependencies.map((node) => node.name), ["reactor", "core", "app", "service"]); const junit = tree.dependencies[1].children[0]; assert.deepEqual([junit.name, junit.version, junit.scope], ["junit", "4.13.2", "test"]); assert.equal(junit.children[0].name, "hamcrest-core"); }); await check("reading the model and dependencies builds nothing", () => { - for (const directory of ["target", "core/target", "app/target"]) { + for (const directory of ["target", "core/target", "app/target", "service/target"]) { assert.ok(!existsSync(join(root, directory)), `${directory} was not created`); } }); + await prepareRuns(signal); + await run("run the filtered Maven test suite", root, buildSystem.test.arguments, signal, { project: "core", suite: "demo.core.GreeterTest" }); await check("a filtered test run writes the report the results glob reads", () => { const report = readFileSync(join(root, "core", "target", "surefire-reports", "TEST-demo.core.GreeterTest.xml"), "utf8"); diff --git a/test/fixtures/reactor/app/pom.xml b/test/fixtures/reactor/app/pom.xml index 361cbc2..f2b24d6 100644 --- a/test/fixtures/reactor/app/pom.xml +++ b/test/fixtures/reactor/app/pom.xml @@ -16,4 +16,21 @@ ${project.version} + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + demo.app.Main + + + + + + diff --git a/test/fixtures/reactor/pom.xml b/test/fixtures/reactor/pom.xml index a1e31b6..d859562 100644 --- a/test/fixtures/reactor/pom.xml +++ b/test/fixtures/reactor/pom.xml @@ -10,6 +10,7 @@ core app + service @@ -30,6 +31,11 @@ maven-compiler-plugin 3.13.0 + + org.apache.maven.plugins + maven-jar-plugin + 3.4.2 + diff --git a/test/fixtures/reactor/service/pom.xml b/test/fixtures/reactor/service/pom.xml new file mode 100644 index 0000000..1b6e79e --- /dev/null +++ b/test/fixtures/reactor/service/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + + demo + reactor + 1.0.0-SNAPSHOT + + service + + + + + demo + core + ${project.version} + + + diff --git a/test/fixtures/reactor/service/src/main/java/demo/service/ServiceApplication.java b/test/fixtures/reactor/service/src/main/java/demo/service/ServiceApplication.java new file mode 100644 index 0000000..7a78a17 --- /dev/null +++ b/test/fixtures/reactor/service/src/main/java/demo/service/ServiceApplication.java @@ -0,0 +1,13 @@ +package demo.service; + +import demo.core.Greeter; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +// A comment naming @SpringBootApplication does not count; the annotation below does. +@SpringBootApplication +public class ServiceApplication { + public static void main(String[] arguments) { + System.out.println(new Greeter().greet("service") + " greeting=" + System.getProperty("greeting") + + " arguments=" + String.join(",", arguments) + " env=" + System.getenv("LITHE_FIXTURE")); + } +} diff --git a/test/fixtures/reactor/service/src/main/java/org/springframework/boot/autoconfigure/SpringBootApplication.java b/test/fixtures/reactor/service/src/main/java/org/springframework/boot/autoconfigure/SpringBootApplication.java new file mode 100644 index 0000000..97143e8 --- /dev/null +++ b/test/fixtures/reactor/service/src/main/java/org/springframework/boot/autoconfigure/SpringBootApplication.java @@ -0,0 +1,11 @@ +package org.springframework.boot.autoconfigure; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** Stands in for Spring Boot's annotation, so the fixture builds without downloading Spring. */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface SpringBootApplication {}