From 45ec2920138345a7291b0dd53581ad40c875b570 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 19:59:16 +0800 Subject: [PATCH] =?UTF-8?q?test:=20=E5=AE=BF=E4=B8=BB=E7=AB=AF=E5=88=B0?= =?UTF-8?q?=E7=AB=AF=E6=B5=8B=E8=AF=95=E5=92=8C=E5=8A=9F=E8=83=BD=E7=9F=A9?= =?UTF-8?q?=E9=98=B5=E7=A7=BB=E5=88=B0=E6=8F=92=E4=BB=B6=E4=BB=93=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 主仓库按 1lck/Lithe-IDEA#1915 不再保存插件的测试和功能矩阵条目,这里接收 Maven 插件的部分: - e2e/host/ 放 TestOfficialMavenPluginBuildsAReactor(含辅助函数)和新建项目测试 maven_integration_test.go,scripts/e2e-host.mjs 把 lithe-host.json 固定的宿主版本 检出到 .artifacts/lithe-host 后运行 - docs/feature-matrix.md 迁移 6 个条目并按 0.0.1 重写,新增 maven-project-generators - README 说明运行方式和功能矩阵位置 --- README.md | 36 ++ docs/feature-matrix.md | 167 +++++++++ .../projectgen/maven_integration_test.go | 112 ++++++ .../official_maven_plugin_e2e_test.go | 319 ++++++++++++++++++ e2e/host/lithe-host.json | 15 + scripts/e2e-host.mjs | 87 +++++ 6 files changed, 736 insertions(+) create mode 100644 docs/feature-matrix.md create mode 100644 e2e/host/desktop/internal/projectgen/maven_integration_test.go create mode 100644 e2e/host/desktop/internal/workbench/official_maven_plugin_e2e_test.go create mode 100644 e2e/host/lithe-host.json create mode 100644 scripts/e2e-host.mjs diff --git a/README.md b/README.md index b2c4bc3..55a528c 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,9 @@ scripts/package.mjs # 构建扩展并打包成 dist/m scripts/test.mjs # 用真实 Maven 运行清单里的模型、依赖和测试命令并检查输出 scripts/test-process.mjs # 进程超时、中断和清理回归,不需要 Maven scripts/verify-scripts.mjs # 在临时副本里打包和测试,检查已有包和宿主 bundle 不被改动 +scripts/e2e-host.mjs # 在固定版本的宿主里运行 e2e/host/ 的测试 +e2e/host/ # 宿主端到端测试和宿主版本固定文件 lithe-host.json +docs/feature-matrix.md # 插件自己的功能矩阵 .github/workflows/ci.yml # PR 时打包、用 Maven 3.6.3 和最新版测试,并用 Lithe Store 的规则检查 .github/workflows/release.yml # 推送 v<版本> 标签时发布 GitHub Release docs/releases/v<版本>.md # 该版本的变化,发布时并入 Release 说明(可选) @@ -154,6 +157,39 @@ node scripts/verify-scripts.mjs --host-bundle /Applications/Lithe.app [插件契约](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md) 和[构建工具接入指南](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/guides/build-tool-integration.md)。 +## 宿主端到端测试 + +`e2e/host/` 里的测试用 Lithe 桌面端自己的测试工具装上插件包,在真实的宿主和 Rust Core 里检查插件: + +- `TestOfficialMavenPluginBuildsAReactor`(宿主的 `desktop/internal/workbench` 包):读取两模块反应堆的模型和依赖树, + 改 Maven executable 设置后重新读取并运行 `compile`,最后确认插件安装目录没有被写入。 +- `TestMavenPluginProjectGeneratesABuildableMavenProject`、`TestMavenPluginArchetypeRunsRealMaven`(`desktop/internal/projectgen` 包): + 用清单里的两个新建项目条目生成项目。 + +这些测试原来放在 Lithe 主仓库,按“宿主不依赖插件”的要求([1lck/Lithe-IDEA#1915](https://github.com/1lck/Lithe-IDEA/pull/1915)) +移到这里:主仓库不读取本仓库,`e2e/host/lithe-host.json` 记录测试最后一次通过时的宿主版本。 + +需要 Node.js 22+、Go、Rust 工具链(构建宿主固定的 Rust Core)、`git` 和 `PATH` 上的 `mvn`: + +```bash +node scripts/package.mjs +LITHE_TEST_MAVEN_PLUGIN_ARCHIVE="$PWD/dist/maven-build-<版本>-darwin.zip" node scripts/e2e-host.mjs +``` + +- `LITHE_TEST_MAVEN_PLUGIN_ARCHIVE` 必须设置,脚本不会因为缺少插件包而跳过测试。 +- 新建项目测试读取 `LITHE_PLUGIN_MAVEN_DIR` 里的 `plugin.json` 和模板,默认是本仓库的 `io.github.lithe-idea.maven-build/`。 +- 原型测试要从 Maven Central 下载原型插件,只在设置了 `LITHE_INTEGRATION_NETWORK=1` 和 `JAVA_HOME` 时运行,否则跳过。 + +脚本把固定版本的宿主(只取 `desktop/` 和 `scripts/`)检出到 `.artifacts/lithe-host`,复制 `e2e/host/desktop/` 下的测试, +再在那里运行宿主的 `scripts/desktop/desktop-go.sh test`;第一次运行会克隆并构建 Rust Core,`LITHE_CORE_RUST_DIR` +可以指向本地的 Core 检出。`--ref <分支或 commit>` 换一个宿主版本试跑,`--run <正则>` 只跑部分测试。 +测试用的是宿主内部的测试工具,升级 `lithe-host.json` 的 `revision` 时可能要同步修改测试。 + +## 功能矩阵 + +插件能力在各平台的实现和验证状态记录在 [docs/feature-matrix.md](docs/feature-matrix.md),Lithe 主仓库的功能矩阵不再收录插件能力。 +改动插件行为的 PR 同时更新这一页。 + ## 发布新版本 1. 按语义化版本同时修改 `plugin.json` 和 `extension/pom.xml` 的版本(打包脚本会检查两者一致):只修 Bug 升修订号, diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md new file mode 100644 index 0000000..0034e11 --- /dev/null +++ b/docs/feature-matrix.md @@ -0,0 +1,167 @@ +# 功能矩阵 + +本页记录 Maven 插件自己的跨平台功能状态。Lithe 主仓库的功能矩阵(`shared/platform-feature-matrix/`) +只记录宿主能力,不再收录插件能力([1lck/Lithe-IDEA#1915](https://github.com/1lck/Lithe-IDEA/pull/1915))。 +插件能力的状态、证据和验证方法在这里维护,改动插件行为的 PR 同时更新本页。 + +## 状态取值 + +沿用主仓库功能矩阵的取值: + +| 字段 | 取值 | +| --- | --- | +| 实现 | `implemented` 已实现;`partial` 部分实现;`missing` 未实现;`not-applicable` 该平台不适用 | +| 验证 | `verified` 已按“验证方法”完整验收;`pending` 尚未完整验收;`not-applicable` 无需验收 | + +只有按“验证方法”完整走过一遍,并写明日期、插件版本和宿主版本,才能标 `verified`。 +自动化测试的结果写在“最近验证”里,不能代替验收。 + +Windows 一列目前都是 `missing`:插件只发布 `maven-build-<版本>-darwin.zip`(`scripts/package.mjs`),没有 Windows 包。 + +## 总览 + +| ID | 能力 | macOS | Windows | 最近验证 | +| --- | --- | --- | --- | --- | +| `java-maven-project` | 识别 Maven 项目:构建根、模块树、内容根和任务 | implemented / pending | missing / not-applicable | 2026-11-14 宿主端到端测试通过 | +| `java-maven-profiles-dependencies` | Profiles 构建选项与依赖树 | implemented / pending | missing / not-applicable | 2026-11-14 依赖树由宿主端到端测试覆盖 | +| `java-maven-project-settings` | Maven 调用设置:Maven 程序和工作区构建选项 | partial / pending | missing / not-applicable | 2026-11-14 Maven executable 由宿主端到端测试覆盖 | +| `java-maven-settings-reach-jdt` | Maven 构建选项作用于 Java 语言服务 | missing / not-applicable | missing / not-applicable | — | +| `java-maven-toolbar-tooltips` | 构建窗口里的 Maven 图标、工具栏开关和提示 | implemented / pending | missing / not-applicable | 没有自动化覆盖 | +| `maven-user-settings-editing` | 编辑用户级 `~/.m2/settings.xml` 的本地仓库 | missing / not-applicable | missing / not-applicable | — | +| `maven-project-generators` | 新建项目:Maven 和 Maven Archetype | implemented / pending | missing / not-applicable | 2026-11-14 宿主端到端测试通过 | + +前六条从主仓库迁移,最后一条是本仓库新增,用来记录随测试一起迁来的新建项目测试。 + +## java-maven-project + +**能力**:工作区最外层的 `pom.xml` 是构建根,`` 组成模块树;随包的 Maven 扩展在 Maven 读完反应堆后导出模块、 +内容根、生命周期和每个模块实际使用的插件目标;`pom.xml`、`.mvn/maven.config`、`.mvn/extensions.xml` 变化后重新读取。 + +**证据**:`io.github.lithe-idea.maven-build/plugin.json` 的 `buildSystems[0]`(`detection`、`model`、`tasks`、`sync`)、 +`extension/`、`scripts/test.mjs`、`e2e/host/desktop/internal/workbench/official_maven_plugin_e2e_test.go`。 + +**依赖的宿主能力**:`buildSystems`(构建窗口识别实例、运行模型命令并解码 `litheBuildModel`、运行任务)。 + +**最近验证**:2026-11-14,macOS arm64,插件 0.0.1 发布包,宿主 `059d878d4`,`node scripts/e2e-host.mjs`:`TestOfficialMavenPluginBuildsAReactor` PASS(8.76s)。测试装上插件包,对两模块反应堆检查模型(两个模块挂在聚合项目下、模型里有插件目标)、运行 `compile` 并检查生成的 class 文件,最后确认插件安装目录的摘要不变。没有覆盖嵌套聚合、内容根、`-pl` 单模块任务、文件变化后的自动重读和插件目标分组,需要手工验收。 + +**验证方法**(macOS): + +1. 安装 `dist/maven-build-<版本>-darwin.zip`,打开单模块、多模块(含嵌套聚合)和非标准源码目录的项目。 +2. 构建窗口的模块树、父子关系和内容根与 `pom.xml` 一致;插件目标按 `Plugins › <前缀>` 分组。 +3. 对整个反应堆和单个模块(`-pl`)运行 `compile`、`test`、`package`,输出和编译问题显示正确。 +4. 修改 `pom.xml` 或 `.mvn/maven.config` 后项目重新读取;读取模型和依赖时不生成 `target/`。 +5. 整个过程中插件安装目录不被写入。 + +**迁移来源**:主仓库 `shared/platform-feature-matrix/features/java-maven-project.json`(1lck/Lithe-IDEA@b582e206a)。 +原条目记录的是旧 Swift 宿主上 Maven Provider、JDT 构建路径和运行配置生成的迁移过程;Maven 插件已按契约 v0 改为声明式 +`buildSystems` 并从 0.0.1 重新发布,没有后端,原条目里的 Provider、JDT 链路和运行配置内容不再适用。 +JDT 侧的项目导入归 Java Support 插件维护。 + +## java-maven-profiles-dependencies + +**能力**:构建选项 Profiles 传 `-P `,候选值从反应堆、父 POM 和 `settings.xml` 读取,也可以手动补充; +依赖树显示整个反应堆或单个模块的依赖(含作用域和传递依赖),反应堆内未安装的兄弟模块也能解析。 + +**证据**:`plugin.json` 的 `buildSystems[0].options`(`profiles`)和 `buildSystems[0].dependencies`、`extension/`、 +`scripts/test.mjs`、宿主端到端测试里 `app` 模块依赖 `core` 的检查。 + +**依赖的宿主能力**:`buildSystems` 的构建选项、依赖命令和 `litheDependencies` 解码。 + +**最近验证**:2026-11-14,macOS arm64,插件 0.0.1 发布包,宿主 `059d878d4`,`node scripts/e2e-host.mjs`:`TestOfficialMavenPluginBuildsAReactor` 检查了 `app` 对反应堆兄弟模块 `core` 的依赖。Profiles 切换、作用域、传递依赖和大依赖树没有自动化覆盖。 + +**验证方法**(macOS): + +1. 在声明了多个 Profile 的项目里切换 Profile,模型和依赖树按所选 Profile 重新读取。 +2. 依赖树的模块归属、顺序、作用域和传递依赖与 `mvn dependency:tree` 一致;依赖节点超过 6,000 个的项目能完整加载。 +3. 依赖解析失败时显示 Maven 的真实错误。 + +**迁移来源**:主仓库 `shared/platform-feature-matrix/features/java-maven-profiles-dependencies.json`(b582e206a)。 +原条目中“Java 导航使用 JDT 解析的依赖快照”属于 Java Support 插件,旧 MavenService 删除记录属于旧 Swift 宿主,都不再写在这里。 + +## java-maven-project-settings + +**能力**:插件设置 Maven executable(全局,修改后重新读取模型);构建选项 JDK (JAVA_HOME)、Profiles、Settings File、 +Local Repository、Offline、Skip Tests,按工作区保存,加到构建、测试和读取模型的命令里。 + +| 平台 | 实现 | 验证 | 说明 | +| --- | --- | --- | --- | +| macOS | partial | pending | 构建选项按工作区保存,不能给单个子项目设置不同的 JDK 或选项 | +| Windows | missing | not-applicable | 没有 Windows 包 | + +**证据**:`plugin.json` 的 `settings`(`mavenExecutable`)、`buildSystems[0].invocation` 和 `buildSystems[0].options`; +宿主端到端测试设置 Maven executable 后检查模型重新读取和 `compile` 都运行了设置的 `mvn`。 + +**依赖的宿主能力**:`settings`(插件设置页和 `reload` 生效方式)、`buildSystems` 的构建选项和可执行文件候选顺序。 + +**最近验证**:2026-11-14,macOS arm64,插件 0.0.1 发布包,宿主 `059d878d4`,`node scripts/e2e-host.mjs`:`TestOfficialMavenPluginBuildsAReactor` 设置 Maven executable 为一个包装脚本后,确认模型重新读取和 `compile` 都运行了它。六个构建选项、按工作区保存和 `mvnw` / `MAVEN_HOME` 的候选顺序没有自动化覆盖。 + +**验证方法**(macOS): + +1. Maven executable 留空时依次使用 `mvnw`、`MAVEN_HOME`、`PATH`;填写后总是用它,路径不存在时报错不回退。 +2. 逐个修改六个构建选项,确认命令行里出现对应参数,Offline 和 Skip Tests 在工具栏上切换。 +3. 关闭并重新打开工作区后构建选项保持;另一个工作区不受影响。 + +**迁移来源**:主仓库 `shared/platform-feature-matrix/features/java-maven-project-settings.json`(b582e206a)。 +原条目的 canonical Run `local.json`、旧 XML 表单、配置迁移和 315 项原生回归都属于旧 Swift 宿主和旧 Maven 后端,0.0.1 没有这些实现。 + +## java-maven-settings-reach-jdt + +**能力**:Maven 的 Settings File、Local Repository、Profiles 等选项和重新加载实时作用于 Java 语言服务(JDT LS)。 + +| 平台 | 实现 | 验证 | 说明 | +| --- | --- | --- | --- | +| macOS | missing | not-applicable | 0.0.1 没有后端,不导出 `languageImport.settings` | +| Windows | missing | not-applicable | 没有 Windows 包 | + +**说明**:Java Support 1.2.0 通过插件函数 `languageImport.settings` 向构建插件收集 JDT LS 设置,构建插件改设置后调用 +`languageImport.settingsChanged`。插件函数需要后端进程来应答,而 0.0.1 是纯声明式插件,所以 Maven 的构建选项目前不会传给 +JDT LS,JDT LS 按自己的默认方式导入 Maven 项目。 + +**迁移来源**:主仓库 `shared/platform-feature-matrix/features/java-maven-settings-reach-jdt.json`(b582e206a)。 +原条目描述的 Core `build.languageImport`、MavenService 回调和 Run/Debug 准备属于旧 Swift 宿主。 + +## java-maven-toolbar-tooltips + +**能力**:构建窗口里的 Maven 图标(IntelliJ Platform 原色 SVG,含暗色版本)、Offline 和 Skip Tests 工具栏开关、任务和选项的提示。 + +**证据**:`io.github.lithe-idea.maven-build/icons/`、`plugin.json` 的 `buildSystems[0].icon` 和 `options`、`NOTICE`。 + +**依赖的宿主能力**:构建窗口按清单显示图标、开关和提示。 + +**最近验证**:没有自动化测试覆盖,也没有做手工验收。 + +**验证方法**(macOS):在明暗主题下打开构建窗口,逐一悬停运行、刷新、开关和选项按钮,提示与动作一致; +图标原色显示,切换主题后使用对应版本;窄窗口下提示不被截断。 + +**迁移来源**:主仓库 `shared/platform-feature-matrix/features/java-maven-toolbar-tooltips.json`(b582e206a)。 +原条目里的 Swift 视图和回归测试名属于旧 Swift 宿主。 + +## maven-user-settings-editing + +**能力**:没有打开项目时,在 Maven 设置页编辑用户级 `~/.m2/settings.xml` 的 ``,回显真实值, +确认后只改写这个元素,文件在读取后被外部修改时拒绝覆盖并保留草稿。 + +| 平台 | 实现 | 验证 | 说明 | +| --- | --- | --- | --- | +| macOS | missing | not-applicable | 0.0.1 没有这个设置;Local Repository 构建选项只传 `-Dmaven.repo.local`,不改 `settings.xml` | +| Windows | missing | not-applicable | 没有 Windows 包 | + +**说明**:旧版 Maven 后端实现过这个功能,契约 v0 重写时没有保留。按 Lithe 的“设置必须反映工具的真实配置”规则, +重新实现时要读取并回显 `settings.xml` 的实际值,确认后才写回,并做外部修改冲突保护。 + +**迁移来源**:主仓库 `shared/platform-feature-matrix/features/maven-user-settings-editing.json`(b582e206a)。 + +## maven-project-generators + +**能力**:新建项目窗口的两个条目。Maven 生成 Maven Java 项目(Java release 8、11、17、21、25,可选示例代码、GroupId、 +ArtifactId);Maven Archetype 用内置或自定义原型,由 `mvn archetype:generate` 生成项目。 + +**证据**:`plugin.json` 的 `projectGenerators`、`io.github.lithe-idea.maven-build/templates/java/`、 +`e2e/host/desktop/internal/projectgen/maven_integration_test.go`。 + +**依赖的宿主能力**:`projectGenerators`(Core 计算表单和生成计划,宿主在临时目录执行后整体移动到位)。 + +**最近验证**:2026-11-14,macOS arm64,插件 0.0.1 发布包,宿主 `059d878d4`,`node scripts/e2e-host.mjs`:`TestMavenPluginProjectGeneratesABuildableMavenProject` PASS(0.60s);设置 `LITHE_INTEGRATION_NETWORK=1` 和 `JAVA_HOME` 后 `TestMavenPluginArchetypeRunsRealMaven` PASS(13.07s,从 Maven Central 下载原型插件并运行真实的 `mvn archetype:generate`)。新建项目窗口的界面没有自动化覆盖。 + +**验证方法**(macOS):在新建项目窗口分别用两个条目生成项目,检查表单默认值、生成的文件和打开的文件; +生成的 Maven 项目能直接 `mvn package`;取消或失败时目标目录不留下半成品。 diff --git a/e2e/host/desktop/internal/projectgen/maven_integration_test.go b/e2e/host/desktop/internal/projectgen/maven_integration_test.go new file mode 100644 index 0000000..24d8f4e --- /dev/null +++ b/e2e/host/desktop/internal/projectgen/maven_integration_test.go @@ -0,0 +1,112 @@ +package projectgen + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// The real Maven plugin's generators, run through Core's plan and this executor. +// It is an integration test: it needs a checkout of the Maven plugin +// (LITHE_PLUGIN_MAVEN_DIR names the directory that holds its plugin.json) and, +// for the build check, an installed mvn. Without the checkout it is skipped. +func mavenPluginDirectory(t *testing.T) (string, []byte) { + t.Helper() + directory := os.Getenv("LITHE_PLUGIN_MAVEN_DIR") + if directory == "" { + t.Skip("LITHE_PLUGIN_MAVEN_DIR is not set") + } + manifest, err := os.ReadFile(filepath.Join(directory, "plugin.json")) + if err != nil { + t.Fatal(err) + } + return directory, manifest +} + +func TestMavenPluginProjectGeneratesABuildableMavenProject(t *testing.T) { + directory, manifest := mavenPluginDirectory(t) + ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute) + defer cancel() + kernel := core.NewClient() + // Core only needs a JDK's home and version for the templates; the files step runs no JDK. + home := t.TempDir() + input := core.ProjectGeneratorFormInput{ + ProjectName: "maven-demo", + Values: map[string]any{"jdk": home}, + Tools: map[string][]core.ProjectToolInstallation{"jdk": {{Home: home, Version: "17.0.2"}}}, + } + form, err := kernel.ProjectGeneratorFormOf(ctx, manifest, "maven-java", input) + if err != nil || !form.Valid { + t.Fatalf("form = %+v, %v", form, err) + } + plan, err := kernel.ProjectGenerationPlanOf(ctx, manifest, "maven-java", directory, input) + if err != nil { + t.Fatal(err) + } + parent := t.TempDir() + result := Run(ctx, Request{Parent: parent, Name: "maven-demo", Plan: plan, Kernel: kernel}) + if result.Failure != nil { + t.Fatal(result.Failure) + } + pom, err := os.ReadFile(filepath.Join(result.Path, "pom.xml")) + if err != nil || !strings.Contains(string(pom), "maven-demo") || !strings.Contains(string(pom), "17") { + t.Fatalf("pom.xml = %q, %v", pom, err) + } + if _, err := os.Stat(filepath.Join(result.Path, "src", "main", "java", "org", "example", "Main.java")); err != nil { + t.Fatalf("the sample class was not generated: %v", err) + } + if !slices.Contains(result.OpenFiles, "src/main/java/org/example/Main.java") { + t.Fatalf("open files = %v", result.OpenFiles) + } + mvn, lookErr := exec.LookPath("mvn") + if lookErr != nil { + return + } + // `validate` binds no plugin, so it checks the POM without the network. + command := exec.CommandContext(ctx, mvn, "-B", "-q", "-o", "validate") + command.Dir = result.Path + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("mvn validate failed: %v\n%s", err, output) + } +} + +func TestMavenPluginArchetypeRunsRealMaven(t *testing.T) { + directory, manifest := mavenPluginDirectory(t) + if os.Getenv("LITHE_INTEGRATION_NETWORK") == "" { + t.Skip("LITHE_INTEGRATION_NETWORK is not set: the archetype plugin is downloaded from Maven Central") + } + if _, err := exec.LookPath("mvn"); err != nil { + t.Skip("mvn is not installed") + } + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Minute) + defer cancel() + kernel := core.NewClient() + home := os.Getenv("JAVA_HOME") + if home == "" { + t.Skip("JAVA_HOME is not set") + } + input := core.ProjectGeneratorFormInput{ + ProjectName: "archetype-demo", + Values: map[string]any{"jdk": home}, + Tools: map[string][]core.ProjectToolInstallation{"jdk": {{Home: home, Version: "17.0.2"}}}, + } + plan, err := kernel.ProjectGenerationPlanOf(ctx, manifest, "maven-archetype", directory, input) + if err != nil { + t.Fatal(err) + } + parent := t.TempDir() + result := Run(ctx, Request{Parent: parent, Name: "archetype-demo", Plan: plan, Kernel: kernel}) + if result.Failure != nil { + t.Fatalf("%v\n%s", result.Failure, result.Failure.Tail) + } + if _, err := os.Stat(filepath.Join(result.Path, "pom.xml")); err != nil { + t.Fatalf("the collected archetype project has no pom.xml: %v", err) + } +} 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 new file mode 100644 index 0000000..6b30272 --- /dev/null +++ b/e2e/host/desktop/internal/workbench/official_maven_plugin_e2e_test.go @@ -0,0 +1,319 @@ +package workbench + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "io" + "io/fs" + "os" + "os/exec" + "path/filepath" + "sort" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/plugininstall" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" + "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" +) + +// This opt-in integration test installs the released Maven Build archive through the real +// installer, enables it and drives the workbench as a user does: detection, the reactor model +// the packaged core extension prints, a module's dependency tree, the Maven executable setting +// and a real compile. It runs the user's own mvn, so it skips unless an archive is named, and +// fails rather than skips once a named archive cannot do its work. + +// installOfficialPluginArchive installs and enables archive in an isolated +// plugin root and returns the installed package directory. +func installOfficialPluginArchive(t *testing.T, h *harness, archive, id string) string { + t.Helper() + service, err := pluginservice.Open(core.NewClient(), h.store, t.TempDir()) + if err != nil { + t.Fatal(err) + } + h.app.plugins = service + 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}) + if err != nil { + t.Fatalf("prepare %s: %v", archive, err) + } + if plan.ID != id { + _ = service.Installer.Discard(plan) + t.Fatalf("archive holds %s, want %s", plan.ID, id) + } + installed, err := service.Installer.Commit(plan) + if err != nil { + _ = service.Installer.Discard(plan) + t.Fatalf("install %s: %v", id, err) + } + if err := service.Manager.SetEnabled(id, true); err != nil { + t.Fatal(err) + } + return installed.Path +} + +// packageDigest hashes every file of an installed package, so a test can prove a +// workflow left the package byte-for-byte as installed. +func packageDigest(t *testing.T, root string) map[string]string { + t.Helper() + digest := map[string]string{} + err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error { + if err != nil || entry.IsDir() { + return err + } + file, err := os.Open(path) + if err != nil { + return err + } + // JDK module images are large; stream the unchanged-package proof so + // test buffers do not inflate the headless host's memory observations. + sum := sha256.New() + _, readErr := io.Copy(sum, file) + closeErr := file.Close() + if readErr != nil { + return readErr + } + if closeErr != nil { + return closeErr + } + relative, err := filepath.Rel(root, path) + if err != nil { + return err + } + digest[relative] = hex.EncodeToString(sum.Sum(nil)) + return nil + }) + if err != nil { + t.Fatal(err) + } + return digest +} + +func assertPackageUnchanged(t *testing.T, root string, before map[string]string) { + t.Helper() + after := packageDigest(t, root) + if len(after) != len(before) { + t.Fatalf("the installed package now has %d files, it had %d", len(after), len(before)) + } + for name, sum := range before { + if after[name] != sum { + t.Fatalf("the workflow changed the installed package file %s", name) + } + } +} + +// writePluginFixture writes files (relative path to content) below root. +func writePluginFixture(t *testing.T, root string, files map[string]string) { + t.Helper() + for name, content := range files { + path := filepath.Join(root, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } +} + +// awaitBuildModel waits until detection found an instance of buildSystemID and its +// model is loaded, failing with the model error when the plugin's command failed. +func awaitBuildModel(t *testing.T, h *harness, p *project, buildSystemID string, limit time.Duration) *buildInstance { + t.Helper() + var instance *buildInstance + awaitStateWithin(t, h, limit, buildSystemID+" detection and model", func() bool { + for index := range p.build.instances { + candidate := &p.build.instances[index] + if candidate.BuildSystemID != buildSystemID { + continue + } + if candidate.modelError != "" { + t.Fatalf("the %s model failed: %s", buildSystemID, candidate.modelError) + } + if candidate.modelLoaded { + p.build.selected = index + instance = candidate + return true + } + } + if p.build.failed != "" { + t.Fatalf("build detection failed: %s", p.build.failed) + } + return false + }) + return instance +} + +// runBuildTaskToEnd runs one task of the selected instance and waits for it to end. +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 { + 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, "") + if p.build.status != h.app.text.Build.Succeeded { + t.Fatalf("%s did not succeed: status=%q output=%q", taskID, p.build.status, output) + } + return output +} + +func modelProjectNamed(model core.BuildModel, name string) *core.BuildProject { + for index := range model.Projects { + if model.Projects[index].Name == name { + return &model.Projects[index] + } + } + return nil +} + +// markingWrapper writes an executable script that records each start in a marker file and +// then runs the named tool found on PATH, so a test can tell that a configured path ran. +func markingWrapper(t *testing.T, name string) (wrapper, marker string) { + t.Helper() + target, err := exec.LookPath(name) + if err != nil { + t.Fatalf("%s is not on PATH: %v", name, err) + } + dir := t.TempDir() + marker = filepath.Join(dir, name+".started") + wrapper = filepath.Join(dir, name) + script := "#!/bin/sh\n: > '" + marker + "'\nexec '" + target + "' \"$@\"\n" + if err := os.WriteFile(wrapper, []byte(script), 0o700); err != nil { + t.Fatal(err) + } + return wrapper, marker +} + +// saveGlobalPluginSettings saves values to the plugin's global settings layer the way the +// settings window does, then dispatches the effects Core answered for the change. +func saveGlobalPluginSettings(t *testing.T, h *harness, instance *buildInstance, values map[string]any) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + store := pluginsettings.New(h.app.kernel, h.store.Dir()) + snapshot, err := store.Load(ctx, instance.Manifest, h.app.project.root) + if err != nil { + t.Fatalf("load the plugin settings: %v", err) + } + ids := make([]string, 0, len(values)) + for id := range values { + ids = append(ids, id) + } + sort.Strings(ids) + edits := make([]core.PluginSettingEdit, 0, len(ids)) + for _, id := range ids { + value, err := json.Marshal(values[id]) + if err != nil { + t.Fatal(err) + } + edits = append(edits, core.PluginSettingEdit{ID: id, Value: value}) + } + result, err := store.Save(ctx, snapshot, "global", edits, nil) + if err != nil || !result.Committed { + t.Fatalf("save the plugin settings: committed=%v err=%v", result.Committed, err) + } + h.app.applyPluginSettingsEffects(core.PluginSettingsOwner{PluginID: instance.PluginID, Version: instance.Version}, result.Effects) +} + +// TestOfficialMavenPluginBuildsAReactor covers the Maven archive: the user's mvn +// loads the packaged core extension from the read-only package, which prints the +// reactor model (projects with their aggregator, plugin goals as model tasks) +// and a module's dependency tree, and a lifecycle task compiles the reactor. It +// uses the user's local repository, so the first run may download Maven plugins. +func TestOfficialMavenPluginBuildsAReactor(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") + } + 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") + before := packageDigest(t, installed) + root := t.TempDir() + module := func(name, dependencies string) string { + return "\n 4.0.0\n" + + " demoreactor1.0.0-SNAPSHOT\n" + + " " + name + "\n" + dependencies + "\n" + } + writePluginFixture(t, root, map[string]string{ + "pom.xml": "\n 4.0.0\n" + + " demoreactor1.0.0-SNAPSHOTpom\n" + + " 11UTF-8\n" + + " coreapp\n\n", + "core/pom.xml": module("core", ""), + "core/src/main/java/demo/core/Greeter.java": "package demo.core;\n\npublic final class Greeter {\n public static String greet(String name) { return \"Hello, \" + name; }\n}\n", + "app/pom.xml": module("app", " democore${project.version}\n"), + "app/src/main/java/demo/app/Main.java": "package demo.app;\n\npublic final class Main {\n public static void main(String[] args) { System.out.println(demo.core.Greeter.greet(\"Lithe\")); }\n}\n", + }) + h.open(root) + p := h.app.project + if p == nil { + t.Fatal("the reactor did not open") + } + h.app.loadBuildSystems(p) + instance := awaitBuildModel(t, h, p, "maven", 3*time.Minute) + reactor, library, application := modelProjectNamed(instance.Model, "reactor"), modelProjectNamed(instance.Model, "core"), modelProjectNamed(instance.Model, "app") + if reactor == nil || library == nil || application == nil { + t.Fatalf("the reactor model is missing a project: %+v", instance.Model.Projects) + } + if library.ParentID != reactor.ID || application.ParentID != reactor.ID || library.Path != "core" { + t.Fatalf("the modules are not below their aggregator: %+v", instance.Model.Projects) + } + goals := 0 + for _, task := range instance.Model.Tasks { + if task.Template == "plugin-goal" { + goals++ + } + } + if goals == 0 { + t.Fatalf("the model lists no plugin goals: %+v", instance.Model.Tasks) + } + + p.build.projectID = application.ID + deps := h.app.dependenciesOf(p, instance, application.ID) + awaitStateWithin(t, h, 3*time.Minute, "the app dependency tree", func() bool { return !deps.loading }) + if deps.failed != "" { + t.Fatalf("the app dependencies failed: %s", deps.failed) + } + if len(deps.tree.Dependencies) != 1 || deps.tree.Dependencies[0].Name != "core" || deps.tree.Dependencies[0].Scope != "compile" { + t.Fatalf("the app dependency tree = %+v", deps.tree.Dependencies) + } + + // The Maven executable setting is the first candidate: a path set there reloads the + // model and runs every later command instead of mvn on PATH. + mvnWrapper, mvnMarker := markingWrapper(t, "mvn") + saveGlobalPluginSettings(t, h, instance, map[string]any{"mavenExecutable": mvnWrapper}) + instance = awaitBuildModel(t, h, p, "maven", 3*time.Minute) + if _, err := os.Stat(mvnMarker); err != nil { + t.Fatalf("the model reload did not run the configured mvn: %v", err) + } + if err := os.Remove(mvnMarker); err != nil { + t.Fatal(err) + } + output := runBuildTaskToEnd(t, h, p, "", "compile", 5*time.Minute) + if !strings.Contains(output, "BUILD SUCCESS") { + t.Fatalf("mvn compile printed no success: %q", output) + } + if _, err := os.Stat(mvnMarker); err != nil { + t.Fatalf("compile did not run the configured mvn: %v", err) + } + for _, class := range []string{"core/target/classes/demo/core/Greeter.class", "app/target/classes/demo/app/Main.class"} { + if _, err := os.Stat(filepath.Join(root, filepath.FromSlash(class))); err != nil { + t.Fatalf("mvn compile did not produce %s: %v", class, err) + } + } + 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 new file mode 100644 index 0000000..ab474c8 --- /dev/null +++ b/e2e/host/lithe-host.json @@ -0,0 +1,15 @@ +{ + "repository": "https://github.com/1lck/Lithe-IDEA.git", + "revision": "059d878d4284e1a1fd218aeaa56c29d9753d4dfa", + "packages": { + "./internal/workbench": "^TestOfficialMavenPluginBuildsAReactor$", + "./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" + }, + "repositoryEnvironment": { + "LITHE_PLUGIN_MAVEN_DIR": "io.github.lithe-idea.maven-build" + } +} diff --git a/scripts/e2e-host.mjs b/scripts/e2e-host.mjs new file mode 100644 index 0000000..aaf0a99 --- /dev/null +++ b/scripts/e2e-host.mjs @@ -0,0 +1,87 @@ +// Runs this plugin's host end-to-end tests against a pinned Lithe desktop host. +// +// node scripts/e2e-host.mjs [--source ] [--ref ] [--run ] +// +// The tests in e2e/host/ drive the real plugin package through the desktop host's own test +// harness (an internal Go package), so they cannot be built in this repository. Each run checks +// out the host revision pinned in e2e/host/lithe-host.json into the disposable .artifacts/lithe-host +// (desktop/ and scripts/ only), copies every e2e/host/desktop/ file to the same path in that +// checkout and runs the host's scripts/desktop/desktop-go.sh test there, which builds the Core +// revision that host pins. The host repository never reads this repository: the tests live here +// and the pin says which host they last passed on. Bumping the pin can require adapting the tests +// to changes in the host's internal harness. +// +// Every variable listed in lithe-host.json "requiredEnvironment" must be set, because the tests +// skip without their plugin input and a skipped run proves nothing. "repositoryEnvironment" maps a +// variable to a path in this repository, used when the variable is not set. --source and --ref override +// the pin, for example to try an unmerged host branch; --run overrides the test selection. +import { spawn } from 'node:child_process'; +import { copyFile, mkdir, readFile, readdir } from 'node:fs/promises'; +import { dirname, join, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseArgs } from 'node:util'; + +const root = fileURLToPath(new URL('..', import.meta.url)); +const tests = join(root, 'e2e', 'host'); +const work = join(root, '.artifacts', 'lithe-host'); + +function run(command, args, options = {}) { + return new Promise((resolvePromise, reject) => { + const child = spawn(command, args, { stdio: 'inherit', ...options }); + child.on('error', reject); + child.on('close', (code, signal) => { + if (code === 0) resolvePromise(); + else reject(new Error(`${command} ${args.join(' ')} failed (${signal ?? `exit ${code}`})`)); + }); + }); +} + +/** Lists the files under e2e/host/desktop, relative to e2e/host. */ +async function hostTestFiles(directory = join(tests, 'desktop')) { + const files = []; + for (const entry of await readdir(directory, { withFileTypes: true })) { + const path = join(directory, entry.name); + if (entry.isDirectory()) files.push(...await hostTestFiles(path)); + else if (entry.isFile()) files.push(relative(tests, path)); + } + return files; +} + +/** Checks out `ref` from `source` into the disposable work directory, desktop/ and scripts/ only. */ +async function checkoutHost(source, ref) { + await mkdir(work, { recursive: true }); + await run('git', ['init', '-q', work]); + await run('git', ['-C', work, 'sparse-checkout', 'set', '--cone', 'desktop', 'scripts']); + // A named remote, because the partial clone fetches missing blobs from it later. + await run('git', ['-C', work, 'config', 'remote.origin.url', source]); + await run('git', ['-C', work, 'fetch', '-q', '--depth', '1', '--filter=blob:none', 'origin', ref]); + await run('git', ['-C', work, 'checkout', '-q', '--force', '--detach', 'FETCH_HEAD']); + // Drops test files copied by an earlier run; ignored build state such as .artifacts/ stays. + await run('git', ['-C', work, 'clean', '-q', '-f', '-d', '--', 'desktop']); +} + +const { values } = parseArgs({ + options: { source: { type: 'string' }, ref: { type: 'string' }, run: { type: 'string' } }, +}); +const pin = JSON.parse(await readFile(join(tests, 'lithe-host.json'), 'utf8')); +for (const [name, path] of Object.entries(pin.repositoryEnvironment ?? {})) { + process.env[name] ||= join(root, path); +} +const missing = Object.entries(pin.requiredEnvironment ?? {}).filter(([name]) => !process.env[name]); +if (missing.length > 0) { + throw new Error(`Set the plugin inputs first:\n${missing.map(([name, what]) => ` ${name}: ${what}`).join('\n')}`); +} + +// git runs inside the checkout, so a local source must be absolute. +const given = values.source ?? pin.repository; +const source = !/^[a-z]+:\/\//.test(given) ? resolve(given) : given; +await checkoutHost(source, values.ref ?? pin.revision); +for (const file of await hostTestFiles()) { + const target = join(work, file); + await mkdir(dirname(target), { recursive: true }); + await copyFile(join(tests, file), target); +} +for (const [pkg, selection] of Object.entries(pin.packages)) { + await run('bash', ['scripts/desktop/desktop-go.sh', 'test', pkg, '-count=1', '-v', + '-timeout', pin.timeout ?? '30m', '-run', values.run ?? selection], { cwd: work }); +}