diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 19a56dd..08e3b11 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -136,6 +136,28 @@ jobs: if-no-files-found: error retention-days: 14 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + - uses: actions/download-artifact@v4 + with: + name: maven-build-windows + path: .artifacts/profile-host-package + - name: Test Maven Profile switching in the desktop host + run: | + compatible="$(node -p ' + const {requires} = require("./io.github.lithe-idea.maven-build/plugin.json"); + require("./e2e/host/lithe-host.json").suites.profiles.hostBuildProviders.includes(requires.buildProviders) + ')" + if [[ "$compatible" == "false" ]]; then + echo "::notice::The pinned Profile-tree host cannot install this buildProviders version. The Maven integration matrix still tests Profile activation." + exit 0 + fi + version="$(node -p 'require("./io.github.lithe-idea.maven-build/plugin.json").version')" + export LITHE_TEST_MAVEN_PLUGIN_ARCHIVE="$PWD/.artifacts/profile-host-package/maven-build-$version-windows.zip" + node scripts/e2e-host.mjs --suite profiles + # The Windows archive built above, unpacked the way Lithe installs it (under # a path with a space), runs the declared commands through mvn.cmd. windows: diff --git a/README.md b/README.md index 3ea8b50..d8b04fd 100644 --- a/README.md +++ b/README.md @@ -203,6 +203,8 @@ node scripts/verify-scripts.mjs --host-bundle /Applications/Lithe.app 打开一个真实的两模块 Spring Boot 3.5 项目(`spring-boot-starter-web`),确认运行配置下拉只列出 `ShopApplication`(服务), 用运行配置编辑器保存 JVM 参数、程序参数和环境变量,运行后检查控制台里的 Maven 构建日志和 Spring Boot 启动日志, 请求 `/hello` 确认三项设置都传到了进程;停止后确认服务不再响应、端口已释放,插件安装目录没有被写入。 +- `TestOfficialMavenPluginSwitchesActiveProfilesInBuildTree`(`desktop/internal/workbench` 包):在构建树切换 Profile, + 编译后检查模块产物,重开项目确认保存的选择仍然有效。 - `TestMavenPluginProjectGeneratesABuildableMavenProject`、`TestMavenPluginArchetypeRunsRealMaven`(`desktop/internal/projectgen` 包): 用清单里的两个新建项目条目生成项目。 @@ -219,14 +221,17 @@ LITHE_TEST_JAVA_PLUGIN_ARCHIVE="$PWD/.artifacts/java-plugin/Lithe-Java-Support-< node scripts/e2e-host.mjs ``` -- `LITHE_TEST_MAVEN_PLUGIN_ARCHIVE` 和 `LITHE_TEST_JAVA_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` 时运行,否则跳过。 -脚本把固定版本的宿主(只取 `desktop/` 和 `scripts/`)检出到 `.artifacts/lithe-host`,复制 `e2e/host/desktop/` 下的测试, -再在那里运行宿主的 `scripts/desktop/desktop-go.sh test`;第一次运行会克隆并构建 Rust Core,`LITHE_CORE_RUST_DIR` +`node scripts/e2e-host.mjs --suite profiles` 只运行 Profile 用例,只需设置 `LITHE_TEST_MAVEN_PLUGIN_ARCHIVE`。 +CI 在固定宿主支持插件所需的 `buildProviders` 版本时,用打包作业的插件包运行此用例。 + +脚本把固定版本的宿主(只取 `desktop/` 和 `scripts/`)检出到 `.artifacts/lithe-host`, +通过 Go overlay 加载本仓库的测试,再运行宿主的 `scripts/desktop/desktop-go.sh test`。第一次运行会克隆并构建 Rust Core,`LITHE_CORE_RUST_DIR` 可以指向本地的 Core 检出。`--ref <分支或 commit>` 换一个宿主版本试跑,`--run <正则>` 只跑部分测试。 测试用的是宿主内部的测试工具,升级 `lithe-host.json` 的 `revision` 时可能要同步修改测试。 diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index 39cc636..286f52d 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -63,14 +63,17 @@ JDT 侧的项目导入归 Java Support 插件维护。 ## java-maven-profiles-dependencies **能力**:构建选项 Profiles 传 `-P `,候选值从反应堆、父 POM 和 `settings.xml` 读取,也可以手动补充; +随包 Maven 扩展用 Maven 自身的 `ProfileSelector` 计算应用 Lithe 覆盖前的默认 Profile(含 `.mvn/maven.config` 中的启用和禁用、`settings.xml`、条件激活以及 Maven 3.9 的 `packaging` 条件)写入 `optionDefaults.profiles`。当前反应堆实际激活的 Profile 由 Maven 项目模型提供,写入 `optionActiveChoices.profiles`,包括 `settings.xml` 和命令行同时激活的选项。扩展还输出 `optionExcludePrefixes.profiles = "-"`,支持在 Build 工具窗口树、构建选项和运行配置里勾选启用或以 `-` 显式取消默认激活 Profile; 依赖树显示整个反应堆或单个模块的依赖(含作用域和传递依赖),反应堆内未安装的兄弟模块也能解析。 -**证据**:`plugin.json` 的 `buildSystems[0].options`(`profiles`)和 `buildSystems[0].dependencies`、`extension/`、 +**证据**:`plugin.json` 的 `buildSystems[0].options`(`profiles`)和 `buildSystems[0].dependencies`、`extension/`(`ModelExport.java`)、 `scripts/test.mjs`、宿主端到端测试里 `app` 模块依赖 `core` 的检查。 -**依赖的宿主能力**:`buildSystems` 的构建选项、依赖命令和 `litheDependencies` 解码。 +**自动化**:`node scripts/test.mjs` 在 Maven 3.6.3 和运行器版本验证原生 Profile 语义。宿主能力版本匹配时,CI 另用 `node scripts/e2e-host.mjs --suite profiles` 验证构建树、编译和重开。 -**最近验证**:2026-11-14,macOS arm64,插件 0.0.1 发布包,宿主 `059d878d4`,`node scripts/e2e-host.mjs`:`TestOfficialMavenPluginBuildsAReactor` 检查了 `app` 对反应堆兄弟模块 `core` 的依赖。Profiles 切换、作用域、传递依赖和大依赖树没有自动化覆盖。 +**依赖的宿主能力**:`buildSystems` 的构建选项(含 `optionDefaults`、`optionActiveChoices`、`optionExcludePrefixes` 与 `presentation: "tree"` 勾选树节点)、依赖命令和 `litheDependencies` 解码。 + +**最近验证**:2026-11-18,macOS arm64,插件 1.0.0 打包产物,`node scripts/test.mjs` 验证了反应堆 `optionValues.profiles`、`optionDefaults.profiles`(``)与 `optionExcludePrefixes.profiles = "-"` 的导出,以及通过 `-P -dev,prod` 切换激活模块和 `-P -dev` 取消全部默认 Profile 后模型按新 Profile 重读且 `optionDefaults` 保持不变。Maven 3.6.3 和 3.9.16 验证了项目配置与打包类型激活基线。Maven 3.9.16 还验证了当前激活集合随这两次切换分别变为 `["prod"]` 和 `[]`,以及 `settings.xml` 激活 `dev` 与命令行选择 `prod` 可以同时生效。固定宿主 `6f31984` 上的 `TestOfficialMavenPluginSwitchesActiveProfilesInBuildTree` 验证项目 Maven 配置的勾选、切换、编译、重开及已安装插件包内容校验;2026-11-14 宿主端到端测试 `TestOfficialMavenPluginBuildsAReactor` 检查了 `app` 对反应堆兄弟模块 `core` 的依赖。完整原生 UI 手工验收与大依赖树仍待执行。 **验证方法**(macOS): 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 81aedbf..9504338 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 @@ -16,6 +16,7 @@ import ( "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/plugininstall" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" @@ -174,7 +175,7 @@ func runBuildTaskToEnd(t *testing.T, h *harness, p *project, projectID, taskID s } awaitStateWithin(t, h, limit, "the "+taskID+" task", func() bool { return p.build.operation == nil }) output := op.session.output.all() - if p.build.status != h.app.text.Build.Succeeded { + if op.session.outcome != runSucceeded { t.Fatalf("%s did not succeed: status=%q output=%q", taskID, p.build.status, output) } return output @@ -332,3 +333,109 @@ func TestOfficialMavenPluginBuildsAReactor(t *testing.T) { h.settle() assertPackageUnchanged(t, installed, before) } + +// TestOfficialMavenPluginSwitchesActiveProfilesInBuildTree installs the Maven Build archive, +// verifies a Profile enabled by .mvn/maven.config appears checked in the Build tool window, +// toggles from dev to prod through the real checkbox UI, and checks that model reload, +// compile and project reopen all honor -P -dev,prod. +func TestOfficialMavenPluginSwitchesActiveProfilesInBuildTree(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() + modulePom := func(name string) string { + return "\n 4.0.0\n" + + " demoreactor1.0.0-SNAPSHOT\n" + + " " + name + "\n\n" + } + writePluginFixture(t, root, map[string]string{ + "pom.xml": "\n 4.0.0\n" + + " demoreactor1.0.0-SNAPSHOTpom\n" + + " 11UTF-8\n" + + " \n" + + " devdev-mod\n" + + " prodprod-mod\n" + + " \n\n", + ".mvn/maven.config": "-Pdev\n", + "dev-mod/pom.xml": modulePom("dev-mod"), + "dev-mod/src/main/java/demo/dev/DevOnly.java": "package demo.dev;\npublic final class DevOnly {}\n", + "prod-mod/pom.xml": modulePom("prod-mod"), + "prod-mod/src/main/java/demo/prod/ProdOk.java": "package demo.prod;\npublic final class ProdOk {}\n", + }) + h.open(root) + p := h.app.project + if p == nil { + t.Fatal("the reactor did not open") + } + h.app.reduceChrome(core.ToggleChrome(itemBuild)) + instance := awaitBuildModel(t, h, p, "maven", 3*time.Minute) + if modelProjectNamed(instance.Model, "dev-mod") == nil || modelProjectNamed(instance.Model, "prod-mod") != nil { + t.Fatalf("initial projects = %+v, want the project config to activate dev-mod", instance.Model.Projects) + } + + awaitStateWithin(t, h, 30*time.Second, "the Build tree layout", func() bool { + return p.build.instances[0].trees.whole != nil && !p.build.instances[0].trees.wholeOut + }) + h.settle() + h.click(center(h.labelBounds("Profiles"))) + h.settle() + + language := h.app.language() + toggle := func(choice string) { + t.Helper() + awaitStateWithin(t, h, 30*time.Second, "tree ready before toggling "+choice, func() bool { + return !p.build.optionSaving && !p.build.loading && len(p.build.instances) == 1 && + p.build.instances[0].modelLoaded && !p.build.instances[0].trees.wholeOut + }) + h.settle() + label := i18n.SharedFormat(language, "desktop.build.toggleOptionChoice", map[string]string{ + "option": "Profiles", + "choice": choice, + }) + h.clickNamed(label) + awaitStateWithin(t, h, 3*time.Minute, "reload after toggling "+choice, func() bool { + return !p.build.optionSaving && p.build.loaded && !p.build.loading && !p.build.reloadPending && + len(p.build.instances) == 1 && p.build.instances[0].modelLoaded && !p.build.instances[0].modelLoading + }) + } + + toggle("prod") + toggle("dev") + instance = &p.build.instances[0] + if modelProjectNamed(instance.Model, "prod-mod") == nil || modelProjectNamed(instance.Model, "dev-mod") != nil { + t.Fatalf("projects after switching to prod = %+v, want prod-mod only", instance.Model.Projects) + } + + 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(filepath.Join(root, "prod-mod/target/classes/demo/prod/ProdOk.class")); err != nil { + t.Fatalf("prod-mod did not compile: %v", err) + } + if _, err := os.Stat(filepath.Join(root, "dev-mod/target/classes/demo/dev/DevOnly.class")); !os.IsNotExist(err) { + t.Fatalf("inactive dev-mod was compiled: %v", err) + } + + // Reopening the workspace keeps -P -dev,prod on cold start before decodeModel runs. + h.app.closeProject() + awaitStateWithin(t, h, 30*time.Second, "the closed project", func() bool { return h.app.project == nil }) + h.open(root) + p = h.app.project + h.app.loadBuildSystems(p) + reopened := awaitBuildModel(t, h, p, "maven", 3*time.Minute) + if modelProjectNamed(reopened.Model, "prod-mod") == nil || modelProjectNamed(reopened.Model, "dev-mod") != nil { + t.Fatalf("projects after reopen = %+v, want prod-mod only", reopened.Model.Projects) + } + 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 13ed172..5d8f23e 100644 --- a/e2e/host/lithe-host.json +++ b/e2e/host/lithe-host.json @@ -1,10 +1,19 @@ { "repository": "https://github.com/1lck/Lithe-IDEA.git", - "revision": "1ce4085e7012a8b9e887c5bab734ef3fd561a7f8", + "revision": "6f319840219a5788ca897ec01a378184efea3471", "packages": { - "./internal/workbench": "^TestOfficialMavenPlugin(BuildsAReactor|RunsASpringBootApplication|DebugsASpringBootApplication)$", + "./internal/workbench": "^TestOfficialMavenPlugin(BuildsAReactor|RunsASpringBootApplication|DebugsASpringBootApplication|SwitchesActiveProfilesInBuildTree)$", "./internal/projectgen": "^TestMavenPlugin" }, + "suites": { + "profiles": { + "hostBuildProviders": [0], + "packages": { + "./internal/workbench": "^TestOfficialMavenPluginSwitchesActiveProfilesInBuildTree$" + }, + "requiredEnvironment": ["LITHE_TEST_MAVEN_PLUGIN_ARCHIVE"] + } + }, "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", diff --git a/extension/pom.xml b/extension/pom.xml index f058e3c..78fe966 100644 --- a/extension/pom.xml +++ b/extension/pom.xml @@ -35,6 +35,12 @@ ${mavenVersion} provided + + org.apache.maven + maven-embedder + ${mavenVersion} + provided + org.slf4j slf4j-api 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 432be50..235e63d 100644 --- a/extension/src/main/java/io/github/litheidea/maven/LitheLifecycleParticipant.java +++ b/extension/src/main/java/io/github/litheidea/maven/LitheLifecycleParticipant.java @@ -11,9 +11,12 @@ import org.apache.maven.AbstractMavenLifecycleParticipant; import org.apache.maven.MavenExecutionException; import org.apache.maven.execution.MavenSession; +import org.apache.maven.model.profile.ProfileSelector; import org.apache.maven.plugin.MavenPluginManager; import org.apache.maven.plugin.version.PluginVersionResolver; import org.apache.maven.project.ProjectDependenciesResolver; +import org.apache.maven.rtinfo.RuntimeInformation; +import org.apache.maven.settings.building.SettingsBuilder; /** * Writes what Lithe asked for once Maven has read the reactor, before any @@ -42,22 +45,32 @@ public final class LitheLifecycleParticipant extends AbstractMavenLifecycleParti private final MavenPluginManager pluginManager; private final PluginVersionResolver versionResolver; private final ProjectDependenciesResolver dependenciesResolver; + private final ProfileSelector profileSelector; + private final SettingsBuilder settingsBuilder; + private final RuntimeInformation runtime; @Inject public LitheLifecycleParticipant( MavenPluginManager pluginManager, PluginVersionResolver versionResolver, - ProjectDependenciesResolver dependenciesResolver) { + ProjectDependenciesResolver dependenciesResolver, + ProfileSelector profileSelector, + SettingsBuilder settingsBuilder, + RuntimeInformation runtime) { this.pluginManager = pluginManager; this.versionResolver = versionResolver; this.dependenciesResolver = dependenciesResolver; + this.profileSelector = profileSelector; + this.settingsBuilder = settingsBuilder; + this.runtime = runtime; } @Override public void afterProjectsRead(MavenSession session) throws MavenExecutionException { String modelOutput = property(session, MODEL_OUTPUT); if (modelOutput != null) { - write(modelOutput, Json.write(new ModelExport(session, pluginManager, versionResolver).document())); + write(modelOutput, Json.write(new ModelExport(session, pluginManager, versionResolver, + profileSelector, settingsBuilder, runtime.isMavenVersion("[3.9.0,)")).document())); } String dependenciesOutput = property(session, DEPENDENCIES_OUTPUT); if (dependenciesOutput != null) { diff --git a/extension/src/main/java/io/github/litheidea/maven/MavenConfigProfiles.java b/extension/src/main/java/io/github/litheidea/maven/MavenConfigProfiles.java new file mode 100644 index 0000000..85b80e9 --- /dev/null +++ b/extension/src/main/java/io/github/litheidea/maven/MavenConfigProfiles.java @@ -0,0 +1,51 @@ +package io.github.litheidea.maven; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; +import org.apache.commons.cli.ParseException; +import org.apache.maven.cli.CLIManager; + +/** Restores the project-side profile switches Maven merges with the invocation's arguments. */ +final class MavenConfigProfiles { + private MavenConfigProfiles() {} + + static void read(File root, boolean maven39OrLater, List active, List inactive) + throws IOException, ParseException { + if (root == null) { + return; + } + Path config = root.toPath().resolve(".mvn").resolve("maven.config"); + if (!Files.isRegularFile(config)) { + return; + } + String[] arguments; + // Maven 3.9 changed from whitespace tokens to one UTF-8 argument per line. + if (maven39OrLater) { + try (Stream lines = Files.lines(config, StandardCharsets.UTF_8)) { + arguments = lines.filter(line -> !line.isEmpty() && !line.startsWith("#")).toArray(String[]::new); + } + } else { + arguments = new String(Files.readAllBytes(config), Charset.defaultCharset()).trim().split("\\s+"); + } + String[] groups = new CLIManager().parse(arguments).getOptionValues(CLIManager.ACTIVATE_PROFILES); + if (groups == null) { + return; + } + for (String group : groups) { + for (String value : group.split(",")) { + String profile = value.trim(); + if (profile.startsWith("-") || profile.startsWith("!")) { + inactive.add(profile.substring(1)); + } else if (!profile.isEmpty()) { + active.add(profile.startsWith("+") ? profile.substring(1) : profile); + } + } + } + } +} 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 431d0d3..6b047d3 100644 --- a/extension/src/main/java/io/github/litheidea/maven/ModelExport.java +++ b/extension/src/main/java/io/github/litheidea/maven/ModelExport.java @@ -2,26 +2,36 @@ import java.io.File; import java.io.IOException; +import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Properties; import java.util.Set; import java.util.TreeSet; +import org.apache.commons.cli.ParseException; import org.apache.maven.MavenExecutionException; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.apache.maven.model.Profile; import org.apache.maven.model.Resource; +import org.apache.maven.model.building.ModelProblemCollector; +import org.apache.maven.model.building.ModelProblemCollectorRequest; +import org.apache.maven.model.profile.DefaultProfileActivationContext; +import org.apache.maven.model.profile.ProfileSelector; import org.apache.maven.plugin.MavenPluginManager; import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.apache.maven.plugin.version.DefaultPluginVersionRequest; import org.apache.maven.plugin.version.PluginVersionResolver; import org.apache.maven.project.MavenProject; +import org.apache.maven.settings.Settings; +import org.apache.maven.settings.building.DefaultSettingsBuildingRequest; +import org.apache.maven.settings.building.SettingsBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,13 +54,25 @@ final class ModelExport { private final MavenSession session; private final MavenPluginManager pluginManager; private final PluginVersionResolver versionResolver; + private final ProfileSelector profileSelector; + private final SettingsBuilder settingsBuilder; + private final boolean maven39OrLater; /** Goals by plugin coordinates, so each descriptor is read once per run. */ private final Map goalsByPlugin = new LinkedHashMap<>(); - ModelExport(MavenSession session, MavenPluginManager pluginManager, PluginVersionResolver versionResolver) { + ModelExport( + MavenSession session, + MavenPluginManager pluginManager, + PluginVersionResolver versionResolver, + ProfileSelector profileSelector, + SettingsBuilder settingsBuilder, + boolean maven39OrLater) { this.session = session; this.pluginManager = pluginManager; this.versionResolver = versionResolver; + this.profileSelector = profileSelector; + this.settingsBuilder = settingsBuilder; + this.maven39OrLater = maven39OrLater; } Map document() { @@ -92,8 +114,12 @@ Map document() { } addGoals(project, path, tasks); } + Set profiles = profileIds(); + Set defaultProfiles = defaultProfileIds(profiles); Map optionValues = new LinkedHashMap<>(); - optionValues.put("profiles", new ArrayList<>(profileIds())); + optionValues.put("profiles", new ArrayList<>(profiles)); + Map optionExcludePrefixes = new LinkedHashMap<>(); + optionExcludePrefixes.put("profiles", "-"); Map document = new LinkedHashMap<>(); document.put("format", "litheBuildModel"); document.put("version", 0); @@ -102,6 +128,14 @@ Map document() { document.put("tasks", tasks); document.put("contentRoots", contentRoots); document.put("optionValues", optionValues); + if (!defaultProfiles.isEmpty()) { + Map optionDefaults = new LinkedHashMap<>(); + optionDefaults.put("profiles", new ArrayList<>(defaultProfiles)); + document.put("optionDefaults", optionDefaults); + } + document.put("optionExcludePrefixes", optionExcludePrefixes); + document.put("optionActiveChoices", + Collections.singletonMap("profiles", new ArrayList<>(activeProfileIds(profiles)))); return document; } @@ -303,10 +337,136 @@ private Set profileIds() { return ids; } - /** A comma would split the ID in {@code -P}, so such a profile is left out. */ + /** Profiles Maven actually applied when it built this reactor model. */ + private Set activeProfileIds(Set knownProfiles) { + Set active = new TreeSet<>(); + for (MavenProject project : session.getProjects()) { + // The build result records parent profiles evaluated in this project's context. + for (List ids : project.getInjectedProfileIds().values()) { + for (String id : ids) { + addKnownProfile(active, knownProfiles, id); + } + } + } + return active; + } + + /** + * Profiles Maven activates before the IDE applies a selection. Project CLI + * configuration remains part of this baseline, along with + * {@code }, {@code settings.xml} + * {@code }, and condition-activated ({@code }, + * {@code }, {@code }, {@code }) profiles evaluated by + * Maven's own {@link ProfileSelector} against a clean activation context. + */ + private Set defaultProfileIds(Set knownProfiles) { + Set defaults = new TreeSet<>(); + Properties userProperties = cleanUserProperties(); + Settings effectiveSettings = effectiveSettings(userProperties); + List activeIds = effectiveSettings == null + ? new ArrayList<>() : new ArrayList<>(effectiveSettings.getActiveProfiles()); + List inactiveIds = new ArrayList<>(); + try { + MavenConfigProfiles.read(session.getRequest().getMultiModuleProjectDirectory(), + maven39OrLater, activeIds, inactiveIds); + } catch (IOException | ParseException error) { + LOG.warn("Lithe could not read Maven project profile defaults ({})", error.getClass().getSimpleName()); + return defaults; + } + List settingsProfiles = session.getRequest().getProfiles(); + ModelProblemCollector problems = new ModelProblemCollector() { + @Override + public void add(ModelProblemCollectorRequest request) {} + }; + for (MavenProject project : session.getProjects()) { + Properties projectUserProperties = new Properties(); + projectUserProperties.putAll(userProperties); + if (maven39OrLater && project.getOriginalModel() != null) { + // Maven evaluates the whole parent lineage in the starting POM's packaging context. + projectUserProperties.putIfAbsent("packaging", project.getOriginalModel().getPackaging()); + } + DefaultProfileActivationContext context = new DefaultProfileActivationContext() + .setActiveProfileIds(activeIds) + .setInactiveProfileIds(inactiveIds) + .setSystemProperties(session.getSystemProperties()) + .setUserProperties(projectUserProperties) + .setProjectDirectory(project.getBasedir()); + Properties externalProperties = new Properties(); + for (Profile active : profileSelector.getActiveProfiles(settingsProfiles, context, problems)) { + addKnownProfile(defaults, knownProfiles, active.getId()); + externalProperties.putAll(active.getProperties()); + } + externalProperties.putAll(projectUserProperties); + context.setUserProperties(externalProperties); + for (MavenProject current = project; current != null; current = current.getParent()) { + if (current.getOriginalModel() == null || current.getOriginalModel().getProfiles().isEmpty()) { + continue; + } + context.setProjectProperties(current.getOriginalModel().getProperties()); + for (Profile active : profileSelector.getActiveProfiles(current.getOriginalModel().getProfiles(), context, problems)) { + addKnownProfile(defaults, knownProfiles, active.getId()); + } + } + } + return defaults; + } + + /** + * Reads global and user {@code settings.xml} directly: {@code session.getSettings()} + * is an adapter over {@code MavenExecutionRequest}, whose active profiles + * already contain command-line {@code -P} selections. + */ + private Settings effectiveSettings(Properties userProperties) { + if (settingsBuilder == null || session.getRequest() == null) { + return null; + } + try { + DefaultSettingsBuildingRequest request = new DefaultSettingsBuildingRequest() + .setGlobalSettingsFile(session.getRequest().getGlobalSettingsFile()) + .setUserSettingsFile(session.getRequest().getUserSettingsFile()) + .setSystemProperties(session.getSystemProperties()) + .setUserProperties(userProperties); + return settingsBuilder.build(request).getEffectiveSettings(); + } catch (Exception error) { + LOG.warn("Lithe could not read settings.xml active profiles: {}", error.getMessage()); + return null; + } + } + + private Properties cleanUserProperties() { + Properties cleaned = new Properties(); + if (session.getUserProperties() == null) { + return cleaned; + } + for (String name : session.getUserProperties().stringPropertyNames()) { + if (!name.startsWith("lithe.") && !"maven.ext.class.path".equals(name)) { + cleaned.setProperty(name, session.getUserProperties().getProperty(name)); + } + } + return cleaned; + } + + private static void addKnownProfile(Set defaults, Set knownProfiles, String id) { + if (id == null) { + return; + } + String trimmed = id.trim(); + if (knownProfiles.contains(trimmed)) { + defaults.add(trimmed); + } + } + + /** + * A comma would split the ID in {@code -P}, and a leading {@code -} or + * {@code !} means deactivation in Maven, so such a profile is left out. + */ private static void addProfile(Set ids, String id) { - if (id != null && !id.trim().isEmpty() && id.indexOf(',') < 0) { - ids.add(id.trim()); + if (id == null) { + return; + } + String trimmed = id.trim(); + if (!trimmed.isEmpty() && trimmed.indexOf(',') < 0 && !trimmed.startsWith("-") && !trimmed.startsWith("!")) { + ids.add(trimmed); } } diff --git a/scripts/e2e-host.mjs b/scripts/e2e-host.mjs index aaf0a99..0820ff7 100644 --- a/scripts/e2e-host.mjs +++ b/scripts/e2e-host.mjs @@ -1,12 +1,12 @@ // Runs this plugin's host end-to-end tests against a pinned Lithe desktop host. // -// node scripts/e2e-host.mjs [--source ] [--ref ] [--run ] +// node scripts/e2e-host.mjs [--source ] [--ref ] [--run ] [--suite ] // // 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 +// (desktop/ and scripts/ only) and overlays the plugin's test files while running +// the host's scripts/desktop/desktop-go.sh test, 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. @@ -15,27 +15,17 @@ // 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'; +// --suite selects a named test group and its required plugin inputs. +import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises'; +import { join, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { parseArgs } from 'node:util'; +import { runCommand, withInterrupts } from './process.mjs'; 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 = []; @@ -48,40 +38,47 @@ async function hostTestFiles(directory = join(tests, 'desktop')) { } /** Checks out `ref` from `source` into the disposable work directory, desktop/ and scripts/ only. */ -async function checkoutHost(source, ref) { +async function checkoutHost(source, ref, signal) { + const run = (args) => runCommand('git', args, { timeoutMs: 120_000, signal }); await mkdir(work, { recursive: true }); - await run('git', ['init', '-q', work]); - await run('git', ['-C', work, 'sparse-checkout', 'set', '--cone', 'desktop', 'scripts']); + await run(['init', '-q', work]); + await run(['-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']); + await run(['-C', work, 'config', 'remote.origin.url', source]); + await run(['-C', work, 'fetch', '-q', '--depth', '1', '--filter=blob:none', 'origin', ref]); + await run(['-C', work, 'checkout', '-q', '--force', '--detach', 'FETCH_HEAD']); + // Discard test files left by earlier versions of this runner in its disposable checkout. + await run(['-C', work, 'clean', '-q', '-f', '-d', '--', 'desktop']); } const { values } = parseArgs({ - options: { source: { type: 'string' }, ref: { type: 'string' }, run: { type: 'string' } }, + options: { source: { type: 'string' }, ref: { type: 'string' }, run: { type: 'string' }, suite: { 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]); +const suite = values.suite && pin.suites?.[values.suite]; +if (values.suite && !suite) throw new Error(`Unknown host E2E suite: ${values.suite}`); +const required = suite?.requiredEnvironment ?? Object.keys(pin.requiredEnvironment ?? {}); +const missing = required.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')}`); + throw new Error(`Set the plugin inputs first:\n${missing.map((name) => ` ${name}: ${pin.requiredEnvironment[name]}`).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 }); -} +await withInterrupts(async (signal) => { + await checkoutHost(source, values.ref ?? pin.revision, signal); + const overlay = join(root, '.artifacts', 'lithe-host-overlay.json'); + const files = await hostTestFiles(); + await writeFile(overlay, JSON.stringify({ + Replace: Object.fromEntries(files.map((file) => [join(work, file), join(tests, file)])), + })); + for (const [pkg, selection] of Object.entries(suite?.packages ?? pin.packages)) { + await runCommand('bash', ['scripts/desktop/desktop-go.sh', 'test', '-overlay', overlay, pkg, + '-count=1', '-v', '-timeout', pin.timeout ?? '20m', '-run', values.run ?? selection], + { cwd: work, timeoutMs: 1_200_000, signal }); + } +}); diff --git a/scripts/test.mjs b/scripts/test.mjs index 754c013..d026527 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -216,6 +216,130 @@ async function test(signal) { await check("profiles become choices of the Profiles option", () => { assert.deepEqual(model.optionValues.profiles, ["ci", "release"]); + assert.equal(model.optionDefaults, undefined); + assert.deepEqual(model.optionActiveChoices, { profiles: [] }); + assert.deepEqual(model.optionExcludePrefixes, { profiles: "-" }); + }); + + const profileRoot = join(scratch, "profiles-reactor"); + const emptySettings = join(scratch, "profile-empty-settings.xml"); + writeFileSync(emptySettings, ""); + const readProfileModel = async (tag, profileArg, settings = emptySettings) => { + const outputFile = join(outputs, `profiles-${tag}.json`); + const extra = profileArg ? ["-P", profileArg] : []; + const argv = [ + ...expand(buildSystem.invocation.globalArguments, { outputFile }), + "-gs", emptySettings, "-s", settings, + ...extra, + ...expand(buildSystem.model.arguments, { outputFile }), + ]; + await runCommand(maven, argv, { + cwd: profileRoot, env: { ...process.env, MAVEN_ARGS: "" }, + stdio: ["ignore", "ignore", "inherit"], timeoutMs, signal, + }); + return JSON.parse(readFileSync(outputFile, "utf8")); + }; + + await check("default-active profiles stay reported across -P switches and deactivations", async () => { + mkdirSync(join(profileRoot, "dev-module"), { recursive: true }); + mkdirSync(join(profileRoot, "prod-module"), { recursive: true }); + writeFileSync(join(profileRoot, "pom.xml"), [ + '', + '', + " 4.0.0", + " demo", + " profiles-reactor", + " 1.0.0-SNAPSHOT", + " pom", + " ", + " ", + " dev", + " true", + " dev-module", + " ", + " ", + " prod", + " prod-module", + " ", + " ", + "", + ].join("\n")); + for (const name of ["dev-module", "prod-module"]) { + writeFileSync(join(profileRoot, name, "pom.xml"), [ + '', + '', + " 4.0.0", + " demoprofiles-reactor1.0.0-SNAPSHOT", + ` ${name}`, + "", + ].join("\n")); + } + const initial = await readProfileModel("default", ""); + assert.deepEqual(initial.optionValues.profiles, ["dev", "prod"]); + assert.deepEqual(initial.optionDefaults, { profiles: ["dev"] }); + assert.deepEqual(initial.optionActiveChoices, { profiles: ["dev"] }); + assert.deepEqual(initial.optionExcludePrefixes, { profiles: "-" }); + assert.deepEqual(initial.projects.map((project) => project.name), ["profiles-reactor", "dev-module"]); + + const switched = await readProfileModel("switched", "-dev,prod"); + assert.deepEqual(switched.optionDefaults, { profiles: ["dev"] }); + assert.deepEqual(switched.optionActiveChoices, { profiles: ["prod"] }); + assert.deepEqual(switched.projects.map((project) => project.name), ["profiles-reactor", "prod-module"]); + + const cleared = await readProfileModel("cleared", "-dev"); + assert.deepEqual(cleared.optionDefaults, { profiles: ["dev"] }); + assert.deepEqual(cleared.optionActiveChoices, { profiles: [] }); + assert.deepEqual(cleared.projects.map((project) => project.name), ["profiles-reactor"]); + + const settings = join(profileRoot, "settings.xml"); + writeFileSync(settings, "dev"); + const fromBothSources = await readProfileModel("settings-and-cli", "prod", settings); + assert.deepEqual(fromBothSources.optionActiveChoices, { profiles: ["dev", "prod"] }); + assert.deepEqual(fromBothSources.projects.map((project) => project.name), + ["profiles-reactor", "dev-module", "prod-module"]); + }); + + await check("packaging activation is reflected in baseline defaults and can be disabled", async () => { + const pom = join(profileRoot, "pom.xml"); + const original = readFileSync(pom, "utf8"); + writeFileSync(pom, original.replace("true", + "packagingpom")); + try { + const baseline = await readProfileModel("packaging", ""); + const active = baseline.projects.some((project) => project.name === "dev-module") ? ["dev"] : []; + assert.deepEqual(baseline.optionDefaults?.profiles ?? [], active); + assert.deepEqual(baseline.optionActiveChoices?.profiles, active); + const disabled = await readProfileModel("packaging-disabled", "-dev"); + assert.deepEqual(disabled.optionDefaults?.profiles ?? [], active); + assert.deepEqual(disabled.optionActiveChoices?.profiles, []); + assert.equal(disabled.projects.some((project) => project.name === "dev-module"), false); + + // A parent Profile evaluates packaging in the child's model context. + writeFileSync(pom, original + .replace("", "prod-module") + .replace("true", + "packagingjar") + .replace("dev-module", "")); + const inherited = await readProfileModel("packaging-parent", ""); + assert.deepEqual(inherited.optionDefaults?.profiles ?? [], active); + assert.deepEqual(inherited.optionActiveChoices?.profiles, active); + } finally { + writeFileSync(pom, original); + } + }); + + await check("project Maven config keeps its active and inactive profiles in the baseline", async () => { + mkdirSync(join(profileRoot, ".mvn")); + writeFileSync(join(profileRoot, ".mvn", "maven.config"), "--activate-profiles\n+prod\n-P\n!dev\n"); + const baseline = await readProfileModel("project-config", ""); + assert.deepEqual(baseline.optionDefaults?.profiles, ["prod"]); + assert.deepEqual(baseline.optionActiveChoices?.profiles, ["prod"]); + assert.deepEqual(baseline.projects.map((project) => project.name), ["profiles-reactor", "prod-module"]); + + const cleared = await readProfileModel("project-config-disabled", "-prod"); + assert.deepEqual(cleared.optionDefaults?.profiles, ["prod"]); + assert.deepEqual(cleared.optionActiveChoices?.profiles, []); + assert.deepEqual(cleared.projects.map((project) => project.name), ["profiles-reactor"]); }); await check("plugin goals are model tasks filed under Plugins", () => {