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