From 0e3697688ab14aae9a8fff27bf8ec1a521e029f2 Mon Sep 17 00:00:00 2001 From: wgw Date: Wed, 28 Oct 2026 14:58:49 +0800 Subject: [PATCH 01/24] feat(maven): expose source-backed native configuration --- .github/workflows/ci.yml | 28 +++ README.md | 34 ++- .../maven/backend/ConfigurationProbe.java | 62 +++++ .../litheidea/maven/backend/Fingerprint.java | 72 +----- .../litheidea/maven/backend/MavenBackend.java | 17 +- .../litheidea/maven/backend/MavenRuns.java | 12 +- .../maven/backend/NativeSources.java | 74 ++++++ .../litheidea/maven/backend/Snapshots.java | 11 +- .../maven/LitheLifecycleParticipant.java | 22 +- .../litheidea/maven/NativeSettingsEvents.java | 46 ++++ .../litheidea/maven/SettingsExport.java | 215 ++++++++++++++++++ io.github.lithe-idea.maven-build/plugin.json | 3 +- scripts/test-backend.mjs | 21 +- scripts/test-configuration.mjs | 119 ++++++++++ scripts/test-native-core.mjs | 1 + scripts/test.mjs | 2 +- test/fixtures/fake-maven-backend.mjs | 9 + 17 files changed, 662 insertions(+), 86 deletions(-) create mode 100644 backend/src/main/java/io/github/litheidea/maven/backend/ConfigurationProbe.java create mode 100644 backend/src/main/java/io/github/litheidea/maven/backend/NativeSources.java create mode 100644 extension/src/main/java/io/github/litheidea/maven/NativeSettingsEvents.java create mode 100644 extension/src/main/java/io/github/litheidea/maven/SettingsExport.java create mode 100644 scripts/test-configuration.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f46cbbc..69695e7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,6 +10,10 @@ on: description: 'Exact lithe-plugin-docs commit for development-only Java 8 validation' required: true type: string + core-revision: + description: 'Optional exact Lithe commit for current native configuration and Core workflows' + required: false + type: string permissions: contents: read @@ -153,6 +157,30 @@ jobs: env: LITHE_TEST_JAVA: ${{ env.JAVA_HOME_8_X64 }}/bin/java run: node scripts/test.mjs + - name: Require a fixed Core revision when selected + if: inputs.core-revision != '' + env: + CORE_REVISION: ${{ inputs.core-revision }} + run: '[[ "$CORE_REVISION" =~ ^[0-9a-f]{40}$ ]]' + - uses: actions/checkout@v4 + if: inputs.core-revision != '' + with: + repository: 1lck/Lithe-IDEA + ref: ${{ inputs.core-revision }} + path: .artifacts/core-source + persist-credentials: false + - uses: dtolnay/rust-toolchain@stable + if: inputs.core-revision != '' + - name: Build the selected host Core and verify real native settings + if: inputs.core-revision != '' + env: + LITHE_TEST_JAVA: ${{ env.JAVA_HOME_8_X64 }}/bin/java + run: | + cargo build --locked --manifest-path .artifacts/core-source/rust/Cargo.toml -p lithe-core --lib + export LITHE_CORE_LIBRARY="$GITHUB_WORKSPACE/.artifacts/core-source/rust/target/debug/liblithe_core.so" + export LITHE_TEST_MAVEN="${MVN:-$(command -v mvn)}" + node scripts/test-configuration.mjs + node scripts/test-native-core.mjs - name: Prove the release inputs stayed unchanged run: | git diff --exit-code -- sdk.lock.json backend/pom.xml extension/pom.xml io.github.lithe-idea.maven-build diff --git a/README.md b/README.md index 727dfc4..2b50d11 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ 为 [Lithe](https://github.com/1lck/Lithe-IDEA) 提供 Maven 项目支持:识别 `pom.xml`,在 Maven 工具窗口里列出 模块、生命周期和插件目标,运行任务和测试,查看依赖树。 -这是一个**社区插件**,用 Lithe 的构建系统接口(插件 API 3 的 `buildSystems` 和 `buildProviders: 3`)实现, +这是一个**社区插件**,用 Lithe 的构建系统接口(插件 API 3 的 `buildSystems` 和 `buildProviders: 7`)实现, 除了下面说的 Maven 扩展 jar 和读取项目用的 Java 后端,没有任何宿主代码。 > English: Maven support for Lithe through the declarative `buildSystems` plugin API — project tree, lifecycle and @@ -213,3 +213,35 @@ node scripts/verify-scripts.mjs --host-bundle /Applications/Lithe.app ## 许可 [Apache-2.0](LICENSE)。图标来自 IntelliJ Platform,见 [NOTICE](NOTICE)。 + +## 原生配置(协议 7,开发中) + +通用的构建系统设置页通过 `lithe/build/configuration` 读取 Maven 实际选中的安装级和用户级 +settings.xml,显示非敏感的 localRepository、activeProfiles 原值及实际生效值。打开页面只读; +只有显式开启覆盖并保存,宿主才修改所列来源。安装来源以及与安装文件相同的用户来源始终只读。 +保存使用源字节哈希防止覆盖外部编辑,保留其他内容、注释、权限和凭据,再由 Maven 重新读取 +生效值。命令行覆盖值单独显示,不能将保存的原值直接当成生效值。 + +扩展观察 Maven 官方的 SettingsBuildingRequest/Result 事件,不重新实现配置优先级; +会话执行请求提供最终 CLI 值。配置读取在 reactor 导入前结束,因此损坏 POM 不会阻止查看 +原生配置。整个 XML 不跨 Provider RPC,服务器/代理密码等字段既不导出也不记录。工具探针 +只在已分配的工作区状态创建临时目录,调用结束清理;app 和插件安装资源不变。 + +模型缓存版本 2 只存实际上游选中的 settings/toolchains 的 URI 与字节哈希。它在读取和发布 +结果时校验来源,在下一次请求复用缓存前再次核对;修改、删除或换向选中来源即使没有 POM +事件也会使缓存失效。旧缓存只是可重建结果,版本不匹配即重新读取。来源哈希不是可跨工作树 +复用的构建身份,不复制缓存或探针目录。用户原生文件只由宿主明确保存流程写入。 + +显式运行隔离测试(不会使用或修改开发者真实 settings): + +```bash +LITHE_TEST_JAVA=/absolute/java LITHE_TEST_MAVEN=/absolute/mvn \ +LITHE_CORE_LIBRARY=/absolute/liblithe_core.dylib node scripts/test-configuration.mjs +``` + +此能力依赖尚待正式发布、锁定的配套 SDK 和宿主。源码的开发包、Core 和原生 macOS +测试通过不等于完成整个 #1495 阶段 D;旧配置数据、其余 Run/Test/Debug 和 Windows +消费者仍需完成各自迁移并删除旧路径。 + +`workflow_dispatch` 的开发 SDK lane 可额外指定 40 位 `core-revision`,构建该宿主 Core 后运行 +原生配置及真实构建/精确测试的集成;SDK、Core 都按明确提交选取,不修改正式锁定文件。 diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/ConfigurationProbe.java b/backend/src/main/java/io/github/litheidea/maven/backend/ConfigurationProbe.java new file mode 100644 index 0000000..ef7fb14 --- /dev/null +++ b/backend/src/main/java/io/github/litheidea/maven/backend/ConfigurationProbe.java @@ -0,0 +1,62 @@ +package io.github.litheidea.maven.backend; + +import io.github.litheidea.plugin.sdk.Cancellation; +import io.github.litheidea.plugin.sdk.Json; +import io.github.litheidea.plugin.sdk.PluginError; +import io.github.litheidea.plugin.sdk.Processes; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Asks the selected Maven to initialize its own settings and exit before + * project import. The extension exports only non-sensitive fields; no complete + * settings document or Maven debug output is returned over the provider wire. + */ +final class ConfigurationProbe { + static Map read(Inputs inputs, Path state, Cancellation cancellation) throws IOException { + Path work = state == null ? Files.createTempDirectory("lithe-maven-configuration-") + : Files.createTempDirectory(state, "configuration-"); + try { + Path output = work.resolve("configuration.json"); + List command = new ArrayList<>(); + command.add(inputs.maven.toString()); + command.add("-B"); command.add("-ntp"); command.add("-o"); + command.addAll(inputs.optionArguments); + command.add("-Dmaven.ext.class.path=" + inputs.extensionJar); + command.add("-Dlithe.configurationOutput=" + output); + command.add("validate"); + Processes.Result result = Processes.run(command, new Processes.Options() + .directory(inputs.root).environment(inputs.environment).cancellation(cancellation) + .maxOutputBytes(16 * 1024)); + cancellation.throwIfCancelled(); + // The extension intentionally aborts Maven after exporting settings. + // A failed invocation without that fresh output must never be + // represented as empty/default settings or disclose debug output. + if (!Files.isRegularFile(output) || Files.size(output) > 2 * 1024 * 1024) { + throw new PluginError("maven.configurationUnavailable", "Maven could not inspect its native settings (exit status " + + result.exitCode() + "). Check the selected Maven installation and settings sources."); + } + Object value = Json.parse(new String(Files.readAllBytes(output), StandardCharsets.UTF_8)); + if (!(value instanceof Map) || !"litheBuildConfiguration".equals(Json.object(value).get("format"))) { + throw new PluginError("maven.invalidConfiguration", "Maven returned an invalid native configuration snapshot."); + } + return Json.object(value); + } finally { + // Every probe owns its temporary files. A cleanup failure is visible + // instead of leaving unbounded native settings snapshots behind. + try (Stream paths = Files.walk(work)) { + List owned = paths.sorted(Comparator.reverseOrder()).limit(1025).collect(Collectors.toList()); + if (owned.size() > 1024) throw new IOException("The Maven configuration probe exceeded its cleanup limit."); + for (Path path : owned) Files.deleteIfExists(path); + } + } + } +} diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/Fingerprint.java b/backend/src/main/java/io/github/litheidea/maven/backend/Fingerprint.java index 9ece30a..e606a6b 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/Fingerprint.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/Fingerprint.java @@ -5,7 +5,6 @@ import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.security.MessageDigest; @@ -27,8 +26,8 @@ * that skips {@code target/}, {@code .git/} and {@code node_modules/}); *
  • {@code .mvn/maven.config}, {@code extensions.xml}, {@code jvm.config} * and the wrapper properties;
  • - *
  • the user and global {@code settings.xml}, the user {@code toolchains.xml}, - * and settings files named by {@code -s}/{@code -gs};
  • + *
  • native settings and toolchains sources selected by Maven are checked + * separately from the stored exact URI/hash projection;
  • *
  • the option arguments, the environment Maven reads, the executable's * path and modification time, {@code java.version}, and the extension * and backend versions.
  • @@ -39,14 +38,12 @@ */ final class Fingerprint { /** Bumped when the inputs below change meaning. */ - private static final int VERSION = 1; + private static final int VERSION = 2; private static final int MAX_DEPTH = 24; private static final int MAX_ENTRIES = 50_000; private static final Set SKIPPED = new HashSet<>(Arrays.asList("target", ".git", "node_modules")); private static final List ENVIRONMENT = Arrays.asList( "JAVA_HOME", "MAVEN_HOME", "M2_HOME", "MAVEN_OPTS", "MAVEN_ARGS", "MAVEN_CONFIG"); - private static final List SETTINGS_FLAGS = Arrays.asList( - "-s", "--settings", "-gs", "--global-settings", "-t", "--toolchains", "-gt", "--global-toolchains"); private final MessageDigest digest; @@ -68,21 +65,8 @@ static String of(Inputs inputs) throws IOException { fingerprint.addFile(".mvn/" + name, inputs.root.resolve(".mvn").resolve(name)); } - Path userHome = Paths.get(System.getProperty("user.home")); - fingerprint.addFile("userSettings", userHome.resolve(".m2/settings.xml")); - fingerprint.addFile("userToolchains", userHome.resolve(".m2/toolchains.xml")); - Path mavenHome = mavenHome(inputs); - if (mavenHome != null) { - fingerprint.add("mavenHome", mavenHome.toString()); - fingerprint.addFile("globalSettings", mavenHome.resolve("conf/settings.xml")); - } - List configArguments = mavenConfig(inputs.root); - for (List arguments : Arrays.asList(inputs.optionArguments, configArguments)) { - for (String file : settingsFiles(arguments)) { - fingerprint.addFile("settingsFile " + file, inputs.root.resolve(file)); - } - } - + // Native source identities are exported by the selected Maven and + // checked by Snapshots/NativeSources, not guessed from CLI syntax. fingerprint.add("optionArguments", String.join("\u0000", inputs.optionArguments)); for (Map.Entry entry : new TreeMap<>(inputs.hostEnvironment).entrySet()) { fingerprint.add("hostEnvironment " + entry.getKey(), entry.getValue()); @@ -97,52 +81,6 @@ static String of(Inputs inputs) throws IOException { return fingerprint.hex(); } - /** {@code -s file}, {@code --settings file}, {@code --settings=file} and {@code -sfile} forms. */ - static List settingsFiles(List arguments) { - List files = new java.util.ArrayList<>(); - for (int index = 0; index < arguments.size(); index++) { - String argument = arguments.get(index); - for (String flag : SETTINGS_FLAGS) { - if (argument.equals(flag) && index + 1 < arguments.size()) { - files.add(arguments.get(++index)); - break; - } - if (flag.startsWith("--") && argument.startsWith(flag + "=")) { - files.add(argument.substring(flag.length() + 1)); - break; - } - } - } - return files; - } - - /** The Maven installation an {@code mvn} script belongs to; none for a wrapper. */ - private static Path mavenHome(Inputs inputs) { - if (inputs.maven.getFileName().toString().startsWith("mvnw")) { - return null; - } - try { - Path real = inputs.maven.toRealPath(); - Path bin = real.getParent(); - return bin == null || bin.getParent() == null ? null : bin.getParent(); - } catch (IOException error) { - return null; - } - } - - private static List mavenConfig(Path root) { - Path config = root.resolve(".mvn/maven.config"); - if (!Files.isRegularFile(config)) { - return Collections.emptyList(); - } - try { - String text = new String(Files.readAllBytes(config), StandardCharsets.UTF_8).trim(); - return text.isEmpty() ? Collections.emptyList() : Arrays.asList(text.split("\\s+")); - } catch (IOException error) { - return Collections.emptyList(); - } - } - private void addPoms(Path root) throws IOException { TreeMap poms = new TreeMap<>(); int[] entries = {0}; diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java index 12ed122..4bd666f 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java @@ -33,6 +33,7 @@ public final class MavenBackend { private volatile Path workspaceRoot; private volatile Snapshots snapshots; private volatile MavenRuns runs; + private volatile Path workspaceState; private MavenBackend(String stateDirectory) { this.stateDirectory = stateDirectory; @@ -54,8 +55,10 @@ private void serve() { } else { backend.log("No --state directory: Maven results are not kept across restarts."); } + workspaceState = state; runs = new MavenRuns(snapshots, backend, state); }); + backend.onConfiguration((params, context) -> ConfigurationProbe.read(inputs(params), workspaceState, context.cancellation())); backend.onModel((params, context) -> copy(load(params, context).model())); backend.onDependencies(this::dependencies); backend.onExecute((params, context) -> execution(params, context, false)); @@ -95,18 +98,20 @@ private MavenRuns.Loaded load(Map params, CallContext context) t if (runs == null) { throw new PluginError("maven.notInitialized", "The Maven backend was not initialized."); } + Inputs inputs = inputs(params); + boolean refresh = Boolean.TRUE.equals(params.get("refresh")); + return runs.load(inputs, refresh, context.cancellation()); + } + + private Inputs inputs(Map params) throws IOException { Path root = root(params); - if (!Files.isDirectory(root)) { - throw new PluginError("maven.missingRoot", root + " is not a directory."); - } + if (!Files.isDirectory(root)) throw new PluginError("maven.missingRoot", "The Maven root is unavailable."); Map environment = environment(params.get("environment")); Object tool = params.get("tool"); String executable = tool instanceof Map ? Json.string(Json.object(tool), "executable") : null; Path maven = MavenExecutable.resolve(executable, root, environment); - Inputs inputs = new Inputs(root, maven, MavenExecution.optionArguments(params, false), + return new Inputs(root, maven, MavenExecution.optionArguments(params, false), environment, hostEnvironment(params.get("environment")), extensionJar()); - boolean refresh = Boolean.TRUE.equals(params.get("refresh")); - return runs.load(inputs, refresh, context.cancellation()); } private Path root(Map params) throws IOException { diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenRuns.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenRuns.java index 7dc04b6..9512584 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenRuns.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenRuns.java @@ -38,12 +38,16 @@ final class MavenRuns { static final class Loaded { private final Map model; private final Map dependencies; + private final List nativeSources; - Loaded(Map model, Map dependencies) { + Loaded(Map model, Map dependencies, List nativeSources) { this.model = model; this.dependencies = dependencies; + this.nativeSources = nativeSources; } + List nativeSources() { return nativeSources; } + Map model() { return model; } @@ -148,6 +152,7 @@ private void leave(Flight flight) { private void fly(Flight flight, Inputs inputs, String before) { try { Loaded loaded = run(inputs, flight.cancellation); + if (!NativeSources.current(loaded.nativeSources())) throw NativeSources.changed(); if (snapshots != null) { if (before.equals(Fingerprint.of(inputs))) { snapshots.write(inputs.root, before, loaded); @@ -172,6 +177,7 @@ private Loaded run(Inputs inputs, Cancellation cancellation) throws IOException try { Path model = work.resolve("model.json"); Path dependencies = work.resolve("dependencies.json"); + Path configuration = work.resolve("configuration.json"); List command = new ArrayList<>(); command.add(inputs.maven.toString()); command.add("-B"); @@ -179,6 +185,7 @@ private Loaded run(Inputs inputs, Cancellation cancellation) throws IOException command.addAll(inputs.optionArguments); command.add("-Dmaven.ext.class.path=" + inputs.extensionJar); command.add("-Dlithe.modelOutput=" + model); + command.add("-Dlithe.configurationContextOutput=" + configuration); // No lithe.dependenciesProject: every module's tree, in the same run. command.add("-Dlithe.dependenciesOutput=" + dependencies); command.add("pre-clean"); @@ -196,7 +203,8 @@ private Loaded run(Inputs inputs, Cancellation cancellation) throws IOException throw new PluginError("maven.loadFailed", "Maven could not read the project (exit status " + result.exitCode() + ")." + (output.isEmpty() ? "" : "\n" + output)); } - return new Loaded(document(model, "model"), document(dependencies, "dependency tree")); + return new Loaded(document(model, "model"), document(dependencies, "dependency tree"), + NativeSources.fromDocument(document(configuration, "native configuration sources"))); } finally { delete(work); } diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/NativeSources.java b/backend/src/main/java/io/github/litheidea/maven/backend/NativeSources.java new file mode 100644 index 0000000..b64f29a --- /dev/null +++ b/backend/src/main/java/io/github/litheidea/maven/backend/NativeSources.java @@ -0,0 +1,74 @@ +package io.github.litheidea.maven.backend; + +import io.github.litheidea.plugin.sdk.Json; +import io.github.litheidea.plugin.sdk.PluginError; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** Exact native inputs selected by Maven, without rediscovering CLI precedence. */ +final class NativeSources { + private static final int MAX_BYTES = 2 * 1024 * 1024; + + static List fromDocument(Map document) { + if (!"litheMavenNativeInputs".equals(document.get("format")) + || !(document.get("version") instanceof Number) + || ((Number) document.get("version")).doubleValue() != 1) { + throw new PluginError("maven.invalidOutput", "Maven did not export its selected configuration sources."); + } + Object input = document.get("sources"); + if (!(input instanceof List) || ((List) input).isEmpty() || ((List) input).size() > 8) { + throw new PluginError("maven.invalidOutput", "Maven configuration sources are invalid."); + } + List result = new ArrayList<>(); + for (Object value : (List) input) { + Map source = Json.object(value); + Map identity = new LinkedHashMap<>(); + identity.put("uri", source.get("uri")); + identity.put("revision", source.get("revision")); + result.add(identity); + } + if (!current(result)) throw changed(); + return result; + } + + static boolean current(Object input) { + if (!(input instanceof List) || ((List) input).isEmpty() || ((List) input).size() > 8) return false; + try { + for (Object value : (List) input) { + Map source = Json.object(value); + if (!(source.get("uri") instanceof String) || !(source.get("revision") instanceof String)) return false; + URI uri = new URI((String) source.get("uri")); + if (!"file".equals(uri.getScheme()) || uri.getQuery() != null || uri.getFragment() != null + || uri.getUserInfo() != null) return false; + Path path = Paths.get(uri); + String revision = (String) source.get("revision"); + if ("missing".equals(revision)) { + if (Files.exists(path)) return false; + } else { + if (!revision.matches("sha256:[0-9a-f]{64}") || !Files.isRegularFile(path) + || Files.size(path) > MAX_BYTES) return false; + byte[] bytes = Files.readAllBytes(path); + if (bytes.length > MAX_BYTES || !revision.equals("sha256:" + hex(MessageDigest.getInstance("SHA-256").digest(bytes)))) return false; + } + } + return true; + } catch (Exception error) { return false; } + } + + static PluginError changed() { + return new PluginError("maven.configurationChanged", "Maven configuration changed while the project was read. Reload the project."); + } + + private static String hex(byte[] bytes) { + StringBuilder result = new StringBuilder(bytes.length * 2); + for (byte value : bytes) result.append(String.format("%02x", value & 0xff)); + return result.toString(); + } +} diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/Snapshots.java b/backend/src/main/java/io/github/litheidea/maven/backend/Snapshots.java index b818be7..b378bbe 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/Snapshots.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/Snapshots.java @@ -18,7 +18,7 @@ * fingerprint of the inputs it was computed from. * *
    - * { "snapshotVersion": 1,
    + * { "snapshotVersion": 2,
      *   "roots": { "/abs/root": { "fingerprint", "savedAt", "model", "dependencies" } } }
      * 
    * @@ -28,7 +28,7 @@ */ final class Snapshots { static final String KEY = "maven-snapshot"; - static final int VERSION = 1; + static final int VERSION = 2; /** Roots kept per workspace; the least recently saved go first. */ private static final int MAX_ROOTS = 32; @@ -44,10 +44,12 @@ final class Snapshots { synchronized MavenRuns.Loaded read(Path root, String fingerprint) { Map entry = Json.object(roots(store.read(KEY, null)).get(root.toString())); if (!fingerprint.equals(entry.get("fingerprint")) - || !(entry.get("model") instanceof Map) || !(entry.get("dependencies") instanceof Map)) { + || !(entry.get("model") instanceof Map) || !(entry.get("dependencies") instanceof Map) + || !NativeSources.current(entry.get("nativeSources"))) { return null; } - return new MavenRuns.Loaded(Json.object(entry.get("model")), Json.object(entry.get("dependencies"))); + return new MavenRuns.Loaded(Json.object(entry.get("model")), Json.object(entry.get("dependencies")), + new ArrayList<>((List) entry.get("nativeSources"))); } synchronized void write(Path root, String fingerprint, MavenRuns.Loaded loaded) { @@ -57,6 +59,7 @@ synchronized void write(Path root, String fingerprint, MavenRuns.Loaded loaded) entry.put("savedAt", System.currentTimeMillis()); entry.put("model", loaded.model()); entry.put("dependencies", loaded.dependencies()); + entry.put("nativeSources", loaded.nativeSources()); roots.remove(root.toString()); roots.put(root.toString(), entry); prune(roots); 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..90f738d 100644 --- a/extension/src/main/java/io/github/litheidea/maven/LitheLifecycleParticipant.java +++ b/extension/src/main/java/io/github/litheidea/maven/LitheLifecycleParticipant.java @@ -36,15 +36,35 @@ public final class LitheLifecycleParticipant extends AbstractMavenLifecycleParti private final MavenPluginManager pluginManager; private final PluginVersionResolver versionResolver; private final ProjectDependenciesResolver dependenciesResolver; + private final NativeSettingsEvents settingsEvents; @Inject public LitheLifecycleParticipant( MavenPluginManager pluginManager, PluginVersionResolver versionResolver, - ProjectDependenciesResolver dependenciesResolver) { + ProjectDependenciesResolver dependenciesResolver, + NativeSettingsEvents settingsEvents) { this.pluginManager = pluginManager; this.versionResolver = versionResolver; this.dependenciesResolver = dependenciesResolver; + this.settingsEvents = settingsEvents; + } + + /** Settings-only probe exits before reactor reading or lifecycle goals. */ + @Override + public void afterSessionStart(MavenSession session) throws MavenExecutionException { + String output = property(session, "lithe.configurationOutput"); + String context = property(session, "lithe.configurationContextOutput"); + if (output == null && context == null) return; + try { + String document = Json.write(output == null + ? SettingsExport.context(session, settingsEvents.capture()) + : SettingsExport.document(session, settingsEvents.capture())); + write(output == null ? context : output, document); + } catch (Exception error) { + throw new MavenExecutionException("Lithe could not inspect Maven configuration.", error); + } + if (output != null) throw new MavenExecutionException("Lithe configuration inspection completed.", (Throwable) null); } @Override diff --git a/extension/src/main/java/io/github/litheidea/maven/NativeSettingsEvents.java b/extension/src/main/java/io/github/litheidea/maven/NativeSettingsEvents.java new file mode 100644 index 0000000..8211ae3 --- /dev/null +++ b/extension/src/main/java/io/github/litheidea/maven/NativeSettingsEvents.java @@ -0,0 +1,46 @@ +package io.github.litheidea.maven; + +import java.util.ArrayList; +import javax.inject.Named; +import javax.inject.Singleton; +import org.apache.maven.eventspy.AbstractEventSpy; +import org.apache.maven.settings.building.SettingsBuildingRequest; +import org.apache.maven.settings.building.SettingsBuildingResult; + +/** + * Observes Maven's original settings build before CLI options populate the + * execution request. Captures exact source revisions rather than re-running + * a settings builder or deriving a second configuration precedence. + */ +@Named("lithe-native-settings") +@Singleton +public final class NativeSettingsEvents extends AbstractEventSpy { + private SettingsExport.Capture capture; + private Exception failure; + + @Override + public void onEvent(Object event) { + try { + if (event instanceof SettingsBuildingRequest) { + SettingsBuildingRequest request = (SettingsBuildingRequest) event; + if (!requested(request)) return; + capture = new SettingsExport.Capture(request); + } else if (event instanceof SettingsBuildingResult && capture != null) { + capture.effectiveProfiles = new ArrayList<>( + ((SettingsBuildingResult) event).getEffectiveSettings().getActiveProfiles()); + } + } catch (Exception error) { failure = error; } + } + + SettingsExport.Capture capture() throws Exception { + if (failure != null) throw failure; + return capture; + } + + private static boolean requested(SettingsBuildingRequest request) { + for (String key : new String[] {"lithe.configurationOutput", "lithe.configurationContextOutput"}) { + if (request.getUserProperties().containsKey(key) || request.getSystemProperties().containsKey(key)) return true; + } + return false; + } +} diff --git a/extension/src/main/java/io/github/litheidea/maven/SettingsExport.java b/extension/src/main/java/io/github/litheidea/maven/SettingsExport.java new file mode 100644 index 0000000..1473a7a --- /dev/null +++ b/extension/src/main/java/io/github/litheidea/maven/SettingsExport.java @@ -0,0 +1,215 @@ +package io.github.litheidea.maven; + +import java.io.File; +import java.io.StringReader; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamReader; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.settings.Settings; +import org.apache.maven.settings.building.SettingsBuildingRequest; +import org.apache.maven.settings.io.xpp3.SettingsXpp3Reader; + +/** + * Non-sensitive configuration facts from the selected Maven's own session. + * This runs before projects are read: no second settings precedence, reactor, + * profile activation engine, or dependency importer is maintained by Lithe. + * Full native documents and credentials never enter the exported JSON. + */ +final class SettingsExport { + private static final int MAX_BYTES = 2 * 1024 * 1024; + private static final String SETTINGS_NAMESPACE = "http://maven.apache.org/SETTINGS/1.0.0"; + + static final class Capture { + final NativeSource installation; + final NativeSource user; + List effectiveProfiles; + + Capture(SettingsBuildingRequest request) throws Exception { + if (request.getGlobalSettingsSource() != null || request.getUserSettingsSource() != null) { + throw new IllegalStateException("Non-file Maven settings sources cannot be edited."); + } + installation = read("installation", request.getGlobalSettingsFile(), false); + // A source shared with installation settings remains read-only. + boolean userWritable = !canonical(request.getUserSettingsFile()).equals(installation.canonicalPath); + user = read("user", request.getUserSettingsFile(), userWritable); + } + } + + static Map document(MavenSession session, Capture capture) throws Exception { + if (capture == null || capture.effectiveProfiles == null + || !capture.installation.current(session.getRequest().getGlobalSettingsFile()) + || !capture.user.current(session.getRequest().getUserSettingsFile())) { + throw new IllegalStateException("Maven configuration changed during inspection; retry with current files."); + } + NativeSource installation = capture.installation; + NativeSource user = capture.user; + String repository = session.getRequest().getLocalRepositoryPath().getAbsolutePath(); + List profiles = new ArrayList<>(session.getRequest().getActiveProfiles()); + String repositoryOrigin = session.getUserProperties().containsKey("maven.repo.local") + || session.getSystemProperties().containsKey("maven.repo.local") ? "commandLine" + : present(user.settings.getLocalRepository()) ? "user" + : present(installation.settings.getLocalRepository()) ? "installation" : "default"; + // The original SettingsBuildingResult predates CLI population; the + // session's SettingsAdapter already includes command-line overrides. + String profileOrigin = profiles.equals(capture.effectiveProfiles) ? "settings" : "commandLine"; + List sources = new ArrayList<>(); + sources.add(installation.export(repository, profiles, repositoryOrigin, profileOrigin)); + sources.add(user.export(repository, profiles, repositoryOrigin, profileOrigin)); + Map result = new LinkedHashMap<>(); + result.put("format", "litheBuildConfiguration"); result.put("version", 1); result.put("sources", sources); + return result; + } + + static Map context(MavenSession session, Capture capture) throws Exception { + Map configuration = document(session, capture); + List inputs = new ArrayList<>(); + for (Object value : (List) configuration.get("sources")) { + @SuppressWarnings("unchecked") Map source = (Map) value; + Map identity = new LinkedHashMap<>(); + identity.put("uri", source.get("uri")); identity.put("revision", source.get("revision")); + inputs.add(identity); + } + for (File file : new File[] {session.getRequest().getGlobalToolchainsFile(), session.getRequest().getUserToolchainsFile()}) { + if (file == null) continue; + Path path = file.toPath().toAbsolutePath().normalize(); + String revision = "missing"; + if (Files.exists(path)) { + if (!Files.isRegularFile(path) || Files.size(path) > MAX_BYTES) throw new IllegalStateException("Maven toolchains are not a bounded regular file."); + byte[] bytes = Files.readAllBytes(path); + if (bytes.length > MAX_BYTES) throw new IllegalStateException("Maven toolchains exceed the size limit."); + revision = "sha256:" + hex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + Map identity = new LinkedHashMap<>(); + identity.put("uri", path.toUri().toString()); identity.put("revision", revision); inputs.add(identity); + } + Map result = new LinkedHashMap<>(); + result.put("format", "litheMavenNativeInputs"); result.put("version", 1); result.put("sources", inputs); + return result; + } + + private static Path canonical(File file) throws Exception { + if (file == null) throw new IllegalStateException("Maven did not select a native settings file."); + Path path = file.toPath().toAbsolutePath().normalize(); + return Files.exists(path) ? path.toRealPath() : path; + } + + private static NativeSource read(String id, File file, boolean writable) throws Exception { + if (file == null) throw new IllegalStateException("Maven did not select its " + id + " settings source."); + Path path = file.toPath().toAbsolutePath().normalize(); + if (!Files.exists(path)) return new NativeSource(id, path, path, "missing", writable && writableParent(path), + new Settings(), false, "settings", SETTINGS_NAMESPACE); + Path canonicalPath = path.toRealPath(); + if (!Files.isRegularFile(path) || Files.size(path) > MAX_BYTES) { + throw new IllegalStateException("Maven settings are not a bounded regular file."); + } + byte[] bytes = Files.readAllBytes(path); + if (bytes.length > MAX_BYTES) throw new IllegalStateException("Maven settings exceed the size limit."); + String xml = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(bytes)).toString(); + // The owning Maven's generated reader supplies raw values. StAX only + // preserves absence/root metadata needed by the generic native editor. + XMLInputFactory factory = XMLInputFactory.newFactory(); + factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); + factory.setProperty("javax.xml.stream.isSupportingExternalEntities", false); + XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(xml)); + String rootName = null; + String rootNamespace = ""; + boolean activeProfiles = false; + int depth = 0; + try { + while (reader.hasNext()) { + int event = reader.next(); + if (event == XMLStreamConstants.START_ELEMENT) { + if (depth == 0) { + rootName = reader.getLocalName(); + rootNamespace = reader.getNamespaceURI() == null ? "" : reader.getNamespaceURI(); + } else if (depth == 1 && "activeProfiles".equals(reader.getLocalName()) + && rootNamespace.equals(reader.getNamespaceURI() == null ? "" : reader.getNamespaceURI())) { + activeProfiles = true; + } + if (++depth > 64) throw new IllegalStateException("Maven settings are too deeply nested."); + } else if (event == XMLStreamConstants.END_ELEMENT) depth--; + else if (event == XMLStreamConstants.DTD) throw new IllegalStateException("Maven settings DTDs cannot be edited."); + } + } finally { reader.close(); } + Settings settings = new SettingsXpp3Reader().read(new StringReader(xml)); + return new NativeSource(id, path, canonicalPath, "sha256:" + hex(MessageDigest.getInstance("SHA-256").digest(bytes)), + writable && Files.isWritable(path), settings, activeProfiles, rootName, rootNamespace); + } + + private static boolean present(String value) { return value != null && !value.trim().isEmpty(); } + + private static boolean writableParent(Path path) { + Path parent = path.getParent(); + while (parent != null && !Files.exists(parent)) parent = parent.getParent(); + return parent != null && Files.isDirectory(parent) && Files.isWritable(parent); + } + + private static String hex(byte[] bytes) { + StringBuilder result = new StringBuilder(bytes.length * 2); + for (byte value : bytes) result.append(String.format("%02x", value & 0xff)); + return result.toString(); + } + + private static final class NativeSource { + final String id; + final Path path; + final Path canonicalPath; + final String revision; + final boolean writable; + final Settings settings; + final boolean activeProfiles; + final String rootName; + final String rootNamespace; + + NativeSource(String id, Path path, Path canonicalPath, String revision, boolean writable, Settings settings, + boolean activeProfiles, String rootName, String rootNamespace) { + this.id = id; this.path = path; this.canonicalPath = canonicalPath; this.revision = revision; this.writable = writable; + this.settings = settings; this.activeProfiles = activeProfiles; + this.rootName = rootName; this.rootNamespace = rootNamespace; + } + + boolean current(File selected) throws Exception { + if (!canonicalPath.equals(canonical(selected))) return false; + if ("missing".equals(revision)) return !Files.exists(path); + if (!Files.isRegularFile(path) || Files.size(path) > MAX_BYTES) return false; + byte[] bytes = Files.readAllBytes(path); + return bytes.length <= MAX_BYTES && revision.equals("sha256:" + hex(MessageDigest.getInstance("SHA-256").digest(bytes))); + } + + Map export(String repository, List profiles, String repositoryOrigin, String profileOrigin) { + Map source = new LinkedHashMap<>(); + source.put("id", id); source.put("scope", id); source.put("uri", path.toUri().toString()); + source.put("revision", revision); source.put("writable", writable); + Map root = new LinkedHashMap<>(); root.put("name", rootName); root.put("namespace", rootNamespace); + source.put("rootElement", root); + List fields = new ArrayList<>(); + fields.add(field("localRepository", "directory", settings.getLocalRepository(), repository, repositoryOrigin, null)); + fields.add(field("activeProfiles", "stringList", activeProfiles ? settings.getActiveProfiles() : null, + profiles, profileOrigin, "activeProfile")); + source.put("fields", fields); + return source; + } + + private Map field(String name, String kind, Object value, Object effective, String origin, String item) { + Map field = new LinkedHashMap<>(); + field.put("id", name); field.put("kind", kind); field.put("value", value); + field.put("effectiveValue", effective); field.put("effectiveSource", origin); + field.put("path", Collections.singletonList(name)); + if (item != null) field.put("itemElement", item); + return field; + } + } +} diff --git a/io.github.lithe-idea.maven-build/plugin.json b/io.github.lithe-idea.maven-build/plugin.json index 02f4bd2..3fd4371 100644 --- a/io.github.lithe-idea.maven-build/plugin.json +++ b/io.github.lithe-idea.maven-build/plugin.json @@ -4,7 +4,7 @@ "displayName": "Maven", "version": "0.1.1", "pluginAPIVersion": 3, - "requires": { "buildProviders": 3, "buildModelInputs": 1, "buildSystems": 1, "serverProcess": 1 }, + "requires": { "buildProviders": 7, "buildModelInputs": 1, "buildSystems": 1, "serverProcess": 1 }, "vendor": { "id": "io.github.lithe-idea", "displayName": "Lithe Community", @@ -92,6 +92,7 @@ "mayUseNetwork": true }, "model": { "source": "provider" }, + "configuration": { "source": "provider" }, "modelSharing": { "options": ["profiles", "offline", "skipTests"] }, "tasks": [ { diff --git a/scripts/test-backend.mjs b/scripts/test-backend.mjs index 19d8aa8..26a15a3 100644 --- a/scripts/test-backend.mjs +++ b/scripts/test-backend.mjs @@ -119,7 +119,7 @@ async function test() { assert.equal(runs().length, 1, "dependencies come from the same run"); const snapshot = JSON.parse(readFileSync(snapshotFile, "utf8")).value; - assert.equal(snapshot.snapshotVersion, 1); + assert.equal(snapshot.snapshotVersion, 2); assert.deepEqual(Object.keys(snapshot.roots), [root]); }); @@ -161,6 +161,21 @@ async function test() { assert.equal((await client.request("lithe/build/model", params({ options: { offline: true } }))).fakeRun, 5); }); + await check("a native settings source selected by Maven invalidates cache even outside CLI guessing", async () => { + const selected = join(root, ".mvn", "selected settings.xml"); + const before = runs().length; + writeFileSync(selected, ""); + await client.request("lithe/build/model", params({ options: { offline: true } })); + assert.equal(runs().length, before + 1); + await client.request("lithe/build/model", params({ options: { offline: true } })); + assert.equal(runs().length, before + 1, "unchanged selected source still permits cache reuse"); + rmSync(selected); + await client.request("lithe/build/model", params({ options: { offline: true } })); + assert.equal(runs().length, before + 2, "removing an explicitly selected native source invalidates its snapshot"); + const entry = JSON.parse(readFileSync(snapshotFile, "utf8")).value.roots[root]; + assert.equal(entry.nativeSources[0].revision, "missing"); + }); + await check("concurrent requests share one Maven run", async () => { touch("core/pom.xml", "concurrent"); const gate = join(scratch, "gate-concurrent"); @@ -276,12 +291,12 @@ async function test() { assert.equal(runs().length, before + 1); const stored = JSON.parse(readFileSync(snapshotFile, "utf8")); - stored.value.snapshotVersion = 2; + stored.value.snapshotVersion = 99; writeFileSync(snapshotFile, JSON.stringify(stored)); before = runs().length; await client.request("lithe/build/model", params()); assert.equal(runs().length, before + 1); - assert.equal(JSON.parse(readFileSync(snapshotFile, "utf8")).value.snapshotVersion, 1, "the next run rewrites it"); + assert.equal(JSON.parse(readFileSync(snapshotFile, "utf8")).value.snapshotVersion, 2, "the next run rewrites it"); }); await check("without tool.executable the backend uses the project's Maven Wrapper", async () => { diff --git a/scripts/test-configuration.mjs b/scripts/test-configuration.mjs new file mode 100644 index 0000000..6dd191e --- /dev/null +++ b/scripts/test-configuration.mjs @@ -0,0 +1,119 @@ +#!/usr/bin/env node +// Explicit real-tool integration. Every native settings file and HOME is isolated. +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { BackendClient, bounded } from './backend-client.mjs'; +import { bundleManifest } from './bundle-manifest.mjs'; +import { coreCommand } from './core-client.mjs'; +import { withInterrupts } from './process.mjs'; +import { createReport } from './report.mjs'; + +const pkg = resolve(process.env.LITHE_TEST_PACKAGE ?? resolve('dist/package', 'io.github.lithe-idea.maven-build')); +const java = process.env.LITHE_TEST_JAVA; +const maven = process.env.LITHE_TEST_MAVEN; +assert.ok(java && maven, 'Set explicit LITHE_TEST_JAVA and LITHE_TEST_MAVEN paths.'); +const manifest = JSON.parse(readFileSync(join(pkg, 'plugin.json'), 'utf8')); +const before = bundleManifest(pkg); +const scratch = realpathSync(mkdtempSync(join(tmpdir(), 'lithe-maven-configuration-'))); +const workspace = join(scratch, 'workspace'); +const root = join(workspace, 'nested'); +const home = join(scratch, 'home'); +const user = join(scratch, 'user settings.xml'); +const installation = join(scratch, 'global.xml'); +const state = join(scratch, 'state'); +const repository = join(scratch, 'global-repository'); +const report = createReport('native-maven-configuration'); +const clients = new Set(); +const hash = bytes => 'sha256:' + createHash('sha256').update(bytes).digest('hex'); +const request = options => ({ buildSystemID: 'maven', root: 'nested', options, + optionArguments: [], environment: {}, tool: { executable: maven } }); +const payload = value => ({ manifest, buildSystemID: 'maven', request: value }); +async function start(version = 7) { + const client = new BackendClient({ java, jar: join(pkg, 'lib/lithe-maven-backend.jar'), state, + javaOptions: [`-Duser.home=${home}`], + env: { ...process.env, MAVEN_OPTS: `-Duser.home=${home}`, JAVA_HOME: resolve(java, '../..') } }); + clients.add(client); + assert.equal((await client.initialize(workspace, [version])).capabilities.experimental.litheBuild.version, version); + return client; +} + +await withInterrupts(async signal => { + const stop = () => { for (const client of clients) client.kill(); }; + signal.addEventListener('abort', stop, { once: true }); + try { + mkdirSync(join(root, '.mvn'), { recursive: true }); + mkdirSync(home); + // An invalid POM proves that inspection exits before reactor import. + writeFileSync(join(root, 'pom.xml'), '${repository}`); + writeFileSync(user, 'cifixturefixture-secret-sentinel'); + const sourcesBefore = [readFileSync(user), readFileSync(installation)]; + const client = await start(); + let snapshot; + await report.step('selected Maven exports native sources before reading a broken POM', async () => { + const plan = coreCommand('build.configurationPlan', payload({ root: 'nested', options: { settingsFile: user }, tool: { executable: maven } })).plan; + assert.equal(plan.provider.method, 'lithe/build/configuration'); + const raw = await client.request(plan.provider.method, plan.provider.params); + snapshot = coreCommand('build.decodeConfiguration', payload({ result: raw })).configuration; + const nativeUser = snapshot.sources.find(source => source.id === 'user'); + const global = snapshot.sources.find(source => source.id === 'installation'); + assert.equal(nativeUser.fields.find(field => field.id === 'localRepository').value, null); + assert.equal(nativeUser.fields.find(field => field.id === 'localRepository').effectiveValue, repository); + assert.equal(global.writable, false); + assert.equal(nativeUser.revision, hash(sourcesBefore[0])); + assert.ok(!JSON.stringify(snapshot).includes('fixture-secret-sentinel')); + assert.deepEqual([readFileSync(user), readFileSync(installation)], sourcesBefore); + assert.equal(existsSync(join(root, 'target')), false); + }); + await report.step('Core edits the approved native field and Maven re-reads the saved source', async () => { + const source = snapshot.sources.find(source => source.id === 'user'); + const replacement = coreCommand('build.editConfigurationDocument', payload({ snapshot, + edits: { sourceID: 'user', revision: source.revision, values: { localRepository: join(scratch, 'saved-repository') } }, + document: sourcesBefore[0].toString('utf8') })).edit; + assert.equal(hash(readFileSync(user)), source.revision); + writeFileSync(user, replacement.document); + assert.ok(replacement.document.includes('')); + assert.ok(replacement.document.includes('fixture-secret-sentinel')); + const updated = await client.request('lithe/build/configuration', request({ settingsFile: user })); + const field = updated.sources.find(source => source.id === 'user').fields.find(field => field.id === 'localRepository'); + assert.equal(field.value, join(scratch, 'saved-repository')); + assert.equal(field.effectiveValue, field.value); + assert.ok(!JSON.stringify(updated).includes('fixture-secret-sentinel')); + assert.deepEqual(readFileSync(installation), sourcesBefore[1]); + }); + await report.step('effective CLI overrides remain distinct from the editable native value', async () => { + const updated = await client.request('lithe/build/configuration', request({ settingsFile: user, + localRepository: join(scratch, 'cli-repository'), profiles: ['cli-profile'] })); + const fields = updated.sources.find(source => source.id === 'user').fields; + const repositoryField = fields.find(field => field.id === 'localRepository'); + assert.equal(repositoryField.value, join(scratch, 'saved-repository')); + assert.equal(repositoryField.effectiveValue, join(scratch, 'cli-repository')); + assert.equal(repositoryField.effectiveSource, 'commandLine'); + assert.deepEqual(fields.find(field => field.id === 'activeProfiles').value, ['ci']); + assert.ok(fields.find(field => field.id === 'activeProfiles').effectiveValue.includes('cli-profile')); + }); + await report.step('older wire versions refuse configuration instead of invoking another method', async () => { + const old = await start(6); + const response = await old.send('lithe/build/configuration', request({ settingsFile: user })).response; + assert.equal(response.error.code, -32601); + await old.close(); clients.delete(old); + }); + await report.step('shutdown cleans probe state and keeps the installed package unchanged', async () => { + await client.close(); clients.delete(client); + assert.deepEqual(bundleManifest(pkg), before); + const entries = await import('node:fs/promises').then(fs => fs.readdir(state)); + assert.equal(entries.some(name => name.startsWith('configuration-')), false); + }); + } finally { + signal.removeEventListener('abort', stop); + for (const client of clients) { + try { await client.close(); } + catch { client.kill(); await bounded(client.exited, 'configuration backend cleanup'); } + } + rmSync(scratch, { recursive: true, force: true }); + } +}).catch(error => { report.failure('native configuration integration', error); process.exitCode = 1; }).finally(() => report.write()); diff --git a/scripts/test-native-core.mjs b/scripts/test-native-core.mjs index f8e8a01..eff3e90 100644 --- a/scripts/test-native-core.mjs +++ b/scripts/test-native-core.mjs @@ -89,6 +89,7 @@ await withInterrupts(async (signal) => { consumer.id = 'org.example.maven-input-consumer'; consumer.requires.buildProviders = 6; delete consumer.buildSystems[0].modelSharing; + delete consumer.buildSystems[0].configuration; consumer.buildSystems[0].modelInputs = [{ pluginID: id, buildSystemID: 'maven' }]; const snapshot = coreCommand('build.resolveModelInputs', { manifest: consumer, buildSystemID: 'maven', request: { revision: 11, sources: [{ manifest, instances: [{ buildSystemID: 'maven', root, state: 'ready', model, options }] }] } }).modelInputs; diff --git a/scripts/test.mjs b/scripts/test.mjs index e66223b..31a8ccf 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -150,7 +150,7 @@ async function test(signal) { await check("one Maven model run serves every tree and leaves a reusable snapshot", async () => { const saved = JSON.parse(readFileSync(join(scratch, "state", "maven-snapshot.json"), "utf8")).value; - assert.equal(saved.snapshotVersion, 1); + assert.equal(saved.snapshotVersion, 2); assert.deepEqual(saved.roots[root].model, model); // The provider remains alive for the native task/test requests below. }); diff --git a/test/fixtures/fake-maven-backend.mjs b/test/fixtures/fake-maven-backend.mjs index 7f2221e..49de1b0 100644 --- a/test/fixtures/fake-maven-backend.mjs +++ b/test/fixtures/fake-maven-backend.mjs @@ -7,6 +7,8 @@ // { "exit": } print an [ERROR] line and exit with the status // { "output": "missing" | "malformed" } succeed without the documents, or with invalid JSON import { spawn } from "node:child_process"; +import { createHash } from "node:crypto"; +import { pathToFileURL } from "node:url"; import { appendFileSync, existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs"; import { join } from "node:path"; @@ -56,6 +58,13 @@ if (!exporting) { process.exit(0); } if (!modelOutput || !dependenciesOutput) throw new Error("expected both output properties"); +const configurationOutput = value("lithe.configurationContextOutput"); +if (!configurationOutput) throw new Error("expected the native configuration context"); +const nativeSource = process.env.FAKE_MAVEN_NATIVE_SOURCE ?? join(process.cwd(), ".mvn", "selected settings.xml"); +writeFileSync(configurationOutput, JSON.stringify({ format: "litheMavenNativeInputs", version: 1, + sources: [{ uri: pathToFileURL(nativeSource).href, + revision: existsSync(nativeSource) ? "sha256:" + createHash("sha256").update(readFileSync(nativeSource)).digest("hex") : "missing" }] })); + if (control.output === "missing") process.exit(0); if (control.output === "malformed") { writeFileSync(modelOutput, "{invalid JSON"); From 080a6bb858f309d47fa83901b4f8679da19f97ae Mon Sep 17 00:00:00 2001 From: wgw Date: Wed, 28 Oct 2026 15:50:30 +0800 Subject: [PATCH 02/24] feat(maven): scope build options to each reactor root --- README.md | 2 ++ io.github.lithe-idea.maven-build/plugin.json | 12 ++++++------ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 2b50d11..b665cb9 100644 --- a/README.md +++ b/README.md @@ -245,3 +245,5 @@ LITHE_CORE_LIBRARY=/absolute/liblithe_core.dylib node scripts/test-configuration `workflow_dispatch` 的开发 SDK lane 可额外指定 40 位 `core-revision`,构建该宿主 Core 后运行 原生配置及真实构建/精确测试的集成;SDK、Core 都按明确提交选取,不修改正式锁定文件。 + +构建选项要求 `buildSystems: 3`,按每个检测到的 reactor 根独立保存;Profiles、settings 文件、仓库、离线和跳过测试不再共享同一个工作区值。宿主升级作用域时须先复制并读回旧 Build 选项,保留已有实例覆盖和显式空选择后再删除旧表示。旧 MavenService 的数据迁移及消费者删除仍属于阶段 D 后续验收,不由这个清单变更代替。 diff --git a/io.github.lithe-idea.maven-build/plugin.json b/io.github.lithe-idea.maven-build/plugin.json index 3fd4371..b34827c 100644 --- a/io.github.lithe-idea.maven-build/plugin.json +++ b/io.github.lithe-idea.maven-build/plugin.json @@ -4,7 +4,7 @@ "displayName": "Maven", "version": "0.1.1", "pluginAPIVersion": 3, - "requires": { "buildProviders": 7, "buildModelInputs": 1, "buildSystems": 1, "serverProcess": 1 }, + "requires": { "buildProviders": 7, "buildModelInputs": 1, "buildSystems": 3, "serverProcess": 1 }, "vendor": { "id": "io.github.lithe-idea", "displayName": "Lithe Community", @@ -50,23 +50,23 @@ { "id": "profiles", "displayName": "Profiles", - "kind": "multiSelect", + "kind": "multiSelect", "scope": "instance", "choicesFromModel": true, "allowCustom": true, "presentation": "tree", "arguments": ["-P", "${value}"] }, - { "id": "settingsFile", "displayName": "Settings File", "kind": "file", "arguments": ["-s", "${value}"] }, + { "id": "settingsFile", "displayName": "Settings File", "kind": "file", "scope": "instance", "arguments": ["-s", "${value}"] }, { "id": "localRepository", "displayName": "Local Repository", - "kind": "directory", + "kind": "directory", "scope": "instance", "arguments": ["-Dmaven.repo.local=${value}"] }, { "id": "offline", "displayName": "Offline", - "kind": "boolean", + "kind": "boolean", "scope": "instance", "presentation": "toolbar", "icon": { "path": "icons/offline.svg" }, "arguments": ["-o"] @@ -74,7 +74,7 @@ { "id": "skipTests", "displayName": "Skip Tests", - "kind": "boolean", + "kind": "boolean", "scope": "instance", "presentation": "toolbar", "icon": { "path": "icons/skipTests.svg" }, "arguments": ["-DskipTests"] From 5d0e6e38d4c137d4fe5fcecd242cbdb8f4a01fbd Mon Sep 17 00:00:00 2001 From: wgw Date: Wed, 28 Oct 2026 16:37:41 +0800 Subject: [PATCH 03/24] fix(maven): honor canonical toolchains and isolate settings probes --- README.md | 4 +++ .../maven/LitheLifecycleParticipant.java | 8 ++--- .../litheidea/maven/NativeSettingsEvents.java | 33 +++++++++++++++++++ .../litheidea/maven/SettingsExport.java | 17 ++++++---- io.github.lithe-idea.maven-build/plugin.json | 24 +++----------- scripts/test-configuration.mjs | 3 ++ 6 files changed, 58 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index b665cb9..bf238df 100644 --- a/README.md +++ b/README.md @@ -247,3 +247,7 @@ LITHE_CORE_LIBRARY=/absolute/liblithe_core.dylib node scripts/test-configuration 原生配置及真实构建/精确测试的集成;SDK、Core 都按明确提交选取,不修改正式锁定文件。 构建选项要求 `buildSystems: 3`,按每个检测到的 reactor 根独立保存;Profiles、settings 文件、仓库、离线和跳过测试不再共享同一个工作区值。宿主升级作用域时须先复制并读回旧 Build 选项,保留已有实例覆盖和显式空选择后再删除旧表示。旧 MavenService 的数据迁移及消费者删除仍属于阶段 D 后续验收,不由这个清单变更代替。 + +工具解析要求 `executableResolution: 2`,通过宿主已有 `project-maven` / `project-maven-jdk` 注册表读取 `.lithe/run/local.json` 的当前实例选择,复用 Run 的配置链。宿主把选中的 Maven 路径以及有限的运行时环境(含 JAVA_HOME/PATH)交给 Provider;Provider 进程自身的 JDK 不等于 Maven 所用的 JDK。显式选择失败不能独立改用其他 Maven;被动导入不执行 Wrapper 或探测版本。 + +只读配置探针观察 Maven 官方完成默认值填充后的 `MavenExecutionRequest`:先保留所选 settings、Profiles 和仓库事实,再将这次探针自己的仓库管理器隔离到临时 `configuration-*/repository`,在工程导入前退出。仅在 `afterSessionStart` 导出会过晚,可能已经创建用户仓库。读取、保存后的回读与 CLI 覆盖均不得创建实际仓库;临时目录统一清理。真实模型、依赖和构建使用原仓库,不采用此探针隔离。 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 90f738d..a803802 100644 --- a/extension/src/main/java/io/github/litheidea/maven/LitheLifecycleParticipant.java +++ b/extension/src/main/java/io/github/litheidea/maven/LitheLifecycleParticipant.java @@ -57,10 +57,8 @@ public void afterSessionStart(MavenSession session) throws MavenExecutionExcepti String context = property(session, "lithe.configurationContextOutput"); if (output == null && context == null) return; try { - String document = Json.write(output == null - ? SettingsExport.context(session, settingsEvents.capture()) - : SettingsExport.document(session, settingsEvents.capture())); - write(output == null ? context : output, document); + if (output != null) settingsEvents.requireConfigurationExported(); + else write(context, Json.write(SettingsExport.context(session, settingsEvents.capture()))); } catch (Exception error) { throw new MavenExecutionException("Lithe could not inspect Maven configuration.", error); } @@ -89,7 +87,7 @@ private static String property(MavenSession session, String key) { return value == null || value.trim().isEmpty() ? null : value.trim(); } - private static void write(String output, String json) throws MavenExecutionException { + static void write(String output, String json) throws MavenExecutionException { Path path = Paths.get(output); try { Files.write(path, json.getBytes(StandardCharsets.UTF_8)); diff --git a/extension/src/main/java/io/github/litheidea/maven/NativeSettingsEvents.java b/extension/src/main/java/io/github/litheidea/maven/NativeSettingsEvents.java index 8211ae3..89374bc 100644 --- a/extension/src/main/java/io/github/litheidea/maven/NativeSettingsEvents.java +++ b/extension/src/main/java/io/github/litheidea/maven/NativeSettingsEvents.java @@ -1,11 +1,17 @@ package io.github.litheidea.maven; import java.util.ArrayList; +import java.nio.file.Path; +import java.nio.file.Paths; +import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.apache.maven.eventspy.AbstractEventSpy; import org.apache.maven.settings.building.SettingsBuildingRequest; import org.apache.maven.settings.building.SettingsBuildingResult; +import org.apache.maven.execution.MavenExecutionRequest; +import org.apache.maven.execution.DefaultMavenExecutionRequest; +import org.apache.maven.bridge.MavenRepositorySystem; /** * Observes Maven's original settings build before CLI options populate the @@ -17,6 +23,11 @@ public final class NativeSettingsEvents extends AbstractEventSpy { private SettingsExport.Capture capture; private Exception failure; + private boolean configurationExported; + private final MavenRepositorySystem repositories; + + @Inject + public NativeSettingsEvents(MavenRepositorySystem repositories) { this.repositories = repositories; } @Override public void onEvent(Object event) { @@ -28,6 +39,23 @@ public void onEvent(Object event) { } else if (event instanceof SettingsBuildingResult && capture != null) { capture.effectiveProfiles = new ArrayList<>( ((SettingsBuildingResult) event).getEffectiveSettings().getActiveProfiles()); + } else if (event instanceof MavenExecutionRequest) { + MavenExecutionRequest request = (MavenExecutionRequest) event; + String output = request.getUserProperties().getProperty("lithe.configurationOutput", + request.getSystemProperties().getProperty("lithe.configurationOutput")); + if (output == null || output.trim().isEmpty()) return; + // MavenCli publishes this fully populated request before + // DefaultMaven creates its repository session. Preserve the + // upstream-selected facts, then isolate the probe's repository + // manager so merely reading settings cannot create the user's + // actual repository. Normal model/build requests never do this. + MavenExecutionRequest selected = DefaultMavenExecutionRequest.copy(request); + Path privateRepository = Paths.get(output).toAbsolutePath().getParent().resolve("repository"); + request.setLocalRepository(null); + request.setLocalRepositoryPath(privateRepository.toFile()); + request.setLocalRepository(repositories.createLocalRepository(request, privateRepository.toFile())); + LitheLifecycleParticipant.write(output, Json.write(SettingsExport.document(selected, capture()))); + configurationExported = true; } } catch (Exception error) { failure = error; } } @@ -37,6 +65,11 @@ SettingsExport.Capture capture() throws Exception { return capture; } + void requireConfigurationExported() throws Exception { + if (failure != null) throw failure; + if (!configurationExported) throw new IllegalStateException("Maven did not publish its populated execution request."); + } + private static boolean requested(SettingsBuildingRequest request) { for (String key : new String[] {"lithe.configurationOutput", "lithe.configurationContextOutput"}) { if (request.getUserProperties().containsKey(key) || request.getSystemProperties().containsKey(key)) return true; diff --git a/extension/src/main/java/io/github/litheidea/maven/SettingsExport.java b/extension/src/main/java/io/github/litheidea/maven/SettingsExport.java index 1473a7a..7f71307 100644 --- a/extension/src/main/java/io/github/litheidea/maven/SettingsExport.java +++ b/extension/src/main/java/io/github/litheidea/maven/SettingsExport.java @@ -17,6 +17,7 @@ import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamReader; import org.apache.maven.execution.MavenSession; +import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.settings.Settings; import org.apache.maven.settings.building.SettingsBuildingRequest; import org.apache.maven.settings.io.xpp3.SettingsXpp3Reader; @@ -48,17 +49,21 @@ static final class Capture { } static Map document(MavenSession session, Capture capture) throws Exception { + return document(session.getRequest(), capture); + } + + static Map document(MavenExecutionRequest request, Capture capture) throws Exception { if (capture == null || capture.effectiveProfiles == null - || !capture.installation.current(session.getRequest().getGlobalSettingsFile()) - || !capture.user.current(session.getRequest().getUserSettingsFile())) { + || !capture.installation.current(request.getGlobalSettingsFile()) + || !capture.user.current(request.getUserSettingsFile())) { throw new IllegalStateException("Maven configuration changed during inspection; retry with current files."); } NativeSource installation = capture.installation; NativeSource user = capture.user; - String repository = session.getRequest().getLocalRepositoryPath().getAbsolutePath(); - List profiles = new ArrayList<>(session.getRequest().getActiveProfiles()); - String repositoryOrigin = session.getUserProperties().containsKey("maven.repo.local") - || session.getSystemProperties().containsKey("maven.repo.local") ? "commandLine" + String repository = request.getLocalRepositoryPath().getAbsolutePath(); + List profiles = new ArrayList<>(request.getActiveProfiles()); + String repositoryOrigin = request.getUserProperties().containsKey("maven.repo.local") + || request.getSystemProperties().containsKey("maven.repo.local") ? "commandLine" : present(user.settings.getLocalRepository()) ? "user" : present(installation.settings.getLocalRepository()) ? "installation" : "default"; // The original SettingsBuildingResult predates CLI population; the diff --git a/io.github.lithe-idea.maven-build/plugin.json b/io.github.lithe-idea.maven-build/plugin.json index b34827c..de0c0ba 100644 --- a/io.github.lithe-idea.maven-build/plugin.json +++ b/io.github.lithe-idea.maven-build/plugin.json @@ -4,7 +4,7 @@ "displayName": "Maven", "version": "0.1.1", "pluginAPIVersion": 3, - "requires": { "buildProviders": 7, "buildModelInputs": 1, "buildSystems": 3, "serverProcess": 1 }, + "requires": { "buildProviders": 7, "buildModelInputs": 1, "buildSystems": 3, "executableResolution": 2, "serverProcess": 1 }, "vendor": { "id": "io.github.lithe-idea", "displayName": "Lithe Community", @@ -23,25 +23,9 @@ "nesting": "outermost" }, "invocation": { - "executables": [ - { - "kind": "projectFile", - "path": "mvnw", - "requires": [".mvn/wrapper/maven-wrapper.properties"], - "platforms": ["macos", "linux"] - }, - { - "kind": "projectFile", - "path": "mvnw.cmd", - "requires": [".mvn/wrapper/maven-wrapper.properties"], - "platforms": ["windows"] - }, - { "kind": "environment", "variable": "MAVEN_HOME", "path": "bin/mvn", "platforms": ["macos", "linux"] }, - { "kind": "environment", "variable": "MAVEN_HOME", "path": "bin/mvn.cmd", "platforms": ["windows"] }, - { "kind": "command", "command": "mvn" } - ], - "environmentInputs": ["MAVEN_HOME"], - "runtimeDependencies": [{ "id": "java", "minimumVersion": "8" }], + "executables": [{ "kind": "toolchain", "toolchainID": "project-maven" }], + "runtimeDependencies": [{ "id": "java", "minimumVersion": "8", + "executables": [{ "kind": "toolchain", "toolchainID": "project-maven-jdk" }] }], "globalArguments": [], "version": { "arguments": ["--version"], "pattern": "Apache Maven (\\d+\\.\\d+\\.\\d+)" }, "minimumVersion": "3.6.3" diff --git a/scripts/test-configuration.mjs b/scripts/test-configuration.mjs index 6dd191e..fe330fc 100644 --- a/scripts/test-configuration.mjs +++ b/scripts/test-configuration.mjs @@ -68,6 +68,7 @@ await withInterrupts(async signal => { assert.ok(!JSON.stringify(snapshot).includes('fixture-secret-sentinel')); assert.deepEqual([readFileSync(user), readFileSync(installation)], sourcesBefore); assert.equal(existsSync(join(root, 'target')), false); + assert.equal(existsSync(repository), false, 'Reading inherited configuration must not create its repository'); }); await report.step('Core edits the approved native field and Maven re-reads the saved source', async () => { const source = snapshot.sources.find(source => source.id === 'user'); @@ -84,6 +85,7 @@ await withInterrupts(async signal => { assert.equal(field.effectiveValue, field.value); assert.ok(!JSON.stringify(updated).includes('fixture-secret-sentinel')); assert.deepEqual(readFileSync(installation), sourcesBefore[1]); + assert.equal(existsSync(join(scratch, 'saved-repository')), false, 'Readback must not initialize the newly selected repository'); }); await report.step('effective CLI overrides remain distinct from the editable native value', async () => { const updated = await client.request('lithe/build/configuration', request({ settingsFile: user, @@ -95,6 +97,7 @@ await withInterrupts(async signal => { assert.equal(repositoryField.effectiveSource, 'commandLine'); assert.deepEqual(fields.find(field => field.id === 'activeProfiles').value, ['ci']); assert.ok(fields.find(field => field.id === 'activeProfiles').effectiveValue.includes('cli-profile')); + assert.equal(existsSync(join(scratch, 'cli-repository')), false, 'CLI overrides must remain facts without repository writes'); }); await report.step('older wire versions refuse configuration instead of invoking another method', async () => { const old = await start(6); From de08de897b4222d4b331f1411cb17e41f5474474 Mon Sep 17 00:00:00 2001 From: wgw Date: Wed, 28 Oct 2026 22:12:55 +0800 Subject: [PATCH 04/24] feat(maven): capture upstream test reports with each execution --- NOTICE | 5 + README.md | 8 +- backend/pom.xml | 11 + .../litheidea/maven/backend/MavenBackend.java | 2 +- .../maven/backend/MavenExecution.java | 24 +- .../maven/backend/MavenTestReports.java | 140 ++++++++++++ .../maven/backend/MavenTestSelection.java | 115 ---------- .../litheidea/maven/ReportCaptureEvents.java | 205 ++++++++++++++++++ .../META-INF/sisu/javax.inject.Named | 2 + io.github.lithe-idea.maven-build/plugin.json | 5 +- scripts/package-development.mjs | 2 + scripts/package.mjs | 2 + scripts/test-native-core.mjs | 31 ++- scripts/test-native.mjs | 21 +- scripts/test.mjs | 7 +- scripts/verify-extension.mjs | 14 ++ test/fixtures/fake-maven-backend.mjs | 14 +- 17 files changed, 464 insertions(+), 144 deletions(-) create mode 100644 backend/src/main/java/io/github/litheidea/maven/backend/MavenTestReports.java delete mode 100644 backend/src/main/java/io/github/litheidea/maven/backend/MavenTestSelection.java create mode 100644 extension/src/main/java/io/github/litheidea/maven/ReportCaptureEvents.java create mode 100644 scripts/verify-extension.mjs diff --git a/NOTICE b/NOTICE index e6c612a..b71862f 100644 --- a/NOTICE +++ b/NOTICE @@ -12,3 +12,8 @@ Version 2.0, at revision 158b854d47ac9af2bbd99c0d7c354a5875cb6f81: skipTests.svg platform/icons/src/expui/run/showIgnored.svg Copyright 2000-2024 JetBrains s.r.o. and contributors. + +The backend includes Apache Maven Surefire Report Parser and Logger API 3.5.2, +Apache Maven Shared Utils 3.3.4, and Apache Commons IO 2.19.0, under the Apache +License, Version 2.0. Copyright The Apache Software Foundation and contributors. +Their license and notice files are also retained inside the backend JAR. diff --git a/README.md b/README.md index bf238df..b2cde2d 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,13 @@ Provider 进度传回,最终结果保留非零退出码;取消或宿主退 测试的类和方法选择映射到 Surefire 的公开接口,特殊模式明确拒绝,不把一个精确 请求扩大成通配匹配。使用 -am 构建依赖模块时,它们可以没有所选测试;执行结束后 还检查当前模块/反应堆是否产生所选测试的新报告,避免“不存在的方法 + 成功空结果” -或旧报告被当成测试通过。完整结果仍由宿主既有 JUnit XML 解析器展示。 +或旧报告被当成测试通过。报告由插件随本次执行返回(buildProviders 8),宿主仅校验并展示规范化结果。 +Maven 已配置的 Surefire/Failsafe 实例提供实际报告目录,支持自定义目录;插件在执行 +前后比较有界字节、时间和文件身份,只有新报告进入当前结果。Apache Surefire Report +Parser 3.5.2 解释状态,读入同一份字节前拒绝 DTD/外部实体;失败执行同样返回报告, +两个模块里的同名测试保留各自工程身份。私有快照位于宿主工作区状态目录的 execution-*, +操作结束删除,原始报告继续留在用户工程,不修改插件包。干净打包还核对 Sisu 组件注册, +不依赖上一次编译的索引。 插件通过 buildModelInputs 1 显式公开规范化项目、目标、内容目录及 profiles/offline/ skipTests 的生效值;共享内容不包含任务、运行计划、settings.xml 内容或私有函数。 diff --git a/backend/pom.xml b/backend/pom.xml index c28bcd8..323ffd7 100644 --- a/backend/pom.xml +++ b/backend/pom.xml @@ -33,7 +33,18 @@ ${project.basedir}/missing-lithe-sdk.jar + + + commons-iocommons-io2.19.0 + + + + + org.apache.maven.surefire + surefire-report-parser + 3.5.2 + io.github.lithe-idea lithe-plugin-sdk-java diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java index 4bd666f..e5570a3 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java @@ -75,7 +75,7 @@ private Object execution(Map params, CallContext context, boolea // Model and execution use the same effective options and Maven runtime. // The extension remains the owner of reactor and plugin-goal facts. MavenRuns.Loaded loaded = load(params, context); - return MavenExecution.run(params, context, root, workspaceRoot, maven, environment, loaded, tests); + return MavenExecution.run(params, context, root, workspaceRoot, maven, environment, loaded, tests, extensionJar(), workspaceState); } private Object dependencies(Map params, CallContext context) throws Exception { diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecution.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecution.java index 4f69c77..0d8eb0f 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecution.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecution.java @@ -27,7 +27,7 @@ final class MavenExecution { private MavenExecution() {} static Map run(Map params, CallContext context, Path root, Path workspace, - Path maven, Map environment, MavenRuns.Loaded loaded, boolean tests) throws IOException { + Path maven, Map environment, MavenRuns.Loaded loaded, boolean tests, Path extension, Path state) throws Exception { String task = tests ? "test" : Json.string(params, "task"); if (!tests && !LIFECYCLE.contains(task) && !"plugin-goal".equals(task) && !"goal".equals(task)) { throw invalid("Unknown Maven task."); @@ -43,22 +43,12 @@ static Map run(Map params, CallContext context, command.add("-pl"); command.add(root.relativize(project).toString()); } - MavenTestSelection selection = null; + String suite = null, method = null; if (tests) { - String suite = filter(params.get("suite"), false); - String method = filter(params.get("case"), true); + suite = filter(params.get("suite"), false); + method = filter(params.get("case"), true); if (method != null && suite == null) throw invalid("A Maven test method needs its suite."); if (suite != null) { - List owners = new ArrayList<>(); - if (project != null) owners.add(project); - else for (Object candidate : list(loaded.model().get("projects"))) { - String path = Json.string(Json.object(candidate), "path"); - if (path == null) continue; - Path owner = root.resolve(path).normalize().toRealPath(); - if (!owner.startsWith(root)) throw invalid("Maven report owner leaves the current reactor."); - if (!owners.contains(owner)) owners.add(owner); - } - selection = new MavenTestSelection(owners, suite, method); if (project != null && !project.equals(root)) command.add("-am"); command.add("-Dtest=" + suite + (method == null ? "" : "#" + method)); command.add("-Dsurefire.failIfNoSpecifiedTests=false"); @@ -73,6 +63,8 @@ else for (Object candidate : list(loaded.model().get("projects"))) { List arguments = strings(params.get("userArguments")); if ("goal".equals(task) && arguments.isEmpty()) throw invalid("A custom Maven goal needs arguments."); command.addAll(arguments); + try (MavenTestReports reports = new MavenTestReports(state, workspace)) { + reports.instrument(command, extension); context.throwIfCancelled(); Output output = new Output(context); Processes.Result result; @@ -84,11 +76,13 @@ else for (Object candidate : list(loaded.model().get("projects"))) { throw error; } context.throwIfCancelled(); - if (selection != null && result.exitCode() == 0) selection.verify(context); + Map testResults = reports.read(context, suite, method, tests && result.exitCode() == 0); Map reply = new LinkedHashMap<>(); reply.put("exitCode", result.exitCode()); reply.put("output", output.text()); + reply.put("testResults", testResults); return reply; + } } /** One configuration drives model import, task execution and test execution. */ diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenTestReports.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenTestReports.java new file mode 100644 index 0000000..bb68589 --- /dev/null +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenTestReports.java @@ -0,0 +1,140 @@ +package io.github.litheidea.maven.backend; + +import io.github.litheidea.plugin.sdk.CallContext; +import io.github.litheidea.plugin.sdk.Json; +import io.github.litheidea.plugin.sdk.PluginError; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; +import javax.xml.XMLConstants; +import javax.xml.parsers.SAXParserFactory; +import org.apache.maven.plugin.surefire.log.api.NullConsoleLogger; +import org.apache.maven.plugins.surefire.report.ReportTestCase; +import org.apache.maven.plugins.surefire.report.ReportTestSuite; +import org.apache.maven.plugins.surefire.report.TestSuiteXmlParser; +import org.xml.sax.helpers.DefaultHandler; + +/** A private operation snapshot parsed by Apache's own Surefire report parser. */ +final class MavenTestReports implements AutoCloseable { + private static final int MAX_BYTES = 8 * 1024 * 1024; + private final Path directory; + private final Path workspace; + + MavenTestReports(Path state, Path workspace) throws IOException { + this.workspace = workspace.toRealPath(); + directory = state == null ? Files.createTempDirectory("lithe-maven-execution-") : Files.createTempDirectory(state, "execution-"); + Map initial = new LinkedHashMap<>(); + initial.put("format", "litheMavenOperationReports"); initial.put("version", 1); + initial.put("reports", Collections.emptyList()); + Files.write(directory.resolve("index.json"), Json.stringify(initial).getBytes(StandardCharsets.UTF_8)); + } + + void instrument(List command, Path extension) { + command.add("-Dmaven.ext.class.path=" + extension); + command.add("-Dlithe.reportOutput=" + directory.resolve("index.json")); + command.add("-Dlithe.reportWorkspace=" + workspace); + } + + Map read(CallContext context, String suite, String method, boolean requireMatch) throws Exception { + Map index = Json.object(Json.parse(new String(read(directory.resolve("index.json"), MAX_BYTES), StandardCharsets.UTF_8))); + if (!"litheMavenOperationReports".equals(index.get("format")) || !(index.get("version") instanceof Number) + || ((Number) index.get("version")).intValue() != 1 || index.containsKey("error") || !(index.get("reports") instanceof List)) { + throw invalid("Maven could not capture its current test reports."); + } + List files = (List) index.get("reports"); + if (files.size() > 10000) throw invalid("Maven test reports exceed the report count budget."); + List tests = new ArrayList<>(); + int total = 0; + boolean matched = false; + for (Object value : files) { + context.throwIfCancelled(); + Map entry = Json.object(value); + String file = Json.string(entry, "file"), project = Json.string(entry, "project"); + if (file == null || !file.matches("report-[0-9]+\\.xml") || project == null) throw invalid("Invalid operation report identity."); + Path owner = workspace.resolve(project).normalize(); + if (!owner.startsWith(workspace) || !owner.toRealPath().startsWith(workspace)) throw invalid("Report project leaves the workspace."); + byte[] bytes = read(directory.resolve(file), MAX_BYTES - total); total += bytes.length; + if (!hash(bytes).equals(entry.get("sha256"))) throw invalid("A captured report changed before decoding."); + // Upstream's parser does not harden its SAX factory. Reject DTDs + // and external entities on the same bounded immutable bytes first; + // all test outcome semantics remain in Apache's parser. + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + factory.setFeature("http://xml.org/sax/features/external-general-entities", false); + factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + factory.setXIncludeAware(false); + factory.newSAXParser().parse(new ByteArrayInputStream(bytes), new DefaultHandler()); + TestSuiteXmlParser parser = new TestSuiteXmlParser(new NullConsoleLogger()); + try (InputStreamReader input = new InputStreamReader(new ByteArrayInputStream(bytes), StandardCharsets.UTF_8)) { + for (ReportTestSuite parsed : parser.parse(input)) { + for (ReportTestCase test : parsed.getTestCases()) { + context.throwIfCancelled(); + if (tests.size() >= 10000) throw invalid("Maven test cases exceed the result budget."); + String name = test.getFullClassName(); + String testName = test.getName(); + if (name == null || name.isEmpty() || testName == null || testName.isEmpty()) throw invalid("Maven produced an unnamed test result."); + double time = test.getTime(); + if (!Double.isFinite(time) || time < 0 || time * 1000 > 9_007_199_254_740_991L) throw invalid("Maven produced an invalid test duration."); + String status = test.hasError() ? "error" : test.hasFailure() ? "failed" : test.hasSkipped() ? "skipped" : "passed"; + Map item = new LinkedHashMap<>(); + item.put("project", project.isEmpty() ? "." : project.replace(java.io.File.separatorChar, '/')); + item.put("suite", name); item.put("case", testName); item.put("status", status); + item.put("durationMillis", Math.round(time * 1000)); + String message = test.getFailureMessage(); + if (message == null || message.isEmpty()) message = test.getFailureDetail(); + if (message != null && !message.isEmpty()) item.put("message", message.substring(0, Math.min(message.length(), 16000))); + tests.add(item); + if (suite != null && (suite.equals(name) || !suite.contains(".") && name.endsWith("." + suite)) + && (method == null || method.equals(testName))) matched = true; + } + } + } + } + if (requireMatch && suite != null && !matched) throw new PluginError("maven.noMatchingTests", "Surefire produced no fresh result for the selected class or method."); + Map document = new LinkedHashMap<>(); + document.put("format", "litheTestResults"); document.put("version", 1); document.put("tests", tests); + if (Json.stringify(document).getBytes(StandardCharsets.UTF_8).length > MAX_BYTES) throw invalid("Maven's canonical test report exceeds its result budget."); + return document; + } + + private static byte[] read(Path file, int remaining) throws IOException { + if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS) || Files.size(file) > remaining) throw invalid("A captured report is not a bounded regular file."); + try (InputStream input = Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS); ByteArrayOutputStream output = new ByteArrayOutputStream()) { + byte[] chunk = new byte[8192]; int count; + while ((count = input.read(chunk)) >= 0) { + if (count > remaining - output.size()) throw invalid("Captured reports exceed the byte budget."); + output.write(chunk, 0, count); + } + return output.toByteArray(); + } + } + + private static String hash(byte[] bytes) throws Exception { + StringBuilder result = new StringBuilder(); + for (byte value : MessageDigest.getInstance("SHA-256").digest(bytes)) result.append(String.format("%02x", value & 255)); + return result.toString(); + } + private static PluginError invalid(String message) { return new PluginError("maven.invalidTestReport", message); } + + @Override + public void close() throws IOException { + try (Stream paths = Files.walk(directory)) { + for (Path path : (Iterable) paths.sorted(Comparator.reverseOrder())::iterator) Files.deleteIfExists(path); + } + } +} diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenTestSelection.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenTestSelection.java deleted file mode 100644 index f7f16b0..0000000 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenTestSelection.java +++ /dev/null @@ -1,115 +0,0 @@ -package io.github.litheidea.maven.backend; - -import io.github.litheidea.plugin.sdk.CallContext; -import io.github.litheidea.plugin.sdk.PluginError; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.LinkOption; -import java.nio.file.Path; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.List; -import java.util.stream.Stream; -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -/** Evidence that Surefire actually ran an explicit selector, not an empty successful reactor. */ -final class MavenTestSelection { - private static final int MAX_REPORT_BYTES = 8 * 1024 * 1024; - private static final int MAX_REPORTS = 10000; - private final Map before; - private final List roots; - private final String suite; - private final String method; - - MavenTestSelection(List roots, String suite, String method) throws IOException { - this.roots = roots; - this.suite = suite; - this.method = method; - before = reports(roots); - } - - void verify(CallContext context) throws IOException { - if (suite == null) return; - for (Map.Entry entry : reports(roots).entrySet()) { - context.throwIfCancelled(); - if (entry.getValue().same(before.get(entry.getKey()))) continue; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - factory.setFeature("http://xml.org/sax/features/external-general-entities", false); - factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); - factory.setXIncludeAware(false); - factory.setExpandEntityReferences(false); - factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); - factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); - NodeList tests = factory.newDocumentBuilder().parse(new ByteArrayInputStream(entry.getValue().bytes)).getElementsByTagName("testcase"); - for (int index = 0; index < tests.getLength(); index++) { - Element test = (Element) tests.item(index); - String name = test.getAttribute("classname"); - if ((suite.equals(name) || (!suite.contains(".") && name.endsWith("." + suite))) && (method == null || method.equals(test.getAttribute("name")))) return; - } - } catch (ParserConfigurationException | SAXException | IllegalArgumentException error) { - throw new PluginError("maven.invalidTestReport", "Surefire produced an unreadable test report.", error); - } - } - throw new PluginError("maven.noMatchingTests", "Surefire produced no fresh result for the selected class or method."); - } - - private static Map reports(List roots) throws IOException { - Map result = new LinkedHashMap<>(); - long total = 0; - int visited = 0; - for (Path root : roots) { - Path directory = root.resolve("target/surefire-reports"); - if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) continue; - Path real = directory.toRealPath(); - if (!real.startsWith(root)) throw new PluginError("maven.invalidTestReport", "Surefire reports leave the selected project."); - try (Stream files = Files.list(real)) { - for (Path file : (Iterable) files.limit(MAX_REPORTS + 1L).sorted()::iterator) { - if (++visited > MAX_REPORTS) throw new PluginError("maven.invalidTestReport", "Surefire reports exceed the verification budget."); - String name = file.getFileName().toString(); - if (!name.startsWith("TEST-") || !name.endsWith(".xml") || !Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) continue; - BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - if (result.size() >= MAX_REPORTS || attributes.size() > MAX_REPORT_BYTES - total) throw new PluginError("maven.invalidTestReport", "Surefire reports exceed the verification budget."); - byte[] bytes = boundedRead(file, (int) (MAX_REPORT_BYTES - total)); - total += bytes.length; - result.put(file, new Stamp(attributes, bytes)); - } - } - } - return result; - } - - private static byte[] boundedRead(Path file, int remaining) throws IOException { - try (InputStream input = Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS); - ByteArrayOutputStream output = new ByteArrayOutputStream()) { - byte[] chunk = new byte[8192]; - int count; - while ((count = input.read(chunk)) >= 0) { - if (count > remaining - output.size()) throw new PluginError("maven.invalidTestReport", "Surefire reports exceed the verification budget."); - output.write(chunk, 0, count); - } - return output.toByteArray(); - } - } - - private static final class Stamp { - final BasicFileAttributes attributes; - final byte[] bytes; - Stamp(BasicFileAttributes attributes, byte[] bytes) { this.attributes = attributes; this.bytes = bytes; } - boolean same(Stamp other) { - return other != null && attributes.lastModifiedTime().equals(other.attributes.lastModifiedTime()) - && java.util.Objects.equals(attributes.fileKey(), other.attributes.fileKey()) && Arrays.equals(bytes, other.bytes); - } - } -} diff --git a/extension/src/main/java/io/github/litheidea/maven/ReportCaptureEvents.java b/extension/src/main/java/io/github/litheidea/maven/ReportCaptureEvents.java new file mode 100644 index 0000000..a9b108a --- /dev/null +++ b/extension/src/main/java/io/github/litheidea/maven/ReportCaptureEvents.java @@ -0,0 +1,205 @@ +package io.github.litheidea.maven; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; +import javax.inject.Named; +import javax.inject.Singleton; +import org.apache.maven.execution.MojoExecutionEvent; +import org.apache.maven.execution.ExecutionEvent; +import org.apache.maven.eventspy.AbstractEventSpy; +import org.apache.maven.execution.MojoExecutionListener; +import org.apache.maven.plugin.MojoExecutionException; + +/** Captures only fresh reports from the configured upstream Surefire/Failsafe mojo. */ +@Named("lithe-operation-reports") +@Singleton +public final class ReportCaptureEvents extends AbstractEventSpy implements MojoExecutionListener { + private static final int MAX_BYTES = 8 * 1024 * 1024; + private static final int MAX_REPORTS = 10000; + private final Map active = new HashMap<>(); + private final List reports = new ArrayList<>(); + private int copiedBytes; + private int activeBytes; + private String failure; + + @Override + public synchronized void beforeMojoExecution(MojoExecutionEvent event) throws MojoExecutionException { + String output = output(event); + if (output == null || !testMojo(event)) return; + try { + Path state = Paths.get(output).toAbsolutePath().normalize().getParent().toRealPath(); + Path workspace = Paths.get(event.getSession().getUserProperties().getProperty("lithe.reportWorkspace")).toRealPath(); + Path project = event.getProject().getBasedir().toPath().toRealPath(); + if (!project.startsWith(workspace)) throw new IOException("Report project leaves the workspace."); + // The actual configured mojo owns interpolation and -D precedence. + // Both upstream plugins expose this public getter; there is no POM + // parser, default-directory guess or parallel parameter evaluator. + Object directory = event.getMojo().getClass().getMethod("getReportsDirectory").invoke(event.getMojo()); + if (!(directory instanceof File)) throw new IOException("The test mojo supplied no report directory."); + Path path = ((File) directory).toPath().toAbsolutePath().normalize(); + Map before = snapshot(path, workspace); + int bytes = 0; + for (Stamp stamp : before.values()) bytes += stamp.bytes.length; + if (bytes > MAX_BYTES - activeBytes) throw new IOException("Concurrent report snapshots exceed the byte budget."); + activeBytes += bytes; + active.put(new Key(event.getExecution(), event.getProject()), new Capture(state, workspace, project, path, before)); + } catch (Exception error) { + failure = "Could not inspect the configured test report directory."; + publish(output); + throw new MojoExecutionException(failure, error); + } + } + + @Override + public synchronized void afterMojoExecutionSuccess(MojoExecutionEvent event) throws MojoExecutionException { + finish(event); + } + + @Override + public synchronized void afterExecutionFailure(MojoExecutionEvent event) { + try { finish(event); } + catch (MojoExecutionException error) { /* The published failure is read by the backend after Maven exits. */ } + } + + private void finish(MojoExecutionEvent event) throws MojoExecutionException { + finish(new Key(event.getExecution(), event.getProject())); + } + + @Override + public synchronized void onEvent(Object event) throws Exception { + // Maven 3.9 does not notify MojoExecutionListener for checked test + // failures. Its execution event still covers every failed mojo, after + // release of the configured instance whose directory we captured. + if (event instanceof ExecutionEvent && ((ExecutionEvent) event).getType() == ExecutionEvent.Type.MojoFailed) { + ExecutionEvent failed = (ExecutionEvent) event; + finish(new Key(failed.getMojoExecution(), failed.getProject())); + } + } + + private void finish(Key key) throws MojoExecutionException { + Capture capture = active.remove(key); + if (capture == null) return; + for (Stamp stamp : capture.before.values()) activeBytes -= stamp.bytes.length; + String output = capture.state.resolve("index.json").toString(); + try { + for (Map.Entry entry : snapshot(capture.directory, capture.workspace).entrySet()) { + if (entry.getValue().same(capture.before.get(entry.getKey()))) continue; + byte[] bytes = entry.getValue().bytes; + if (reports.size() >= MAX_REPORTS || bytes.length > MAX_BYTES - copiedBytes) throw new IOException("Report budget exceeded."); + String name = "report-" + reports.size() + ".xml"; + Files.write(capture.state.resolve(name), bytes, StandardOpenOption.CREATE_NEW); + copiedBytes += bytes.length; + Map report = new LinkedHashMap<>(); + report.put("file", name); + report.put("sha256", hash(bytes)); + report.put("project", capture.workspace.relativize(capture.project).toString().replace(File.separatorChar, '/')); + reports.add(report); + } + publish(output); + } catch (Exception error) { + failure = "Could not capture the current Maven test reports."; + publish(output); + throw new MojoExecutionException(failure, error); + } + } + + private void publish(String output) throws MojoExecutionException { + Map value = new LinkedHashMap<>(); + value.put("format", "litheMavenOperationReports"); value.put("version", 1); + value.put("reports", reports); + if (failure != null) value.put("error", failure); + try { LitheLifecycleParticipant.write(output, Json.write(value)); } + catch (org.apache.maven.MavenExecutionException error) { throw new MojoExecutionException("Could not publish Maven report capture.", error); } + } + + private static boolean testMojo(MojoExecutionEvent event) { + if (!"org.apache.maven.plugins".equals(event.getExecution().getGroupId())) return false; + String artifact = event.getExecution().getArtifactId(); + String goal = event.getExecution().getGoal(); + return "maven-surefire-plugin".equals(artifact) && "test".equals(goal) + || "maven-failsafe-plugin".equals(artifact) && "integration-test".equals(goal); + } + + private static String output(MojoExecutionEvent event) { + return event.getSession().getUserProperties().getProperty("lithe.reportOutput"); + } + + private static Map snapshot(Path directory, Path workspace) throws IOException { + Map result = new LinkedHashMap<>(); + if (!Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) return result; + Path real = directory.toRealPath(); + if (!real.startsWith(workspace) || !Files.isDirectory(real)) throw new IOException("Reports leave the workspace."); + int total = 0; + try (Stream files = Files.list(real)) { + int visited = 0; + for (Path file : (Iterable) files.limit(MAX_REPORTS + 1L).sorted()::iterator) { + if (++visited > MAX_REPORTS) throw new IOException("Report count exceeded."); + String name = file.getFileName().toString(); + if (!name.startsWith("TEST-") || !name.endsWith(".xml")) continue; + if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Report is not a regular file."); + BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (attributes.size() > MAX_BYTES - total) throw new IOException("Report byte budget exceeded."); + byte[] bytes = read(file, MAX_BYTES - total); total += bytes.length; + result.put(file, new Stamp(attributes, bytes)); + } + } + return result; + } + + private static byte[] read(Path file, int remaining) throws IOException { + try (InputStream input = Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS); ByteArrayOutputStream output = new ByteArrayOutputStream()) { + byte[] chunk = new byte[8192]; int count; + while ((count = input.read(chunk)) >= 0) { + if (count > remaining - output.size()) throw new IOException("Report byte budget exceeded."); + output.write(chunk, 0, count); + } + return output.toByteArray(); + } + } + + private static String hash(byte[] bytes) throws Exception { + StringBuilder value = new StringBuilder(); + for (byte part : MessageDigest.getInstance("SHA-256").digest(bytes)) value.append(String.format("%02x", part & 255)); + return value.toString(); + } + + private static final class Key { + final Object execution, project; + Key(Object execution, Object project) { this.execution = execution; this.project = project; } + @Override public boolean equals(Object other) { return other instanceof Key && ((Key) other).execution == execution && ((Key) other).project == project; } + @Override public int hashCode() { return 31 * System.identityHashCode(execution) + System.identityHashCode(project); } + } + + private static final class Capture { + final Path state, workspace, project, directory; + final Map before; + Capture(Path state, Path workspace, Path project, Path directory, Map before) { + this.state = state; this.workspace = workspace; this.project = project; this.directory = directory; this.before = before; + } + } + private static final class Stamp { + final BasicFileAttributes attributes; + final byte[] bytes; + Stamp(BasicFileAttributes attributes, byte[] bytes) { this.attributes = attributes; this.bytes = bytes; } + boolean same(Stamp other) { + return other != null && attributes.lastModifiedTime().equals(other.attributes.lastModifiedTime()) + && java.util.Objects.equals(attributes.fileKey(), other.attributes.fileKey()) && Arrays.equals(bytes, other.bytes); + } + } +} diff --git a/extension/src/main/resources/META-INF/sisu/javax.inject.Named b/extension/src/main/resources/META-INF/sisu/javax.inject.Named index 957f27e..fb12338 100644 --- a/extension/src/main/resources/META-INF/sisu/javax.inject.Named +++ b/extension/src/main/resources/META-INF/sisu/javax.inject.Named @@ -1 +1,3 @@ io.github.litheidea.maven.LitheLifecycleParticipant +io.github.litheidea.maven.NativeSettingsEvents +io.github.litheidea.maven.ReportCaptureEvents diff --git a/io.github.lithe-idea.maven-build/plugin.json b/io.github.lithe-idea.maven-build/plugin.json index de0c0ba..42af8f5 100644 --- a/io.github.lithe-idea.maven-build/plugin.json +++ b/io.github.lithe-idea.maven-build/plugin.json @@ -4,7 +4,7 @@ "displayName": "Maven", "version": "0.1.1", "pluginAPIVersion": 3, - "requires": { "buildProviders": 7, "buildModelInputs": 1, "buildSystems": 3, "executableResolution": 2, "serverProcess": 1 }, + "requires": { "buildProviders": 8, "buildModelInputs": 1, "buildSystems": 3, "executableResolution": 2, "serverProcess": 1 }, "vendor": { "id": "io.github.lithe-idea", "displayName": "Lithe Community", @@ -185,8 +185,7 @@ "source": "provider", "arguments": [], "results": { - "decoder": "junitXml", - "reports": ["target/surefire-reports/TEST-*.xml", "target/failsafe-reports/TEST-*.xml"] + "decoder": "provider" } }, "diagnostics": { diff --git a/scripts/package-development.mjs b/scripts/package-development.mjs index f38bb9b..20f2e83 100644 --- a/scripts/package-development.mjs +++ b/scripts/package-development.mjs @@ -4,6 +4,7 @@ import { createHash } from 'node:crypto'; import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { runCommand, withInterrupts, mavenTimeout } from './process.mjs'; +import { verifyExtension } from './verify-extension.mjs'; import { createReport } from './report.mjs'; import { bundleManifest } from './bundle-manifest.mjs'; @@ -26,6 +27,7 @@ await withInterrupts(async (signal) => { ['extension', []], ['backend', [`-Dlithe.sdk.jar=${sdk}`]], ]) await report.step(`build ${name} with the explicit development SDK`, () => runCommand(process.env.MVN ?? 'mvn', ['-B', '-ntp', '-q', '-f', join(scratch, name, 'pom.xml'), ...args, 'package'], { signal, timeoutMs: mavenTimeout() })); + await report.step('check clean extension component registration', () => verifyExtension(join(scratch, 'extension/target/lithe-maven-extension.jar'))); const pkg = join(run, id); await report.step('assemble a development-only package', () => { cpSync(resolve(id), pkg, { recursive: true }); diff --git a/scripts/package.mjs b/scripts/package.mjs index 423bc68..e4e334b 100644 --- a/scripts/package.mjs +++ b/scripts/package.mjs @@ -18,6 +18,7 @@ // Usage: node scripts/package.mjs [--expect-tag ] import { mavenTimeout, runCommand, withInterrupts, ZIP_TIMEOUT_MS } from "./process.mjs"; +import { verifyExtension } from './verify-extension.mjs'; import { createReport } from "./report.mjs"; import { createHash } from "node:crypto"; import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; @@ -117,6 +118,7 @@ await withInterrupts(async (signal) => { await report.step("build the Maven extension", async () => { await runCommand(process.env.MVN ?? "mvn", ["-B", "-ntp", "-q", "-f", "extension/pom.xml", "clean", "package"], { timeoutMs, signal }); if (!existsSync(EXTENSION_JAR)) throw new Error(`${EXTENSION_JAR} was not built`); + verifyExtension(EXTENSION_JAR); }); const sdk = await report.step("check the plugin SDK", () => sdkJar(signal)); diff --git a/scripts/test-native-core.mjs b/scripts/test-native-core.mjs index eff3e90..f3a27b4 100644 --- a/scripts/test-native-core.mjs +++ b/scripts/test-native-core.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node // The production plugin, current Core C ABI, and a real Maven reactor in one workflow. import assert from 'node:assert/strict'; -import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs'; +import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { spawnSync } from 'node:child_process'; @@ -45,7 +45,7 @@ await withInterrupts(async (signal) => { state: join(scratch, 'state'), timeoutMs: mavenTimeout() }); await report.step('Core admits the new Maven capability and produces only Provider plans', async () => { coreCommand('plugins.declarative.validate', { manifest }); - assert.equal((await client.initialize(workspace, [3])).capabilities.experimental.litheBuild.version, 3); + assert.equal((await client.initialize(workspace, [8])).capabilities.experimental.litheBuild.version, 8); for (const task of manifest.buildSystems[0].tasks) { assert.equal(task.source, 'provider'); assert.deepEqual(task.arguments, []); } assert.equal(manifest.buildSystems[0].test.source, 'provider'); }); @@ -73,7 +73,7 @@ await withInterrupts(async (signal) => { const result = await send(testPlan, 'exact-test'); assert.equal(result.exitCode, 0, result.output); const tests = build('build.decodeTestResults', { workspaceRoot: workspace, root, project: project.path, projects: model.projects.map(project => project.path), - suite: 'demo.core.GreeterTest', output: result.output }).results; + suite: 'demo.core.GreeterTest', output: result.output, result: result.testResults }).results; assert.equal(tests.summary.total, 1, JSON.stringify(tests)); assert.equal(tests.summary.failed, 0, JSON.stringify(tests)); assert.equal(tests.tests[0].case, 'greetsByName'); @@ -84,12 +84,37 @@ await withInterrupts(async (signal) => { const plan = build('build.testPlan', planned({ project, suite: 'demo.core.GreeterTest', case: 'doesNotExist', userArguments: [] })).plan; await assert.rejects(send(plan, 'unknown-test'), /no fresh result/); }); + await report.step('custom Surefire directories and a failing method return only fresh inline reports', async () => { + const directory = join(workspace, root, 'core'); + const pom = join(directory, 'pom.xml'); + const original = readFileSync(pom, 'utf8'); + writeFileSync(pom, original.replace('', `org.apache.maven.plugins + maven-surefire-plugin\${project.build.directory}/custom reports + `)); + const failure = join(directory, 'src/test/java/demo/core/FailureTest.java'); + writeFileSync(failure, 'package demo.core; public class FailureTest { @org.junit.Test public void failsForReport() { org.junit.Assert.fail("expected report failure"); } }'); + const plan = build('build.testPlan', planned({ project, suite: 'demo.core.FailureTest', case: 'failsForReport', userArguments: [] })).plan; + const result = await send(plan, 'failing-custom-report'); + assert.notEqual(result.exitCode, 0, result.output); + assert.ok(existsSync(join(directory, 'target/custom reports/TEST-demo.core.FailureTest.xml'))); + const decoded = build('build.decodeTestResults', { workspaceRoot: workspace, root, project: project.path, + projects: model.projects.map(value => value.path), result: result.testResults }).results; + assert.equal(decoded.summary.total, 1, JSON.stringify(decoded)); + assert.equal(decoded.summary.failed, 1, JSON.stringify(decoded)); + assert.equal(decoded.tests[0].project, 'nested/core'); + assert.equal(decoded.tests[0].case, 'failsForReport'); + assert.match(decoded.tests[0].message, /expected report failure/); + assert.deepEqual((await (await import('node:fs/promises')).readdir(join(scratch, 'state'))).filter(name => name.startsWith('execution-')), []); + rmSync(failure); + writeFileSync(pom, original); + }); await report.step('publish the same normalized Maven facts and effective options to a declared consumer', () => { const consumer = JSON.parse(JSON.stringify(manifest)); consumer.id = 'org.example.maven-input-consumer'; consumer.requires.buildProviders = 6; delete consumer.buildSystems[0].modelSharing; delete consumer.buildSystems[0].configuration; + delete consumer.buildSystems[0].test.results; consumer.buildSystems[0].modelInputs = [{ pluginID: id, buildSystemID: 'maven' }]; const snapshot = coreCommand('build.resolveModelInputs', { manifest: consumer, buildSystemID: 'maven', request: { revision: 11, sources: [{ manifest, instances: [{ buildSystemID: 'maven', root, state: 'ready', model, options }] }] } }).modelInputs; diff --git a/scripts/test-native.mjs b/scripts/test-native.mjs index f06c527..65c7085 100644 --- a/scripts/test-native.mjs +++ b/scripts/test-native.mjs @@ -23,7 +23,10 @@ const executable = join(scratch, 'mvn'); const clients = new Set(); const report = createReport('native-maven'); const runs = () => existsSync(log) ? readFileSync(log, 'utf8').trim().split('\n').filter(Boolean).map(JSON.parse) : []; -const executionRuns = () => runs().filter(run => !run.argv.includes('pre-clean')); +const executionRuns = () => runs().filter(run => !run.argv.includes('pre-clean')).map(run => ({ ...run, + instrumentation: run.argv.filter(arg => ['-Dmaven.ext.class.path=', '-Dlithe.reportOutput=', '-Dlithe.reportWorkspace='].some(prefix => arg.startsWith(prefix))), + argv: run.argv.filter(arg => !['-Dmaven.ext.class.path=', '-Dlithe.reportOutput=', '-Dlithe.reportWorkspace='].some(prefix => arg.startsWith(prefix))), +})); const control = value => writeFileSync(controlFile, JSON.stringify(value)); const alive = pid => { try { process.kill(pid, 0); return true; } catch (error) { if (error.code === 'ESRCH') return false; throw error; } }; async function until(condition, description) { @@ -42,7 +45,7 @@ async function start() { state, javaOptions: [`-Duser.home=${join(scratch, 'home')}`], env: { ...process.env, FAKE_MAVEN_CONTROL: controlFile, FAKE_MAVEN_LOG: log } }); clients.add(client); - assert.equal((await client.initialize(workspace, [3])).capabilities.experimental.litheBuild.version, 3); + assert.equal((await client.initialize(workspace, [8])).capabilities.experimental.litheBuild.version, 8); return client; } await withInterrupts(async (signal) => { @@ -69,6 +72,9 @@ await withInterrupts(async (signal) => { assert.equal(result.exitCode, 0); const run = executionRuns().at(-1); assert.equal(run.cwd, root); + assert.equal(run.instrumentation.length, 3); + assert.ok(run.instrumentation.some(arg => arg.startsWith('-Dlithe.reportOutput=' + state + '/execution-'))); + assert.deepEqual(result.testResults.tests, []); assert.deepEqual(run.argv, ['-B', '-ntp', '-Pci', '-s', '/fixture settings.xml', '-Dmaven.repo.local=/fixture repository', '-o', '-DskipTests', '-pl', 'core', 'package', '-Dmessage=two words']); const progress = client.notifications.filter(message => message.method === 'lithe/build/progress' && message.params.operationID === 'package'); assert.equal(progress.map(message => message.params.output ?? '').join(''), result.output); @@ -88,6 +94,8 @@ await withInterrupts(async (signal) => { const result = await client.request('lithe/build/test', params({ project: selected, suite: 'demo.core.GreeterTest', case: 'greets', options: { skipTests: true }, operationID: 'exact-test' })); assert.equal(result.exitCode, 0); + assert.equal(result.testResults.tests[0].suite, 'demo.core.GreeterTest'); + assert.equal(result.testResults.tests[0].project, 'nested/core'); assert.deepEqual(executionRuns().at(-1).argv, ['-B', '-ntp', '-pl', 'core', '-am', '-Dtest=demo.core.GreeterTest#greets', '-Dsurefire.failIfNoSpecifiedTests=false', 'test']); const count = executionRuns().length; await assert.rejects(client.request('lithe/build/test', params({ project: selected, suite: '*', operationID: 'wildcard' })), /exact Surefire/); @@ -106,6 +114,15 @@ await withInterrupts(async (signal) => { operationID: 'wrong-package-test' })), /no fresh result/); control({}); }); + await report.step('malformed or external-entity reports fail closed and release operation state', async () => { + for (const badReport of ['broken', 'external-entity']) { + control({ execution: { badReport } }); + await assert.rejects(client.request('lithe/build/test', params({ project: selected, + suite: 'demo.core.GreeterTest', operationID: 'bad-' + badReport }))); + assert.deepEqual((await (await import('node:fs/promises')).readdir(state)).filter(name => name.startsWith('execution-')), []); + } + control({}); + }); await report.step('a custom goal preserves user arguments and an unknown project cannot execute', async () => { await client.request('lithe/build/execute', params({ task: 'goal', operationID: 'custom', userArguments: ['validate', '-Dvalue=a b'] })); assert.deepEqual(executionRuns().at(-1).argv, ['-B', '-ntp', 'validate', '-Dvalue=a b']); diff --git a/scripts/test.mjs b/scripts/test.mjs index 31a8ccf..28cb5c9 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -78,7 +78,7 @@ async function test(signal) { state: join(scratch, "state"), timeoutMs, }); - await report.step("start the build provider", () => backend.initialize(root, [3])); + await report.step("start the build provider", () => backend.initialize(root, [8])); const params = (extra = {}) => ({ buildSystemID: "maven", root: ".", options: {}, optionArguments: [], environment: {}, tool: { executable: mavenExecutable() }, ...extra, @@ -165,8 +165,11 @@ async function test(signal) { const result = await backend.request("lithe/build/test", params({ project: { name: "core", path: "core" }, suite: "demo.core.GreeterTest", userArguments: [], operationID: "test-suite" })); assert.equal(result.exitCode, 0, result.output); + assert.equal(result.testResults.format, "litheTestResults"); + assert.equal(result.testResults.tests.length, 2); + assert.ok(result.testResults.tests.every(test => test.project === "core" && test.status === "passed")); }); - await check("a filtered test run writes the report the results glob reads", () => { + await check("the upstream reports remain in the project while the host consumes the inline document", () => { const report = readFileSync(join(root, "core", "target", "surefire-reports", "TEST-demo.core.GreeterTest.xml"), "utf8"); assert.match(report, /]*name="demo\.core\.GreeterTest"[^>]*tests="2"/); }); diff --git a/scripts/verify-extension.mjs b/scripts/verify-extension.mjs new file mode 100644 index 0000000..517c197 --- /dev/null +++ b/scripts/verify-extension.mjs @@ -0,0 +1,14 @@ +// Runtime-discovered components must survive a clean package, independent of +// compiler output left by an earlier build. Native settings and failed report +// callbacks are otherwise silently absent despite their classes being present. +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +export function verifyExtension(jar) { + const result = spawnSync('unzip', ['-p', jar, 'META-INF/sisu/javax.inject.Named'], + { encoding: 'utf8', timeout: 5000, maxBuffer: 65536 }); + assert.equal(result.status, 0, result.error?.message ?? result.stderr); + const components = new Set(result.stdout.trim().split(/\r?\n/)); + for (const name of ['LitheLifecycleParticipant', 'NativeSettingsEvents', 'ReportCaptureEvents']) { + assert.ok(components.has('io.github.litheidea.maven.' + name), `The clean extension package omits ${name}`); + } +} diff --git a/test/fixtures/fake-maven-backend.mjs b/test/fixtures/fake-maven-backend.mjs index 49de1b0..dd1f6d7 100644 --- a/test/fixtures/fake-maven-backend.mjs +++ b/test/fixtures/fake-maven-backend.mjs @@ -10,7 +10,7 @@ import { spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { pathToFileURL } from "node:url"; import { appendFileSync, existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs"; -import { join } from "node:path"; +import { join, dirname, relative } from "node:path"; const configuration = existsSync(process.env.FAKE_MAVEN_CONTROL ?? "") ? JSON.parse(readFileSync(process.env.FAKE_MAVEN_CONTROL, "utf8")) @@ -52,7 +52,17 @@ if (!exporting) { const suite = control.reportSuite ?? selectedSuite; const directory = join(process.cwd(), "core/target/surefire-reports"); mkdirSync(directory, { recursive: true }); - writeFileSync(join(directory, "TEST-" + suite + ".xml"), ``); + const xml = control.badReport === 'broken' ? ']>&external;' + : ``; + writeFileSync(join(directory, "TEST-" + suite + ".xml"), xml); + if (value("lithe.reportOutput")) { + const file = join(dirname(value("lithe.reportOutput")), 'report-0.xml'); + writeFileSync(file, xml); + writeFileSync(value("lithe.reportOutput"), JSON.stringify({ format: 'litheMavenOperationReports', version: 1, + reports: [{ file: 'report-0.xml', project: relative(value("lithe.reportWorkspace"), join(process.cwd(), 'core')), + sha256: createHash('sha256').update(xml).digest('hex') }] })); + } } if (control.flood) await new Promise((done, reject) => process.stdout.write("x".repeat(9 * 1024 * 1024), error => error ? reject(error) : done())); process.exit(0); From af679f7afa8999381ee9d7fd0b38d13471dd1f37 Mon Sep 17 00:00:00 2001 From: wgw Date: Thu, 29 Oct 2026 08:07:29 +0800 Subject: [PATCH 05/24] test(maven): preserve Failsafe reports from failing verify tasks --- scripts/test-native-core.mjs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/scripts/test-native-core.mjs b/scripts/test-native-core.mjs index f3a27b4..58d0921 100644 --- a/scripts/test-native-core.mjs +++ b/scripts/test-native-core.mjs @@ -108,6 +108,39 @@ await withInterrupts(async (signal) => { rmSync(failure); writeFileSync(pom, original); }); + await report.step('verify retains Failsafe failures alongside fresh Surefire results', async () => { + const directory = join(workspace, root, 'core'); + const pom = join(directory, 'pom.xml'); + const original = readFileSync(pom, 'utf8'); + const integration = join(directory, 'src/test/java/demo/core/FailureIT.java'); + try { + writeFileSync(pom, original.replace('', `org.apache.maven.plugins + maven-failsafe-plugin3.5.2 + \${project.build.directory}/integration reports + integration-testverify + `)); + writeFileSync(integration, 'package demo.core; public class FailureIT { @org.junit.Test public void failsInIntegration() { org.junit.Assert.fail("expected Failsafe failure"); } }'); + // Clean removes the preceding failing class after its source was removed. + // Maven owns both phases; the host must not merge stale report directories. + const plan = build('build.taskPlan', planned({ task: 'goal', project, userArguments: ['clean', 'verify'] })).plan; + const result = await send(plan, 'failsafe-verify'); + assert.notEqual(result.exitCode, 0, result.output); + assert.ok(existsSync(join(directory, 'target/integration reports/TEST-demo.core.FailureIT.xml'))); + const decoded = build('build.decodeTestResults', { workspaceRoot: workspace, root, project: project.path, + projects: model.projects.map(value => value.path), result: result.testResults }).results; + assert.equal(decoded.summary.total, 3, JSON.stringify(decoded)); + assert.equal(decoded.summary.passed, 2, JSON.stringify(decoded)); + assert.equal(decoded.summary.failed, 1, JSON.stringify(decoded)); + assert.ok(decoded.tests.every(test => test.project === 'nested/core')); + const failed = decoded.tests.find(test => test.case === 'failsInIntegration'); + assert.equal(failed?.status, 'failed'); + assert.match(failed.message, /expected Failsafe failure/); + assert.deepEqual((await (await import('node:fs/promises')).readdir(join(scratch, 'state'))).filter(name => name.startsWith('execution-')), []); + } finally { + rmSync(integration, { force: true }); + writeFileSync(pom, original); + } + }); await report.step('publish the same normalized Maven facts and effective options to a declared consumer', () => { const consumer = JSON.parse(JSON.stringify(manifest)); consumer.id = 'org.example.maven-input-consumer'; From 7a03fae17c0042f2e377125e923ee04ef1d95435 Mon Sep 17 00:00:00 2001 From: wgw Date: Thu, 29 Oct 2026 13:36:20 +0800 Subject: [PATCH 06/24] feat(maven): execute exact JDT test identities with reactor isolation --- README.md | 11 ++ .../maven/backend/MavenExecution.java | 37 +++--- .../maven/backend/MavenTestReports.java | 10 +- .../maven/backend/MavenTestSelection.java | 122 ++++++++++++++++++ .../litheidea/maven/ReportCaptureEvents.java | 10 ++ io.github.lithe-idea.maven-build/plugin.json | 3 +- scripts/test-native-core.mjs | 102 ++++++++++++++- scripts/test-native.mjs | 33 ++++- test/fixtures/fake-maven-backend.mjs | 7 +- 9 files changed, 301 insertions(+), 34 deletions(-) create mode 100644 backend/src/main/java/io/github/litheidea/maven/backend/MavenTestSelection.java diff --git a/README.md b/README.md index b2cde2d..ba04d00 100644 --- a/README.md +++ b/README.md @@ -257,3 +257,14 @@ LITHE_CORE_LIBRARY=/absolute/liblithe_core.dylib node scripts/test-configuration 工具解析要求 `executableResolution: 2`,通过宿主已有 `project-maven` / `project-maven-jdk` 注册表读取 `.lithe/run/local.json` 的当前实例选择,复用 Run 的配置链。宿主把选中的 Maven 路径以及有限的运行时环境(含 JAVA_HOME/PATH)交给 Provider;Provider 进程自身的 JDK 不等于 Maven 所用的 JDK。显式选择失败不能独立改用其他 Maven;被动导入不执行 Wrapper 或探测版本。 只读配置探针观察 Maven 官方完成默认值填充后的 `MavenExecutionRequest`:先保留所选 settings、Profiles 和仓库事实,再将这次探针自己的仓库管理器隔离到临时 `configuration-*/repository`,在工程导入前退出。仅在 `afterSessionStart` 导出会过晚,可能已经创建用户仓库。读取、保存后的回读与 CLI 覆盖均不得创建实际仓库;临时目录统一清理。真实模型、依赖和构建使用原仓库,不采用此探针隔离。 + +开发协议 9 还接受 JDT 提供的公开 `java.test.fullName` 标识。宿主原样转交标识, +Maven 后端才把类或 `类#方法()` 映射成 Surefire 的精确选择器;不按源码文件名猜类名。 +不能精确表示的签名或模式会明确拒绝。成功执行还要求所选工程的新报告包含每个标识, +依赖模块里的同名用例不能代替它。空选择列表只在明确的工作区/工程测试范围运行全部测试。 + +精确筛选使用 Surefire 公开 `%regex[class#method]` 接口,引用完整类文件路径, +避免普通全限定名模式的 `**/` 后缀匹配。参数化调用归并到同一 Java 方法;报告明确 +区分工程和覆盖范围,整类重跑才能移除该类过时的方法结果。`-am` 仍编译依赖, +已配置的测试 Mojo 通过公开 setter 跳过未选工程;原始 `-Dtest=*` 不会扩大类型化选择。 +没有明确整类选择时,继承的上游筛选可能仍有效,所以只声明报告中返回的方法覆盖。 diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecution.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecution.java index 0d8eb0f..edeff96 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecution.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecution.java @@ -43,15 +43,10 @@ static Map run(Map params, CallContext context, command.add("-pl"); command.add(root.relativize(project).toString()); } - String suite = null, method = null; + MavenTestSelection selection = MavenTestSelection.from(params); if (tests) { - suite = filter(params.get("suite"), false); - method = filter(params.get("case"), true); - if (method != null && suite == null) throw invalid("A Maven test method needs its suite."); - if (suite != null) { + if (selection.isFiltered()) { if (project != null && !project.equals(root)) command.add("-am"); - command.add("-Dtest=" + suite + (method == null ? "" : "#" + method)); - command.add("-Dsurefire.failIfNoSpecifiedTests=false"); } command.add("test"); } else if ("plugin-goal".equals(task)) { @@ -63,8 +58,14 @@ static Map run(Map params, CallContext context, List arguments = strings(params.get("userArguments")); if ("goal".equals(task) && arguments.isEmpty()) throw invalid("A custom Maven goal needs arguments."); command.addAll(arguments); + // Typed selectors outrank raw CLI properties; the user must not + // accidentally turn an exact test action into an unfiltered run. + if (tests && selection.isFiltered()) { + command.add(selection.argument()); + command.add("-Dsurefire.failIfNoSpecifiedTests=false"); + } try (MavenTestReports reports = new MavenTestReports(state, workspace)) { - reports.instrument(command, extension); + reports.instrument(command, extension, tests ? project : null); context.throwIfCancelled(); Output output = new Output(context); Processes.Result result; @@ -76,7 +77,15 @@ static Map run(Map params, CallContext context, throw error; } context.throwIfCancelled(); - Map testResults = reports.read(context, suite, method, tests && result.exitCode() == 0); + Map testResults = reports.read(context); + if (tests && result.exitCode() == 0 && selection.isFiltered()) { + String owner = project == null ? null : workspace.relativize(project).toString().replace(java.io.File.separatorChar, '/'); + selection.verify(testResults, "".equals(owner) ? "." : owner); + } + if (tests) selection.addCoverage(testResults); + if (Json.stringify(testResults).getBytes(java.nio.charset.StandardCharsets.UTF_8).length > MAX_OUTPUT_BYTES) { + throw new PluginError("maven.outputTooLarge", "Maven's canonical test report exceeds its result budget."); + } Map reply = new LinkedHashMap<>(); reply.put("exitCode", result.exitCode()); reply.put("output", output.text()); @@ -137,16 +146,6 @@ private static String pluginGoal(Object selected, Path project, Path root, Maven throw invalid("The plugin goal is absent from the current Maven model."); } - private static String filter(Object value, boolean method) { - if (value == null) return null; - String text = optionalString(value); - // Surefire treats punctuation as patterns. Exact selectors must not widen to another test. - if (text == null || !text.matches(method ? "[A-Za-z_$][A-Za-z0-9_$]*" : "[A-Za-z_$][A-Za-z0-9_.$]*")) { - throw invalid("The test selector cannot be represented as an exact Surefire class or method."); - } - return text; - } - private static boolean booleanOption(Map options, String name) { Object value = options.get(name); if (value != null && !(value instanceof Boolean)) throw invalid("Expected a boolean Maven option."); diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenTestReports.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenTestReports.java index bb68589..1d598c4 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenTestReports.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenTestReports.java @@ -43,13 +43,14 @@ final class MavenTestReports implements AutoCloseable { Files.write(directory.resolve("index.json"), Json.stringify(initial).getBytes(StandardCharsets.UTF_8)); } - void instrument(List command, Path extension) { + void instrument(List command, Path extension, Path testProject) { + command.add("-Dlithe.testProject=" + (testProject == null ? "" : testProject)); command.add("-Dmaven.ext.class.path=" + extension); command.add("-Dlithe.reportOutput=" + directory.resolve("index.json")); command.add("-Dlithe.reportWorkspace=" + workspace); } - Map read(CallContext context, String suite, String method, boolean requireMatch) throws Exception { + Map read(CallContext context) throws Exception { Map index = Json.object(Json.parse(new String(read(directory.resolve("index.json"), MAX_BYTES), StandardCharsets.UTF_8))); if (!"litheMavenOperationReports".equals(index.get("format")) || !(index.get("version") instanceof Number) || ((Number) index.get("version")).intValue() != 1 || index.containsKey("error") || !(index.get("reports") instanceof List)) { @@ -59,7 +60,6 @@ Map read(CallContext context, String suite, String method, boole if (files.size() > 10000) throw invalid("Maven test reports exceed the report count budget."); List tests = new ArrayList<>(); int total = 0; - boolean matched = false; for (Object value : files) { context.throwIfCancelled(); Map entry = Json.object(value); @@ -87,6 +87,7 @@ Map read(CallContext context, String suite, String method, boole if (tests.size() >= 10000) throw invalid("Maven test cases exceed the result budget."); String name = test.getFullClassName(); String testName = test.getName(); + if (testName != null) testName = MavenTestSelection.reportMethod(testName); if (name == null || name.isEmpty() || testName == null || testName.isEmpty()) throw invalid("Maven produced an unnamed test result."); double time = test.getTime(); if (!Double.isFinite(time) || time < 0 || time * 1000 > 9_007_199_254_740_991L) throw invalid("Maven produced an invalid test duration."); @@ -99,13 +100,10 @@ Map read(CallContext context, String suite, String method, boole if (message == null || message.isEmpty()) message = test.getFailureDetail(); if (message != null && !message.isEmpty()) item.put("message", message.substring(0, Math.min(message.length(), 16000))); tests.add(item); - if (suite != null && (suite.equals(name) || !suite.contains(".") && name.endsWith("." + suite)) - && (method == null || method.equals(testName))) matched = true; } } } } - if (requireMatch && suite != null && !matched) throw new PluginError("maven.noMatchingTests", "Surefire produced no fresh result for the selected class or method."); Map document = new LinkedHashMap<>(); document.put("format", "litheTestResults"); document.put("version", 1); document.put("tests", tests); if (Json.stringify(document).getBytes(StandardCharsets.UTF_8).length > MAX_BYTES) throw invalid("Maven's canonical test report exceeds its result budget."); diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenTestSelection.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenTestSelection.java new file mode 100644 index 0000000..4147ade --- /dev/null +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenTestSelection.java @@ -0,0 +1,122 @@ +package io.github.litheidea.maven.backend; + +import io.github.litheidea.plugin.sdk.Json; +import io.github.litheidea.plugin.sdk.PluginError; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +/** Maps JDT's public fullName identity to Surefire, without reading Java sources. */ +final class MavenTestSelection { + private final Map selections = new LinkedHashMap<>(); + + static MavenTestSelection from(Map params) { + MavenTestSelection result = new MavenTestSelection(); + Object kind = params.get("selectorKind"), values = params.get("selectors"); + if (kind == null && values == null) { + Object suite = params.get("suite"), method = params.get("case"); + if (suite == null) { + if (method != null) throw invalid("A Maven test method needs its suite."); + return result; + } + if (!(suite instanceof String) || !exactName((String) suite, false) + || method != null && (!(method instanceof String) || !exactName((String) method, true))) { + throw invalid("The test selector cannot be represented as an exact Surefire class or method."); + } + String key = suite + (method == null ? "" : "#" + method); + result.selections.put(key, method == null ? new String[] {(String) suite} : new String[] {(String) suite, (String) method}); + return result; + } + if (!"java.test.fullName".equals(kind) || !(values instanceof List) + || ((List) values).size() > 64 || params.containsKey("suite") || params.containsKey("case")) { + throw invalid("Unsupported or conflicting semantic test selectors."); + } + for (Object value : (List) values) { + if (!(value instanceof String)) throw invalid("A test selector must be a string."); + String identifier = (String) value; + // Surefire can address a method by name, but cannot distinguish + // overloaded signatures. Reject those rather than silently widening. + if (identifier.endsWith("()")) identifier = identifier.substring(0, identifier.length() - 2); + String[] parts = identifier.split("#", -1); + if (parts.length > 2 || !exactName(parts[0], false) + || parts.length == 2 && !exactName(parts[1], true)) { + throw invalid("The semantic test selector cannot be represented as an exact Surefire class or method."); + } + result.selections.put(identifier, parts); + } + return result; + } + + static boolean exactName(String value, boolean method) { + return value.matches(method ? "\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*" + : "\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*(?:\\.\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*)*"); + } + + /** Surefire's parameterized invocations retain one Java method identity. */ + static String reportMethod(String name) { + int paren = name.indexOf('('), bracket = name.indexOf('['); + int end = paren < 0 ? bracket : bracket < 0 ? paren : Math.min(paren, bracket); + if (end <= 0) return name; + String method = name.substring(0, end); + return exactName(method, true) ? method : name; + } + + boolean isFiltered() { return !selections.isEmpty(); } + + String argument() { + List filters = new java.util.ArrayList<>(); + for (String[] selected : selections.values()) { + // Literal/FQN patterns receive **/ in Surefire's ResolvedTest. + // Its public %regex[class#method] form retains the complete class + // path. Parameter suffixes cannot name another Java method. + String filter = Pattern.quote(selected[0].replace('.', java.io.File.separatorChar) + ".class"); + if (selected.length == 2) filter += "#" + Pattern.quote(selected[1]) + "(?:\\(.*\\))?(?:\\[.*\\])?"; + filters.add("%regex[" + filter + "]"); + } + return "-Dtest=" + String.join(",", filters); + } + + /** A dependency's same-named test cannot satisfy the selected project's request. */ + void verify(Map report, String project) { + Set missing = new LinkedHashSet<>(selections.keySet()); + Object values = report.get("tests"); + if (values instanceof List) for (Object value : (List) values) { + Map test = Json.object(value); + if (project != null && !project.equals(test.get("project"))) continue; + for (Map.Entry selected : selections.entrySet()) { + String[] parts = selected.getValue(); + if (parts[0].equals(test.get("suite")) && (parts.length == 1 || parts[1].equals(test.get("case")))) { + missing.remove(selected.getKey()); + } + } + } + if (!missing.isEmpty()) throw new PluginError("maven.noMatchingTests", + "Surefire produced no fresh result in the selected project for one or more semantic test selectors."); + } + + /** Complete suites replace their old methods; a method run cannot clear siblings. */ + void addCoverage(Map report) { + Map covered = new LinkedHashMap<>(); + Object values = report.get("tests"); + if (values instanceof List) for (Object value : (List) values) { + Map test = Json.object(value); + String project = Json.string(test, "project"), suite = Json.string(test, "suite"), method = Json.string(test, "case"); + // An unfiltered UI request can still inherit upstream -Dtest settings. + // Only an explicit typed class selection proves suite coverage. + boolean wholeSuite = false; + for (String[] selected : selections.values()) { + if (selected.length == 1 && selected[0].equals(suite)) wholeSuite = true; + } + Map scope = new LinkedHashMap<>(); + scope.put("project", project); scope.put("suite", suite); + if (!wholeSuite) scope.put("case", method); + covered.put(Json.stringify(scope), scope); + } + report.put("coverage", new java.util.ArrayList<>(covered.values())); + } + + private static PluginError invalid(String message) { return new PluginError("maven.invalidSelection", message); } +} diff --git a/extension/src/main/java/io/github/litheidea/maven/ReportCaptureEvents.java b/extension/src/main/java/io/github/litheidea/maven/ReportCaptureEvents.java index a9b108a..8c31b3c 100644 --- a/extension/src/main/java/io/github/litheidea/maven/ReportCaptureEvents.java +++ b/extension/src/main/java/io/github/litheidea/maven/ReportCaptureEvents.java @@ -46,6 +46,16 @@ public synchronized void beforeMojoExecution(MojoExecutionEvent event) throws Mo Path state = Paths.get(output).toAbsolutePath().normalize().getParent().toRealPath(); Path workspace = Paths.get(event.getSession().getUserProperties().getProperty("lithe.reportWorkspace")).toRealPath(); Path project = event.getProject().getBasedir().toPath().toRealPath(); + String selected = event.getSession().getUserProperties().getProperty("lithe.testProject"); + if (selected != null && !selected.isEmpty() && !project.equals(Paths.get(selected).toRealPath())) { + // Maven's -am must still build prerequisites, but the configured + // Surefire/Failsafe mojo must not run their same-named tests. + // This is the upstream public setter after Maven has applied + // CLI/POM precedence, not a second model/configuration reader. + event.getMojo().getClass().getMethod("setSkipTests", boolean.class).invoke(event.getMojo(), true); + return; + } + if (!project.startsWith(workspace)) throw new IOException("Report project leaves the workspace."); // The actual configured mojo owns interpolation and -D precedence. // Both upstream plugins expose this public getter; there is no POM diff --git a/io.github.lithe-idea.maven-build/plugin.json b/io.github.lithe-idea.maven-build/plugin.json index 42af8f5..0680aec 100644 --- a/io.github.lithe-idea.maven-build/plugin.json +++ b/io.github.lithe-idea.maven-build/plugin.json @@ -4,7 +4,7 @@ "displayName": "Maven", "version": "0.1.1", "pluginAPIVersion": 3, - "requires": { "buildProviders": 8, "buildModelInputs": 1, "buildSystems": 3, "executableResolution": 2, "serverProcess": 1 }, + "requires": { "buildProviders": 9, "buildModelInputs": 1, "buildSystems": 3, "executableResolution": 2, "serverProcess": 1 }, "vendor": { "id": "io.github.lithe-idea", "displayName": "Lithe Community", @@ -182,6 +182,7 @@ "test": { "scopes": ["workspace", "project"], "filters": ["suite", "case"], + "selectorKinds": ["java.test.fullName"], "source": "provider", "arguments": [], "results": { diff --git a/scripts/test-native-core.mjs b/scripts/test-native-core.mjs index 58d0921..af7be2b 100644 --- a/scripts/test-native-core.mjs +++ b/scripts/test-native-core.mjs @@ -45,7 +45,7 @@ await withInterrupts(async (signal) => { state: join(scratch, 'state'), timeoutMs: mavenTimeout() }); await report.step('Core admits the new Maven capability and produces only Provider plans', async () => { coreCommand('plugins.declarative.validate', { manifest }); - assert.equal((await client.initialize(workspace, [8])).capabilities.experimental.litheBuild.version, 8); + assert.equal((await client.initialize(workspace, [9])).capabilities.experimental.litheBuild.version, 9); for (const task of manifest.buildSystems[0].tasks) { assert.equal(task.source, 'provider'); assert.deepEqual(task.arguments, []); } assert.equal(manifest.buildSystems[0].test.source, 'provider'); }); @@ -80,6 +80,85 @@ await withInterrupts(async (signal) => { const progress = client.notifications.filter(message => message.method === 'lithe/build/progress' && message.params.operationID === 'exact-test'); assert.equal(progress.map(message => message.params.output ?? '').join(''), result.output); }); + await report.step('Core forwards semantic test identities and Maven reports the exact selected method', async () => { + const selectors = ['demo.core.GreeterTest#greetsByName()']; + const plan = build('build.testPlan', planned({ project, selectorKind: 'java.test.fullName', selectors, userArguments: [] })).plan; + assert.deepEqual(plan.provider.params.selectors, selectors); + assert.equal(plan.provider.params.suite, undefined); + const result = await send(plan, 'semantic-test'); + assert.equal(result.exitCode, 0, result.output); + const decoded = build('build.decodeTestResults', { workspaceRoot: workspace, root, project: project.path, + projects: model.projects.map(value => value.path), result: result.testResults }).results; + assert.equal(decoded.summary.total, 1); + assert.equal(decoded.tests[0].case, 'greetsByName'); + assert.equal(decoded.tests[0].project, 'nested/core'); + }); + await report.step('Unicode Java class and method identities survive the full Core Maven report roundtrip', async () => { + const source = join(workspace, root, 'core/src/test/java/demo/core/测试.java'); + try { + writeFileSync(source, 'package demo.core; public class 测试 { @org.junit.Test public void 校验() { org.junit.Assert.assertTrue(true); } }'); + const plan = build('build.testPlan', planned({ project, selectorKind: 'java.test.fullName', selectors: ['demo.core.测试#校验()'] })).plan; + const result = await send(plan, 'unicode-semantic-test'); + assert.equal(result.exitCode, 0, result.output); + const decoded = build('build.decodeTestResults', { workspaceRoot: workspace, root, project: project.path, result: result.testResults }).results; + assert.equal(decoded.summary.total, 1); + assert.equal(decoded.tests[0].suite, 'demo.core.测试'); + assert.equal(decoded.tests[0].case, '校验'); + } finally { rmSync(source, { force: true }); } + }); + await report.step('an exact class cannot execute a different package with the same class-path suffix', async () => { + const directory = join(workspace, root, 'core/src/test/java/other/demo/core'); + const source = join(directory, 'GreeterTest.java'); + mkdirSync(directory, { recursive: true }); + try { + writeFileSync(source, 'package other.demo.core; public class GreeterTest { @org.junit.Test public void greetsByName() { org.junit.Assert.fail("wrong package executed"); } }'); + const plan = build('build.testPlan', planned({ project, selectorKind: 'java.test.fullName', selectors: ['demo.core.GreeterTest'] })).plan; + const result = await send(plan, 'exact-package-test'); + assert.equal(result.exitCode, 0, result.output); + assert.deepEqual([...new Set(result.testResults.tests.map(value => value.suite))], ['demo.core.GreeterTest']); + assert.deepEqual(result.testResults.coverage, [{ project: 'nested/core', suite: 'demo.core.GreeterTest' }]); + } finally { rmSync(source, { force: true }); } + }); + await report.step('parameterized invocations preserve the method selector, severity, count and total duration', async () => { + const source = join(workspace, root, 'core/src/test/java/demo/core/ParameterizedTest.java'); + try { + writeFileSync(source, `package demo.core; @org.junit.runner.RunWith(org.junit.runners.Parameterized.class) + public class ParameterizedTest { + @org.junit.runners.Parameterized.Parameters public static java.util.Collection inputs() { + return java.util.Arrays.asList(new Object[][] {{1}, {2}}); } + public ParameterizedTest(int value) {} @org.junit.Test public void checks() { org.junit.Assert.assertTrue(true); } + }`); + const plan = build('build.testPlan', planned({ project, selectorKind: 'java.test.fullName', selectors: ['demo.core.ParameterizedTest#checks()'] })).plan; + const result = await send(plan, 'parameterized-method-test'); + assert.equal(result.exitCode, 0, result.output); + const decoded = build('build.decodeTestResults', { workspaceRoot: workspace, root, project: project.path, result: result.testResults }).results; + assert.equal(decoded.summary.total, 1); + assert.equal(decoded.tests[0].case, 'checks'); + assert.equal(decoded.tests[0].invocations, 2); + assert.equal(decoded.tests[0].durationMillis, result.testResults.tests.reduce((sum, test) => sum + test.durationMillis, 0)); + } finally { rmSync(source, { force: true }); } + }); + await report.step('project selection builds prerequisites without running their identical test class', async () => { + const coreSource = join(workspace, root, 'core/src/test/java/demo/core/GreeterTest.java'); + const original = readFileSync(coreSource, 'utf8'); + const directory = join(workspace, root, 'app/src/test/java/demo/core'); + const appSource = join(directory, 'GreeterTest.java'); + const appPom = join(workspace, root, 'app/pom.xml'); + const originalPom = readFileSync(appPom, 'utf8'); + mkdirSync(directory, { recursive: true }); + try { + writeFileSync(coreSource, original.replace(/}\s*$/, '@org.junit.Test public void scopedMethod() { org.junit.Assert.fail("dependency test executed"); } }')); + writeFileSync(appPom, originalPom.replace('', 'junitjunit4.13.2test')); + writeFileSync(appSource, 'package demo.core; public class GreeterTest { @org.junit.Test public void scopedMethod() { org.junit.Assert.assertTrue(true); } }'); + const app = model.projects.find(value => value.name === 'app'); + const plan = build('build.testPlan', planned({ project: app, selectorKind: 'java.test.fullName', + selectors: ['demo.core.GreeterTest#scopedMethod()'], userArguments: ['-Dtest=*', '-DskipTests=false'] })).plan; + const result = await send(plan, 'exact-project-test'); + assert.equal(result.exitCode, 0, result.output); + assert.deepEqual(result.testResults.tests.map(value => [value.project, value.suite, value.case]), + [['nested/app', 'demo.core.GreeterTest', 'scopedMethod']]); + } finally { writeFileSync(coreSource, original); writeFileSync(appPom, originalPom); rmSync(appSource, { force: true }); } + }); await report.step('an unknown method cannot pass with a fresh empty Surefire report', async () => { const plan = build('build.testPlan', planned({ project, suite: 'demo.core.GreeterTest', case: 'doesNotExist', userArguments: [] })).plan; await assert.rejects(send(plan, 'unknown-test'), /no fresh result/); @@ -148,6 +227,7 @@ await withInterrupts(async (signal) => { delete consumer.buildSystems[0].modelSharing; delete consumer.buildSystems[0].configuration; delete consumer.buildSystems[0].test.results; + delete consumer.buildSystems[0].test.selectorKinds; consumer.buildSystems[0].modelInputs = [{ pluginID: id, buildSystemID: 'maven' }]; const snapshot = coreCommand('build.resolveModelInputs', { manifest: consumer, buildSystemID: 'maven', request: { revision: 11, sources: [{ manifest, instances: [{ buildSystemID: 'maven', root, state: 'ready', model, options }] }] } }).modelInputs; @@ -161,6 +241,26 @@ await withInterrupts(async (signal) => { const plan = coreCommand('build.modelPlan', { manifest: consumer, buildSystemID: 'maven', request: planned({ modelInputs: snapshot }) }).plan; assert.deepEqual(plan.provider.params.modelInputs, snapshot); }); + await report.step('a module opened as the workspace retains the dot project identity', async () => { + const module = join(workspace, root, 'core'); + const standalone = new BackendClient({ java: process.env.LITHE_TEST_JAVA ?? 'java', jar: join(pkg, 'lib/lithe-maven-backend.jar'), + state: join(scratch, 'module-state'), timeoutMs: mavenTimeout() }); + try { + await standalone.initialize(module, [9]); + const plan = build('build.testPlan', { root: '.', options: {}, project: { name: 'core', path: '.' }, + selectorKind: 'java.test.fullName', selectors: ['demo.core.GreeterTest#greetsByName()'] }).plan; + const result = await standalone.request(plan.provider.method, { ...plan.provider.params, + tool: { executable: maven }, operationID: 'module-workspace-test' }); + assert.equal(result.exitCode, 0, result.output); + const decoded = build('build.decodeTestResults', { workspaceRoot: module, root: '.', project: '.', result: result.testResults }).results; + assert.equal(decoded.summary.total, 1); + assert.equal(decoded.tests[0].project, '.'); + assert.equal(decoded.tests[0].case, 'greetsByName'); + } finally { + standalone.kill(); + await bounded(standalone.exited, 'module backend cleanup'); + } + }); await report.step('close the backend and preserve the entire plugin package', async () => { assert.equal(await client.close(), 0); assert.deepEqual(bundleManifest(pkg), before); diff --git a/scripts/test-native.mjs b/scripts/test-native.mjs index 65c7085..86b42e8 100644 --- a/scripts/test-native.mjs +++ b/scripts/test-native.mjs @@ -24,8 +24,8 @@ const clients = new Set(); const report = createReport('native-maven'); const runs = () => existsSync(log) ? readFileSync(log, 'utf8').trim().split('\n').filter(Boolean).map(JSON.parse) : []; const executionRuns = () => runs().filter(run => !run.argv.includes('pre-clean')).map(run => ({ ...run, - instrumentation: run.argv.filter(arg => ['-Dmaven.ext.class.path=', '-Dlithe.reportOutput=', '-Dlithe.reportWorkspace='].some(prefix => arg.startsWith(prefix))), - argv: run.argv.filter(arg => !['-Dmaven.ext.class.path=', '-Dlithe.reportOutput=', '-Dlithe.reportWorkspace='].some(prefix => arg.startsWith(prefix))), + instrumentation: run.argv.filter(arg => ['-Dmaven.ext.class.path=', '-Dlithe.reportOutput=', '-Dlithe.reportWorkspace=', '-Dlithe.testProject='].some(prefix => arg.startsWith(prefix))), + argv: run.argv.filter(arg => !['-Dmaven.ext.class.path=', '-Dlithe.reportOutput=', '-Dlithe.reportWorkspace=', '-Dlithe.testProject='].some(prefix => arg.startsWith(prefix))), })); const control = value => writeFileSync(controlFile, JSON.stringify(value)); const alive = pid => { try { process.kill(pid, 0); return true; } catch (error) { if (error.code === 'ESRCH') return false; throw error; } }; @@ -40,12 +40,13 @@ async function until(condition, description) { const params = (extra = {}) => ({ buildSystemID: 'maven', root: 'nested', options: {}, optionArguments: [], environment: {}, tool: { executable }, userArguments: [], ...extra }); const selected = { name: 'core', path: 'nested/core' }; +const exact = (suite, method) => '-Dtest=%regex[\\Q' + suite.replaceAll('.', '/') + '.class\\E#\\Q' + method + '\\E(?:\\(.*\\))?(?:\\[.*\\])?]'; async function start() { const client = new BackendClient({ java: process.env.LITHE_TEST_JAVA ?? 'java', jar: join(pkg, 'lib/lithe-maven-backend.jar'), state, javaOptions: [`-Duser.home=${join(scratch, 'home')}`], env: { ...process.env, FAKE_MAVEN_CONTROL: controlFile, FAKE_MAVEN_LOG: log } }); clients.add(client); - assert.equal((await client.initialize(workspace, [8])).capabilities.experimental.litheBuild.version, 8); + assert.equal((await client.initialize(workspace, [9])).capabilities.experimental.litheBuild.version, 9); return client; } await withInterrupts(async (signal) => { @@ -72,7 +73,7 @@ await withInterrupts(async (signal) => { assert.equal(result.exitCode, 0); const run = executionRuns().at(-1); assert.equal(run.cwd, root); - assert.equal(run.instrumentation.length, 3); + assert.equal(run.instrumentation.length, 4); assert.ok(run.instrumentation.some(arg => arg.startsWith('-Dlithe.reportOutput=' + state + '/execution-'))); assert.deepEqual(result.testResults.tests, []); assert.deepEqual(run.argv, ['-B', '-ntp', '-Pci', '-s', '/fixture settings.xml', '-Dmaven.repo.local=/fixture repository', '-o', '-DskipTests', '-pl', 'core', 'package', '-Dmessage=two words']); @@ -96,14 +97,30 @@ await withInterrupts(async (signal) => { assert.equal(result.exitCode, 0); assert.equal(result.testResults.tests[0].suite, 'demo.core.GreeterTest'); assert.equal(result.testResults.tests[0].project, 'nested/core'); - assert.deepEqual(executionRuns().at(-1).argv, ['-B', '-ntp', '-pl', 'core', '-am', '-Dtest=demo.core.GreeterTest#greets', '-Dsurefire.failIfNoSpecifiedTests=false', 'test']); + assert.deepEqual(executionRuns().at(-1).argv, ['-B', '-ntp', '-pl', 'core', '-am', 'test', exact('demo.core.GreeterTest', 'greets'), '-Dsurefire.failIfNoSpecifiedTests=false']); const count = executionRuns().length; await assert.rejects(client.request('lithe/build/test', params({ project: selected, suite: '*', operationID: 'wildcard' })), /exact Surefire/); await assert.rejects(client.request('lithe/build/test', params({ project: selected, case: 'greets', operationID: 'no-suite' })), /needs its suite/); assert.equal(executionRuns().length, count); }); + await report.step('opaque JDT identities reach Surefire exactly and reject unsupported or missing selections', async () => { + const result = await client.request('lithe/build/test', params({ project: selected, + selectorKind: 'java.test.fullName', selectors: ['demo.core.GreeterTest#greets()'], operationID: 'semantic-test' })); + assert.equal(result.exitCode, 0); + assert.ok(executionRuns().at(-1).argv.includes(exact('demo.core.GreeterTest', 'greets'))); + await client.request('lithe/build/test', params({ project: selected, + selectorKind: 'java.test.fullName', selectors: ['示例.测试#校验()'], operationID: 'unicode-semantic-test' })); + assert.ok(executionRuns().at(-1).argv.includes(exact('示例.测试', '校验'))); + + for (const selectors of [['*'], ['demo.core.GreeterTest#greets(java.lang.String)']]) { + await assert.rejects(client.request('lithe/build/test', params({ project: selected, + selectorKind: 'java.test.fullName', selectors, operationID: 'invalid-semantic-test' }))); + } + }); await report.step('an old or empty Surefire report cannot make an unknown selector pass', async () => { control({ execution: { noReport: true } }); + await assert.rejects(client.request('lithe/build/test', params({ project: selected, selectorKind: 'java.test.fullName', + selectors: ['demo.core.GreeterTest#greets()'], operationID: 'stale-semantic-test' })), /no fresh result/); await assert.rejects(client.request('lithe/build/test', params({ project: selected, suite: 'demo.core.GreeterTest', case: 'greets', operationID: 'stale-test' })), /no fresh result/); control({}); @@ -114,6 +131,12 @@ await withInterrupts(async (signal) => { operationID: 'wrong-package-test' })), /no fresh result/); control({}); }); + await report.step('another reactor project cannot satisfy an exact report-derived test selection', async () => { + control({ execution: { reportProject: 'nested/app' } }); + await assert.rejects(client.request('lithe/build/test', params({ project: selected, suite: 'demo.core.GreeterTest', + case: 'greets', operationID: 'wrong-project-report' })), /no fresh result/); + control({}); + }); await report.step('malformed or external-entity reports fail closed and release operation state', async () => { for (const badReport of ['broken', 'external-entity']) { control({ execution: { badReport } }); diff --git a/test/fixtures/fake-maven-backend.mjs b/test/fixtures/fake-maven-backend.mjs index dd1f6d7..03fceb0 100644 --- a/test/fixtures/fake-maven-backend.mjs +++ b/test/fixtures/fake-maven-backend.mjs @@ -48,7 +48,10 @@ if (!exporting) { console.log("[WARNING] " + join(process.cwd(), "core/src/main/java/demo/core/Greeter.java") + ":[1,1] test diagnostic"); const selector = argv.find(argument => argument.startsWith("-Dtest="))?.slice(7); if (selector && !control.noReport) { - const [selectedSuite, method = "greets"] = selector.split("#"); + const quoted = /^%regex\[\\Q(.+?)\\E(?:#\\Q(.+?)\\E.*?)?\]$/.exec(selector); + const [selectedSuite, method = "greets"] = quoted + ? [quoted[1].replace(/\.class$/, '').replaceAll('/', '.'), quoted[2]] + : selector.split("#"); const suite = control.reportSuite ?? selectedSuite; const directory = join(process.cwd(), "core/target/surefire-reports"); mkdirSync(directory, { recursive: true }); @@ -60,7 +63,7 @@ if (!exporting) { const file = join(dirname(value("lithe.reportOutput")), 'report-0.xml'); writeFileSync(file, xml); writeFileSync(value("lithe.reportOutput"), JSON.stringify({ format: 'litheMavenOperationReports', version: 1, - reports: [{ file: 'report-0.xml', project: relative(value("lithe.reportWorkspace"), join(process.cwd(), 'core')), + reports: [{ file: 'report-0.xml', project: control.reportProject ?? relative(value("lithe.reportWorkspace"), join(process.cwd(), 'core')), sha256: createHash('sha256').update(xml).digest('hex') }] })); } } From 6d110411ce023be6e965d04ac34abb8cc8e87091 Mon Sep 17 00:00:00 2001 From: wgw Date: Thu, 29 Oct 2026 14:29:48 +0800 Subject: [PATCH 07/24] feat(maven): own Java run resource preparation in provider tasks --- README.md | 5 ++++ .../maven/backend/MavenExecution.java | 9 ++++++- io.github.lithe-idea.maven-build/plugin.json | 18 ++++++++++++++ scripts/test-native-core.mjs | 24 +++++++++++++++++++ scripts/test-native.mjs | 12 ++++++++++ 5 files changed, 67 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ba04d00..49d77e1 100644 --- a/README.md +++ b/README.md @@ -268,3 +268,8 @@ Maven 后端才把类或 `类#方法()` 映射成 Surefire 的精确选择器; 区分工程和覆盖范围,整类重跑才能移除该类过时的方法结果。`-am` 仍编译依赖, 已配置的测试 Mojo 通过公开 setter 跳过未选工程;原始 `-Dtest=*` 不会扩大类型化选择。 没有明确整类选择时,继承的上游筛选可能仍有效,所以只声明报告中返回的方法覆盖。 + +Java 启动前的公开项目任务 `java-prepare-run-main`/`java-prepare-run-test` +分别通过 Maven 的 `resources:resources`,或再加 `resources:testResources` 处理资源。 +自定义目录、过滤和 Profile 由当前 Maven 模型处理;依赖仍按 `-am` 参与,不在宿主 +重新解析 POM。任务需要当前工程且不接受附加目标,失败或取消不能作为启动成功。 diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecution.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecution.java index edeff96..cd6594b 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecution.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecution.java @@ -29,10 +29,13 @@ private MavenExecution() {} static Map run(Map params, CallContext context, Path root, Path workspace, Path maven, Map environment, MavenRuns.Loaded loaded, boolean tests, Path extension, Path state) throws Exception { String task = tests ? "test" : Json.string(params, "task"); - if (!tests && !LIFECYCLE.contains(task) && !"plugin-goal".equals(task) && !"goal".equals(task)) { + boolean prepareMain = "java-prepare-run-main".equals(task), prepareTest = "java-prepare-run-test".equals(task); + if (!tests && !prepareMain && !prepareTest && !LIFECYCLE.contains(task) && !"plugin-goal".equals(task) && !"goal".equals(task)) { throw invalid("Unknown Maven task."); } Path project = selectedProject(params.get("project"), root, workspace, loaded); + if ((prepareMain || prepareTest) && (project == null || params.get("modelTask") != null + || !strings(params.get("userArguments")).isEmpty())) throw invalid("Java resource preparation needs one current project and no raw goals."); if (params.get("target") != null) throw invalid("Maven tasks do not accept a target selector."); List command = new ArrayList<>(); command.add(maven.toString()); @@ -49,6 +52,10 @@ static Map run(Map params, CallContext context, if (project != null && !project.equals(root)) command.add("-am"); } command.add("test"); + } else if (prepareMain || prepareTest) { + if (!project.equals(root)) command.add("-am"); + command.add("resources:resources"); + if (prepareTest) command.add("resources:testResources"); } else if ("plugin-goal".equals(task)) { command.add(pluginGoal(params.get("modelTask"), project, root, loaded)); } else if (!"goal".equals(task)) { diff --git a/io.github.lithe-idea.maven-build/plugin.json b/io.github.lithe-idea.maven-build/plugin.json index 0680aec..3dcca1b 100644 --- a/io.github.lithe-idea.maven-build/plugin.json +++ b/io.github.lithe-idea.maven-build/plugin.json @@ -79,6 +79,24 @@ "configuration": { "source": "provider" }, "modelSharing": { "options": ["profiles", "offline", "skipTests"] }, "tasks": [ + { + "id": "java-prepare-run-main", + "displayName": "resources:resources", + "group": "build", + "category": ["Lifecycle"], + "scopes": ["project"], + "source": "provider", + "arguments": [] + }, + { + "id": "java-prepare-run-test", + "displayName": "resources:resources + resources:testResources", + "group": "build", + "category": ["Lifecycle"], + "scopes": ["project"], + "source": "provider", + "arguments": [] + }, { "id": "clean", "displayName": "clean", diff --git a/scripts/test-native-core.mjs b/scripts/test-native-core.mjs index af7be2b..ba24b8d 100644 --- a/scripts/test-native-core.mjs +++ b/scripts/test-native-core.mjs @@ -67,6 +67,30 @@ await withInterrupts(async (signal) => { const decoded = build('build.decodeDiagnostics', { workspaceRoot: workspace, root, output: result.output }); assert.deepEqual(decoded.diagnostics, []); }); + await report.step('Java preparation preserves Maven filtering, custom roots and main versus test resources', async () => { + const directory = join(workspace, root, 'core'); + const pom = join(directory, 'pom.xml'); + const original = readFileSync(pom, 'utf8'); + const resources = join(directory, 'custom inputs'), testResources = join(directory, 'test inputs'); + mkdirSync(resources); mkdirSync(testResources); + writeFileSync(join(resources, 'runtime.properties'), 'selected=${prepared.value}'); + writeFileSync(join(testResources, 'test.properties'), 'test=${prepared.value}'); + try { + writeFileSync(pom, original.replace('', `custom inputstrue + test inputstrue + preparedupstream`)); + const plan = task => build('build.taskPlan', planned({ task, project, options: { profiles: ['prepared'] } })).plan; + const main = await send(plan('java-prepare-run-main'), 'prepare-main-resources'); + assert.equal(main.exitCode, 0, main.output); + assert.equal(readFileSync(join(directory, 'target/classes/runtime.properties'), 'utf8'), 'selected=upstream'); + assert.equal(existsSync(join(directory, 'target/test-classes/test.properties')), false); + const tests = await send(plan('java-prepare-run-test'), 'prepare-test-resources'); + assert.equal(tests.exitCode, 0, tests.output); + assert.equal(readFileSync(join(directory, 'target/test-classes/test.properties'), 'utf8'), 'test=upstream'); + await assert.rejects(send(build('build.taskPlan', planned({ task: 'java-prepare-run-main', project, userArguments: ['verify'] })).plan, + 'reject-extra-resource-goals'), /no raw goals/); + } finally { writeFileSync(pom, original); rmSync(resources, { recursive: true, force: true }); rmSync(testResources, { recursive: true, force: true }); } + }); await report.step('Core and Surefire run one exact method and decode one report result', async () => { testPlan = build('build.testPlan', planned({ project, suite: 'demo.core.GreeterTest', case: 'greetsByName', userArguments: [] })).plan; assert.equal(testPlan.provider.method, 'lithe/build/test'); diff --git a/scripts/test-native.mjs b/scripts/test-native.mjs index 86b42e8..f503628 100644 --- a/scripts/test-native.mjs +++ b/scripts/test-native.mjs @@ -81,6 +81,18 @@ await withInterrupts(async (signal) => { assert.equal(progress.map(message => message.params.output ?? '').join(''), result.output); assert.match(result.output, /\[WARNING\]/); }); + await report.step('Java resource tasks preserve effective options and refuse missing projects or injected goals', async () => { + for (const [task, goals] of [['java-prepare-run-main', ['resources:resources']], + ['java-prepare-run-test', ['resources:resources', 'resources:testResources']]]) { + const result = await client.request('lithe/build/execute', params({ task, project: selected, options: { profiles: ['ci'] }, operationID: task })); + assert.equal(result.exitCode, 0); + assert.deepEqual(executionRuns().at(-1).argv, ['-B', '-ntp', '-Pci', '-pl', 'core', '-am', ...goals]); + const count = executionRuns().length; + await assert.rejects(client.request('lithe/build/execute', params({ task, operationID: task + '-no-project' })), /current project/); + await assert.rejects(client.request('lithe/build/execute', params({ task, project: selected, userArguments: ['verify'], operationID: task + '-raw' })), /no raw goals/); + assert.equal(executionRuns().length, count); + } + }); await report.step('model goals are checked against the current Maven extension output', async () => { const modelTask = { name: 'compiler:compile', path: 'nested/core', properties: { goal: 'org.apache.maven.plugins:maven-compiler-plugin:3.13.0:compile' } }; const result = await client.request('lithe/build/execute', params({ task: 'plugin-goal', project: selected, modelTask, operationID: 'goal' })); From ab1b349e69a665786ff05b581af14b29c1a8dbc0 Mon Sep 17 00:00:00 2001 From: wgw Date: Fri, 30 Oct 2026 08:48:52 +0800 Subject: [PATCH 08/24] feat(maven): export frameworks from effective applied plugins --- README.md | 6 +++++ .../github/litheidea/maven/ModelExport.java | 24 +++++++++++++++++ scripts/core-client.mjs | 4 +-- scripts/test-native-core.mjs | 27 +++++++++++++++++++ 4 files changed, 59 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 49d77e1..cb23a35 100644 --- a/README.md +++ b/README.md @@ -273,3 +273,9 @@ Java 启动前的公开项目任务 `java-prepare-run-main`/`java-prepare-run- 分别通过 Maven 的 `resources:resources`,或再加 `resources:testResources` 处理资源。 自定义目录、过滤和 Profile 由当前 Maven 模型处理;依赖仍按 `-am` 参与,不在宿主 重新解析 POM。任务需要当前工程且不接受附加目标,失败或取消不能作为启动成功。 + +Maven 生效模型现在在每个工程发布 `run.modelVersion: "1"`;实际应用 Spring Boot、 +Quarkus 或 Micronaut 插件的非聚合工程还发布 `run.provider`。识别使用 Maven 的 +`getBuildPlugins()`,包含生效 Profile 和继承,只有 pluginManagement 时不会误报。 +宿主依据这些事实生成兼容的服务配置,不再解析 POM 判断框架;框架的既有启动规划 +仍在迁移中,不能把这个模型元数据等同于新的 Provider 服务启动接口。 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 dd489ee..88705f5 100644 --- a/extension/src/main/java/io/github/litheidea/maven/ModelExport.java +++ b/extension/src/main/java/io/github/litheidea/maven/ModelExport.java @@ -73,6 +73,9 @@ Map document() { properties.put("artifactId", project.getArtifactId()); properties.put("version", project.getVersion()); properties.put("packaging", project.getPackaging()); + properties.put("run.modelVersion", "1"); + String provider = runProvider(project); + if (provider != null) properties.put("run.provider", provider); entry.put("properties", properties); projects.add(entry); if (!"pom".equals(project.getPackaging())) { @@ -112,6 +115,27 @@ private Map aggregators() { return result; } + /** Effective build plugins include active profiles and inherited plugins. + * Plugin management alone does not apply a plugin. Coordinate precedence + * preserves the host's existing service identity if several are applied. + */ + private static String runProvider(MavenProject project) { + if ("pom".equals(project.getPackaging())) return null; + String[][] providers = { + {"org.springframework.boot", "spring-boot-maven-plugin", "spring-boot.maven"}, + {"io.quarkus", "quarkus-maven-plugin", "quarkus.maven"}, + {"io.quarkus.platform", "quarkus-maven-plugin", "quarkus.maven"}, + {"io.micronaut.build", "micronaut-maven-plugin", "micronaut.maven"}, + {"io.micronaut.maven", "micronaut-maven-plugin", "micronaut.maven"} + }; + for (String[] provider : providers) { + for (Plugin plugin : project.getBuildPlugins()) { + if (provider[0].equals(plugin.getGroupId()) && provider[1].equals(plugin.getArtifactId())) return provider[2]; + } + } + return null; + } + private void addContentRoots(MavenProject project, String owner, List roots) { File basedir = project.getBasedir(); for (String root : project.getCompileSourceRoots()) { diff --git a/scripts/core-client.mjs b/scripts/core-client.mjs index db7c6c4..3a4644d 100644 --- a/scripts/core-client.mjs +++ b/scripts/core-client.mjs @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; -export function coreCommand(command, payload) { +export function coreCommand(command, payload, expectedStatus = 'ok') { if (!process.env.LITHE_CORE_LIBRARY) throw new Error('Set LITHE_CORE_LIBRARY to the current host Core dynamic library.'); const result = spawnSync(process.env.PYTHON ?? 'python3', [fileURLToPath(new URL('./core-command.py', import.meta.url)), process.env.LITHE_CORE_LIBRARY], { input: JSON.stringify({ id: 'maven-integration', command, payload }), encoding: 'utf8', timeout: 15000, maxBuffer: 32 * 1024 * 1024, @@ -10,6 +10,6 @@ export function coreCommand(command, payload) { assert.equal(result.status, 0, result.error?.message ?? result.stderr); const envelope = JSON.parse(result.stdout); assert.equal(envelope.ok, true, JSON.stringify(envelope)); - assert.equal(envelope.data.status, 'ok', JSON.stringify(envelope.data)); + if (expectedStatus !== null) assert.equal(envelope.data.status, expectedStatus, JSON.stringify(envelope.data)); return envelope.data; } diff --git a/scripts/test-native-core.mjs b/scripts/test-native-core.mjs index ba24b8d..11e9cf3 100644 --- a/scripts/test-native-core.mjs +++ b/scripts/test-native-core.mjs @@ -56,6 +56,33 @@ await withInterrupts(async (signal) => { assert.deepEqual(model.projects.map(project => project.name).sort(), ['app', 'core', 'reactor']); assert.ok(model.contentRoots.some(content => content.path === 'nested/core/src/main/java')); }); + await report.step('effective Profile and inherited plugins own framework Run generation without host POM parsing', async () => { + const pom = join(workspace, root, 'pom.xml'); + const original = readFileSync(pom, 'utf8'); + try { + writeFileSync(pom, original.replace('', ` + org.springframework.bootspring-boot-maven-plugin0.0.0-fixture + `).replace('', `framework + io.quarkus.platformquarkus-maven-plugin0.0.0-fixture + `)); + const read = async profiles => build('build.decodeModel', { workspaceRoot: workspace, root, + result: await send(build('build.modelPlan', planned({ options: { profiles, offline: true } })).plan, 'framework-model') }).model; + const inactive = await read([]); + assert.ok(inactive.projects.every(project => project.properties['run.modelVersion'] === '1')); + assert.ok(inactive.projects.every(project => project.properties['run.provider'] === undefined), 'plugin management alone is not an applied framework'); + const active = await read(['framework']); + assert.equal(active.projects.find(project => project.name === 'reactor').properties['run.provider'], undefined, 'aggregators are not services'); + assert.ok(active.projects.filter(project => project.name !== 'reactor').every(project => project.properties['run.provider'] === 'quarkus.maven'), 'Maven applies the inherited active Profile'); + const ownership = active.projects.map(project => ({ path: project.path, name: project.name, mavenReactorPath: root, + mavenRunProvider: project.properties['run.provider'], contentRoots: [] })); + writeFileSync(pom, ''); + const generated = coreCommand('runConfig.generate', { root: workspace, paths: [], javaEntrypoints: { schemaVersion: 1, entries: [], diagnostics: [] }, projectOwnership: ownership }, null); + assert.deepEqual(generated.generated.configurations.map(item => item.id).sort(), ['quarkus.maven:nested/app', 'quarkus.maven:nested/core']); + for (const item of generated.generated.configurations) { + assert.equal(item.cwd, root); assert.equal(item.execution, 'service'); + } + } finally { writeFileSync(pom, original); } + }); const project = model.projects.find(project => project.name === 'core'); await report.step('Core plans a module build, Maven executes it, and the class file exists', async () => { compilePlan = build('build.taskPlan', planned({ task: 'compile', project })).plan; From 072960cc2ef92a535b8c13c346f8fe7c1c88f2ac Mon Sep 17 00:00:00 2001 From: wgw Date: Fri, 30 Oct 2026 09:01:05 +0800 Subject: [PATCH 09/24] feat(maven): export compiler requirements from upstream execution plans --- README.md | 4 ++ .../litheidea/maven/CompilerRequirements.java | 70 +++++++++++++++++++ .../maven/LitheLifecycleParticipant.java | 8 ++- .../github/litheidea/maven/ModelExport.java | 7 +- scripts/test-native-core.mjs | 42 +++++++++++ scripts/test.mjs | 2 + 6 files changed, 130 insertions(+), 3 deletions(-) create mode 100644 extension/src/main/java/io/github/litheidea/maven/CompilerRequirements.java diff --git a/README.md b/README.md index cb23a35..979192d 100644 --- a/README.md +++ b/README.md @@ -279,3 +279,7 @@ Quarkus 或 Micronaut 插件的非聚合工程还发布 `run.provider`。识别 `getBuildPlugins()`,包含生效 Profile 和继承,只有 pluginManagement 时不会误报。 宿主依据这些事实生成兼容的服务配置,不再解析 POM 判断框架;框架的既有启动规划 仍在迁移中,不能把这个模型元数据等同于新的 Provider 服务启动接口。 + +`java.minimumVersion` 来自 Maven 的实际编译执行计划和参数解析器,涵盖 Profile、 +继承、测试编译和自定义 compiler execution;只计算不执行。无法解析时记录诊断并 +保持未知,宿主不得回退到 POM 正则;插件仍以 Maven 3.6.3 API 和 Java 8 构建。 diff --git a/extension/src/main/java/io/github/litheidea/maven/CompilerRequirements.java b/extension/src/main/java/io/github/litheidea/maven/CompilerRequirements.java new file mode 100644 index 0000000..08942c7 --- /dev/null +++ b/extension/src/main/java/io/github/litheidea/maven/CompilerRequirements.java @@ -0,0 +1,70 @@ +package io.github.litheidea.maven; + +import java.util.Collections; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.lifecycle.internal.LifecycleExecutionPlanCalculator; +import org.apache.maven.lifecycle.internal.LifecycleTask; +import org.apache.maven.plugin.MojoExecution; +import org.apache.maven.plugin.PluginParameterExpressionEvaluator; +import org.apache.maven.project.MavenProject; +import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Reads configured compiler parameters from Maven's own execution plan. + * No goal is executed and no POM interpretation is duplicated in the host. + */ +final class CompilerRequirements { + private static final Logger LOG = LoggerFactory.getLogger(CompilerRequirements.class); + + static String minimumJava(MavenSession session, MavenProject project, LifecycleExecutionPlanCalculator plans) { + if ("pom".equals(project.getPackaging())) return null; + MavenSession selected = session.clone(); + selected.setCurrentProject(project); + int minimum = 0; + try { + for (MojoExecution execution : plans.calculateExecutionPlan(selected, project, + Collections.singletonList(new LifecycleTask("test-compile")), true).getMojoExecutions()) { + if (!"org.apache.maven.plugins".equals(execution.getGroupId()) + || !"maven-compiler-plugin".equals(execution.getArtifactId()) + || !("compile".equals(execution.getGoal()) || "testCompile".equals(execution.getGoal()))) continue; + PluginParameterExpressionEvaluator evaluator = new PluginParameterExpressionEvaluator(selected, execution); + boolean test = "testCompile".equals(execution.getGoal()); + String release = value(execution, evaluator, test ? "testRelease" : "release"); + if (test && release == null) release = value(execution, evaluator, "release"); + int required; + if (release != null) required = feature(release); + else { + String source = value(execution, evaluator, test ? "testSource" : "source"); + String target = value(execution, evaluator, test ? "testTarget" : "target"); + if (test && source == null) source = value(execution, evaluator, "source"); + if (test && target == null) target = value(execution, evaluator, "target"); + required = Math.max(source == null ? 0 : feature(source), target == null ? 0 : feature(target)); + } + minimum = Math.max(minimum, required); + } + return minimum == 0 ? null : Integer.toString(minimum); + } catch (Exception error) { + // Unavailable plugin descriptors or unresolved expressions leave the + // requirement unknown. They must never trigger a second POM parser. + LOG.warn("Lithe could not determine Java compiler requirements for {}: {}", project.getArtifactId(), error.getMessage()); + return null; + } + } + + private static String value(MojoExecution execution, PluginParameterExpressionEvaluator evaluator, String name) throws Exception { + Xpp3Dom configuration = execution.getConfiguration(); + Xpp3Dom parameter = configuration == null ? null : configuration.getChild(name); + if (parameter == null) return null; + Object value = evaluator.evaluate(parameter.getValue()); + if (value == null) value = evaluator.evaluate(parameter.getAttribute("default-value")); + return value == null || value.toString().trim().isEmpty() ? null : value.toString().trim(); + } + + private static int feature(String version) { + if (!version.matches("(?:1\\.)?[0-9]+")) throw new IllegalArgumentException("Unresolved compiler language version"); + int value = Integer.parseInt(version.startsWith("1.") ? version.substring(2) : version); + if (value < 1 || value > 999) throw new IllegalArgumentException("Compiler language version is out of bounds"); + return value; + } +} 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 a803802..1b736f6 100644 --- a/extension/src/main/java/io/github/litheidea/maven/LitheLifecycleParticipant.java +++ b/extension/src/main/java/io/github/litheidea/maven/LitheLifecycleParticipant.java @@ -11,6 +11,7 @@ import org.apache.maven.AbstractMavenLifecycleParticipant; import org.apache.maven.MavenExecutionException; import org.apache.maven.execution.MavenSession; +import org.apache.maven.lifecycle.internal.LifecycleExecutionPlanCalculator; import org.apache.maven.plugin.MavenPluginManager; import org.apache.maven.plugin.version.PluginVersionResolver; import org.apache.maven.project.ProjectDependenciesResolver; @@ -34,6 +35,7 @@ public final class LitheLifecycleParticipant extends AbstractMavenLifecycleParti static final String DEPENDENCIES_PROJECT = "lithe.dependenciesProject"; private final MavenPluginManager pluginManager; + private final LifecycleExecutionPlanCalculator executionPlans; private final PluginVersionResolver versionResolver; private final ProjectDependenciesResolver dependenciesResolver; private final NativeSettingsEvents settingsEvents; @@ -43,8 +45,10 @@ public LitheLifecycleParticipant( MavenPluginManager pluginManager, PluginVersionResolver versionResolver, ProjectDependenciesResolver dependenciesResolver, - NativeSettingsEvents settingsEvents) { + NativeSettingsEvents settingsEvents, + LifecycleExecutionPlanCalculator executionPlans) { this.pluginManager = pluginManager; + this.executionPlans = executionPlans; this.versionResolver = versionResolver; this.dependenciesResolver = dependenciesResolver; this.settingsEvents = settingsEvents; @@ -69,7 +73,7 @@ public void afterSessionStart(MavenSession session) throws MavenExecutionExcepti 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, executionPlans).document())); } String dependenciesOutput = property(session, DEPENDENCIES_OUTPUT); if (dependenciesOutput != 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 88705f5..d02363a 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.Set; import java.util.TreeSet; import org.apache.maven.execution.MavenSession; +import org.apache.maven.lifecycle.internal.LifecycleExecutionPlanCalculator; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.apache.maven.model.Profile; @@ -40,12 +41,14 @@ final class ModelExport { private final MavenSession session; private final MavenPluginManager pluginManager; + private final LifecycleExecutionPlanCalculator executionPlans; private final PluginVersionResolver versionResolver; /** 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, LifecycleExecutionPlanCalculator executionPlans) { this.session = session; + this.executionPlans = executionPlans; this.pluginManager = pluginManager; this.versionResolver = versionResolver; } @@ -74,6 +77,8 @@ Map document() { properties.put("version", project.getVersion()); properties.put("packaging", project.getPackaging()); properties.put("run.modelVersion", "1"); + String minimumJava = CompilerRequirements.minimumJava(session, project, executionPlans); + if (minimumJava != null) properties.put("java.minimumVersion", minimumJava); String provider = runProvider(project); if (provider != null) properties.put("run.provider", provider); entry.put("properties", properties); diff --git a/scripts/test-native-core.mjs b/scripts/test-native-core.mjs index 11e9cf3..b0d98e8 100644 --- a/scripts/test-native-core.mjs +++ b/scripts/test-native-core.mjs @@ -56,6 +56,48 @@ await withInterrupts(async (signal) => { assert.deepEqual(model.projects.map(project => project.name).sort(), ['app', 'core', 'reactor']); assert.ok(model.contentRoots.some(content => content.path === 'nested/core/src/main/java')); }); + await report.step('Maven configured compiler executions own Java requirements across profiles and modules', async () => { + const pom = join(workspace, root, 'pom.xml'), modulePom = join(workspace, root, 'core/pom.xml'); + const original = readFileSync(pom, 'utf8'), originalModule = readFileSync(modulePom, 'utf8'); + const version = project => project.properties['java.minimumVersion']; + try { + const read = async profiles => build('build.decodeModel', { workspaceRoot: workspace, root, + result: await send(build('build.modelPlan', planned({ options: { profiles, offline: true } })).plan, 'compiler-model') }).model; + assert.equal(version(model.projects.find(project => project.name === 'core')), '8'); + writeFileSync(pom, original.replace('', `compiler-floor + 1721 + `)); + let current = await read(['compiler-floor']); + assert.equal(version(current.projects.find(project => project.name === 'core')), '21', 'test release is part of the effective compiler requirement'); + assert.equal(version(current.projects.find(project => project.name === 'app')), '21'); + writeFileSync(modulePom, originalModule.replace('', ` + org.apache.maven.pluginsmaven-compiler-plugin + 11extra-compile + compilecompile23 + `)); + current = await read(['compiler-floor']); + assert.equal(version(current.projects.find(project => project.name === 'core')), '23', 'custom execution configuration is interpreted by Maven'); + assert.equal(version(current.projects.find(project => project.name === 'app')), '21', 'module override does not leak'); + writeFileSync(modulePom, originalModule.replace('', ` + org.apache.maven.pluginsmaven-compiler-plugin + \${unresolved.compiler.release} + `)); + const absent = await read(['compiler-floor']); + assert.equal(version(absent.projects.find(project => project.name === 'core')), '21', 'Maven treats an absent expression as unset and retains the configured test release'); + writeFileSync(modulePom, originalModule.replace('', ` + org.apache.maven.pluginsmaven-compiler-plugin + unsupported-language + `)); + const unknown = await read(['compiler-floor']); + assert.equal(version(unknown.projects.find(project => project.name === 'core')), undefined, 'an unsupported configured language stays unknown rather than guessing from the parent POM'); + + writeFileSync(pom, '99'); + const generated = coreCommand('runConfig.generate', { root: workspace, paths: [], javaEntrypoints: { schemaVersion: 1, entries: [] }, + projectOwnership: current.projects.map(project => ({ path: project.path, name: project.name, mavenReactorPath: root, + minimumJavaVersion: version(project), contentRoots: [] })) }, null); + assert.equal(generated.toolchainRequirements.toolchains['project-jdk'].minimumVersion, '23'); + } finally { writeFileSync(pom, original); writeFileSync(modulePom, originalModule); } + }); await report.step('effective Profile and inherited plugins own framework Run generation without host POM parsing', async () => { const pom = join(workspace, root, 'pom.xml'); const original = readFileSync(pom, 'utf8'); diff --git a/scripts/test.mjs b/scripts/test.mjs index 28cb5c9..080c34f 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -97,6 +97,8 @@ async function test(signal) { artifactId: "app", version: "1.0.0-SNAPSHOT", packaging: "jar", + "run.modelVersion": "1", + "java.minimumVersion": "8", }); }); From 00208cd33a12018ecb079cd9c0c7021c33267221 Mon Sep 17 00:00:00 2001 From: wgw Date: Fri, 30 Oct 2026 09:22:15 +0800 Subject: [PATCH 10/24] feat(maven): export native Wrapper facts and bound cache fingerprint reads --- README.md | 5 ++ .../litheidea/maven/backend/Fingerprint.java | 26 +++++++-- .../litheidea/maven/CompilerRequirements.java | 2 +- .../github/litheidea/maven/ModelExport.java | 3 + .../litheidea/maven/WrapperRequirements.java | 55 +++++++++++++++++++ io.github.lithe-idea.maven-build/plugin.json | 2 +- scripts/test-native-core.mjs | 35 +++++++++++- 7 files changed, 120 insertions(+), 8 deletions(-) create mode 100644 extension/src/main/java/io/github/litheidea/maven/WrapperRequirements.java diff --git a/README.md b/README.md index 979192d..123c44e 100644 --- a/README.md +++ b/README.md @@ -283,3 +283,8 @@ Quarkus 或 Micronaut 插件的非聚合工程还发布 `run.provider`。识别 `java.minimumVersion` 来自 Maven 的实际编译执行计划和参数解析器,涵盖 Profile、 继承、测试编译和自定义 compiler execution;只计算不执行。无法解析时记录诊断并 保持未知,宿主不得回退到 POM 正则;插件仍以 Maven 3.6.3 API 和 Java 8 构建。 + +Wrapper 元数据 `maven.wrapper` / `maven.minimumVersion` 来自所选 reactor 的原生 +脚本和 properties。读取遵循 Java Properties 的注释与转义,文件大小有硬上限; +不执行 Wrapper,也不导出完整分发 URL。未知发行文件名保持未知,脚本新增、替换 +或删除均撤销后端快照,宿主同步观察这些文件;多个 reactor 不共用全局 Wrapper。 diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/Fingerprint.java b/backend/src/main/java/io/github/litheidea/maven/backend/Fingerprint.java index e606a6b..f2b359f 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/Fingerprint.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/Fingerprint.java @@ -1,6 +1,7 @@ package io.github.litheidea.maven.backend; import java.io.IOException; +import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.FileVisitResult; import java.nio.file.Files; @@ -38,7 +39,8 @@ */ final class Fingerprint { /** Bumped when the inputs below change meaning. */ - private static final int VERSION = 2; + private static final int VERSION = 3; + private static final long MAX_FILE_BYTES = 64L * 1024 * 1024; private static final int MAX_DEPTH = 24; private static final int MAX_ENTRIES = 50_000; private static final Set SKIPPED = new HashSet<>(Arrays.asList("target", ".git", "node_modules")); @@ -65,6 +67,8 @@ static String of(Inputs inputs) throws IOException { fingerprint.addFile(".mvn/" + name, inputs.root.resolve(".mvn").resolve(name)); } + for (String name : Arrays.asList("mvnw", "mvnw.cmd")) fingerprint.addFile(name, inputs.root.resolve(name)); + // Native source identities are exported by the selected Maven and // checked by Snapshots/NativeSources, not guessed from CLI syntax. fingerprint.add("optionArguments", String.join("\u0000", inputs.optionArguments)); @@ -97,7 +101,7 @@ public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes att @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { if (attributes.isRegularFile() && file.getFileName().toString().equals("pom.xml")) { - poms.put(root.relativize(file).toString(), sha256(Files.readAllBytes(file))); + poms.put(root.relativize(file).toString(), sha256(file)); } return count(); } @@ -123,7 +127,7 @@ private FileVisitResult count() { private void addFile(String label, Path path) throws IOException { if (Files.isRegularFile(path)) { - add(label, sha256(Files.readAllBytes(path))); + add(label, sha256(path)); } else { add(label, null); } @@ -150,9 +154,21 @@ private String hex() { return hex(digest.digest()); } - private static String sha256(byte[] bytes) { + private static String sha256(Path path) throws IOException { try { - return hex(MessageDigest.getInstance("SHA-256").digest(bytes)); + MessageDigest fileDigest = MessageDigest.getInstance("SHA-256"); + if (Files.size(path) > MAX_FILE_BYTES) throw new IOException("Maven fingerprint input exceeds 64 MiB"); + try (InputStream input = Files.newInputStream(path)) { + byte[] buffer = new byte[8192]; + long total = 0; + int count; + while ((count = input.read(buffer)) != -1) { + total += count; + if (total > MAX_FILE_BYTES) throw new IOException("Maven fingerprint input exceeds 64 MiB"); + fileDigest.update(buffer, 0, count); + } + } + return hex(fileDigest.digest()); } catch (NoSuchAlgorithmException error) { throw new IllegalStateException(error); } diff --git a/extension/src/main/java/io/github/litheidea/maven/CompilerRequirements.java b/extension/src/main/java/io/github/litheidea/maven/CompilerRequirements.java index 08942c7..77db810 100644 --- a/extension/src/main/java/io/github/litheidea/maven/CompilerRequirements.java +++ b/extension/src/main/java/io/github/litheidea/maven/CompilerRequirements.java @@ -45,7 +45,7 @@ static String minimumJava(MavenSession session, MavenProject project, LifecycleE } return minimum == 0 ? null : Integer.toString(minimum); } catch (Exception error) { - // Unavailable plugin descriptors or unresolved expressions leave the + // Unavailable plugin descriptors or unsupported evaluated versions leave the // requirement unknown. They must never trigger a second POM parser. LOG.warn("Lithe could not determine Java compiler requirements for {}: {}", project.getArtifactId(), error.getMessage()); return 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 d02363a..0dfb824 100644 --- a/extension/src/main/java/io/github/litheidea/maven/ModelExport.java +++ b/extension/src/main/java/io/github/litheidea/maven/ModelExport.java @@ -58,6 +58,8 @@ Map document() { List tasks = new ArrayList<>(); List contentRoots = new ArrayList<>(); Map aggregators = aggregators(); + Map wrapper = new LinkedHashMap<>(); + WrapperRequirements.add(session, wrapper); for (MavenProject project : session.getProjects()) { String path = path(project.getBasedir()); Map entry = new LinkedHashMap<>(); @@ -77,6 +79,7 @@ Map document() { properties.put("version", project.getVersion()); properties.put("packaging", project.getPackaging()); properties.put("run.modelVersion", "1"); + properties.putAll(wrapper); String minimumJava = CompilerRequirements.minimumJava(session, project, executionPlans); if (minimumJava != null) properties.put("java.minimumVersion", minimumJava); String provider = runProvider(project); diff --git a/extension/src/main/java/io/github/litheidea/maven/WrapperRequirements.java b/extension/src/main/java/io/github/litheidea/maven/WrapperRequirements.java new file mode 100644 index 0000000..7b972a0 --- /dev/null +++ b/extension/src/main/java/io/github/litheidea/maven/WrapperRequirements.java @@ -0,0 +1,55 @@ +package io.github.litheidea.maven; + +import java.io.File; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.apache.maven.execution.MavenSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Reads the selected build root's native Wrapper properties without executing it. */ +final class WrapperRequirements { + private static final Logger LOG = LoggerFactory.getLogger(WrapperRequirements.class); + private static final Pattern DISTRIBUTION = Pattern.compile("apache-maven-([0-9]+(?:\\.[0-9]+)+)-bin\\.(?:zip|tar\\.gz)"); + + static void add(MavenSession session, Map properties) { + Path root = new File(session.getExecutionRootDirectory()).toPath(); + String script = Files.isRegularFile(root.resolve("mvnw")) ? "mvnw" + : Files.isRegularFile(root.resolve("mvnw.cmd")) ? "mvnw.cmd" : null; + if (script != null) properties.put("maven.wrapper", script); + Path source = root.resolve(".mvn/wrapper/maven-wrapper.properties"); + if (!Files.isRegularFile(source)) return; + try { + if (Files.size(source) > 1024 * 1024) throw new IllegalArgumentException("Wrapper properties exceed the input budget"); + Properties nativeValues = new Properties(); + try (InputStream input = Files.newInputStream(source)) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte[] buffer = new byte[8192]; + int total = 0, count; + while ((count = input.read(buffer, 0, Math.min(buffer.length, 1024 * 1024 + 1 - total))) != -1) { + total += count; + if (total > 1024 * 1024) throw new IllegalArgumentException("Wrapper properties exceed the input budget"); + bytes.write(buffer, 0, count); + } + nativeValues.load(new ByteArrayInputStream(bytes.toByteArray())); + } + String distribution = nativeValues.getProperty("distributionUrl"); + if (distribution == null) return; + String path = new URI(distribution.trim()).getPath(); + if (path == null) return; + String filename = path.substring(path.lastIndexOf('/') + 1); + Matcher version = DISTRIBUTION.matcher(filename); + if (version.matches()) properties.put("maven.minimumVersion", version.group(1)); + } catch (Exception error) { + LOG.warn("Lithe could not determine Maven Wrapper requirements: {}", error.getMessage()); + } + } +} diff --git a/io.github.lithe-idea.maven-build/plugin.json b/io.github.lithe-idea.maven-build/plugin.json index 3dcca1b..ff2aa05 100644 --- a/io.github.lithe-idea.maven-build/plugin.json +++ b/io.github.lithe-idea.maven-build/plugin.json @@ -231,7 +231,7 @@ ] }, "dependencies": { "source": "provider", "scopes": ["workspace", "project"] }, - "sync": { "watch": [".mvn/extensions.xml", ".mvn/maven.config", "pom.xml"] }, + "sync": { "watch": [".mvn/extensions.xml", ".mvn/maven.config", ".mvn/jvm.config", ".mvn/wrapper/maven-wrapper.properties", "mvnw", "mvnw.cmd", "pom.xml"] }, "layout": { "excluded": ["target"] }, "languageImport": { "kind": "maven", diff --git a/scripts/test-native-core.mjs b/scripts/test-native-core.mjs index b0d98e8..19696af 100644 --- a/scripts/test-native-core.mjs +++ b/scripts/test-native-core.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node // The production plugin, current Core C ABI, and a real Maven reactor in one workflow. import assert from 'node:assert/strict'; -import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, truncateSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { spawnSync } from 'node:child_process'; @@ -98,6 +98,39 @@ await withInterrupts(async (signal) => { assert.equal(generated.toolchainRequirements.toolchains['project-jdk'].minimumVersion, '23'); } finally { writeFileSync(pom, original); writeFileSync(modulePom, originalModule); } }); + await report.step('native Wrapper metadata uses Properties semantics and script changes revoke cached facts', async () => { + const directory = join(workspace, root), wrapper = join(directory, 'mvnw'), windowsWrapper = join(directory, 'mvnw.cmd'); + const properties = join(directory, '.mvn/wrapper/maven-wrapper.properties'); + mkdirSync(join(directory, '.mvn/wrapper'), { recursive: true }); + const read = async () => build('build.decodeModel', { workspaceRoot: workspace, root, + result: await send(build('build.modelPlan', planned({ options: { offline: true } })).plan, 'wrapper-model') }).model; + try { + writeFileSync(wrapper, '#!/bin/sh\nexit 99\n'); + writeFileSync(properties, '# distributionUrl=https://example.invalid/apache-maven-99.0.0-bin.zip\ndistributionUrl=https\\://example.invalid/apache-maven-3.9.9-bin.zip\n'); + let current = await read(); + assert.ok(current.projects.every(project => project.properties['maven.wrapper'] === 'mvnw')); + assert.ok(current.projects.every(project => project.properties['maven.minimumVersion'] === '3.9.9'), 'native properties ignore comments and unescape the URL'); + writeFileSync(properties, 'distributionUrl=https://example.invalid/apache-maven-99.0.0-bin.zip\n'); + const generated = coreCommand('runConfig.generate', { root: workspace, paths: [], javaEntrypoints: { schemaVersion: 1, entries: [] }, + projectOwnership: current.projects.map(project => ({ path: project.path, name: project.name, mavenReactorPath: root, + mavenMinimumVersion: project.properties['maven.minimumVersion'], mavenWrapper: root + '/' + project.properties['maven.wrapper'], contentRoots: [] })) }, null); + assert.equal(generated.toolchainRequirements.toolchains['project-maven'].minimumVersion, '3.9.9'); + assert.equal(generated.toolchainRequirements.toolchains['project-maven'].wrapper, 'nested/mvnw'); + writeFileSync(properties, '# distributionUrl=https://example.invalid/apache-maven-99.0.0-bin.zip\ndistributionUrl=https://example.invalid/custom.zip\n'); + current = await read(); + assert.ok(current.projects.every(project => project.properties['maven.minimumVersion'] === undefined), 'unrecognized distribution stays unknown'); + rmSync(wrapper); writeFileSync(windowsWrapper, '@exit /b 99\n'); + current = await read(); + assert.ok(current.projects.every(project => project.properties['maven.wrapper'] === 'mvnw.cmd'), 'script-only changes invalidate the backend snapshot'); + rmSync(windowsWrapper); + current = await read(); + assert.ok(current.projects.every(project => project.properties['maven.wrapper'] === undefined), 'removing the last script revokes the Wrapper fact'); + writeFileSync(wrapper, ''); truncateSync(wrapper, 64 * 1024 * 1024 + 1); + await assert.rejects(read(), 'an oversized script is rejected before an unbounded fingerprint allocation or Maven execution'); + } finally { + rmSync(wrapper, { force: true }); rmSync(windowsWrapper, { force: true }); rmSync(properties, { force: true }); + } + }); await report.step('effective Profile and inherited plugins own framework Run generation without host POM parsing', async () => { const pom = join(workspace, root, 'pom.xml'); const original = readFileSync(pom, 'utf8'); From b426f42749f81eb82e47996dd5f2c4ed76ec0da1 Mon Sep 17 00:00:00 2001 From: wgw Date: Fri, 30 Oct 2026 14:58:32 +0800 Subject: [PATCH 11/24] feat(maven): prepare framework services with the upstream reactor --- README.md | 14 +++ .../litheidea/maven/backend/Fingerprint.java | 2 +- .../litheidea/maven/backend/MavenBackend.java | 15 +++ .../maven/backend/MavenExecution.java | 2 +- .../maven/backend/MavenRunPreparation.java | 114 +++++++++++++++++ .../litheidea/maven/FrameworkLaunch.java | 36 ++++++ .../github/litheidea/maven/ModelExport.java | 36 +++--- .../litheidea/maven/RunExecutionEvents.java | 115 ++++++++++++++++++ .../META-INF/sisu/javax.inject.Named | 1 + io.github.lithe-idea.maven-build/plugin.json | 26 +++- scripts/test-native-core.mjs | 71 ++++++++++- scripts/verify-extension.mjs | 2 +- 12 files changed, 410 insertions(+), 24 deletions(-) create mode 100644 backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java create mode 100644 extension/src/main/java/io/github/litheidea/maven/FrameworkLaunch.java create mode 100644 extension/src/main/java/io/github/litheidea/maven/RunExecutionEvents.java diff --git a/README.md b/README.md index 123c44e..def6ee7 100644 --- a/README.md +++ b/README.md @@ -288,3 +288,17 @@ Wrapper 元数据 `maven.wrapper` / `maven.minimumVersion` 来自所选 reactor 脚本和 properties。读取遵循 Java Properties 的注释与转义,文件大小有硬上限; 不执行 Wrapper,也不导出完整分发 URL。未知发行文件名保持未知,脚本新增、替换 或删除均撤销后端快照,宿主同步观察这些文件;多个 reactor 不共用全局 Wrapper。 + + +开发协议 10 的框架和模块运行使用 `lithe/build/prepareRun`,目标来自当前 Maven +模型,应用参数、JVM 参数、环境、入口和显式 cwd 分别传递。插件返回 portable +启动计划,由宿主既有 Run 会话启动和停止进程。Spring Boot、Quarkus、Micronaut +的目标选择来自生效的 build plugins;仅存在于 pluginManagement 的插件不会成为服务。 +框架启动保留同 reactor 的 workspace reader:先构建依赖,再仅在所选工程执行 +实际 Mojo,不把服务目标交给父工程。参数按当前 Mojo 描述符的数组/字符串类型 +设置,无法精确保留(例如不支持的空参数或 cwd)时明确拒绝。 + +模块任务的用户输入是目标和普通 `-D` 属性;Profiles、settings、仓库、工程选择 +仍经类型化 Build 选项传递,不接受额外 CLI 覆盖制造第二套配置。属性和环境也 +参与准备时的有效模型读取。开发组合可用 `scripts/package-development.mjs` +及 `scripts/test-native-core.mjs` 验证;正式 SDK 锁定和发行条件保持不变。 diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/Fingerprint.java b/backend/src/main/java/io/github/litheidea/maven/backend/Fingerprint.java index f2b359f..4a4f791 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/Fingerprint.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/Fingerprint.java @@ -39,7 +39,7 @@ */ final class Fingerprint { /** Bumped when the inputs below change meaning. */ - private static final int VERSION = 3; + private static final int VERSION = 4; private static final long MAX_FILE_BYTES = 64L * 1024 * 1024; private static final int MAX_DEPTH = 24; private static final int MAX_ENTRIES = 50_000; diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java index e5570a3..5e8b26e 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java @@ -13,6 +13,7 @@ import java.nio.file.Paths; import java.util.LinkedHashMap; import java.util.Map; +import java.util.List; /** * Lithe's build provider for Maven. It answers {@code lithe/build/model} and @@ -63,6 +64,20 @@ private void serve() { backend.onDependencies(this::dependencies); backend.onExecute((params, context) -> execution(params, context, false)); backend.onTest((params, context) -> execution(params, context, true)); + backend.onPrepareRun((params, context) -> { + Map request = new LinkedHashMap<>(params); + Map environment = new LinkedHashMap<>(); + if (params.get("environment") instanceof Map) environment.putAll(Json.object(params.get("environment"))); + environment.putAll(Json.object(Json.object(params.get("launchOptions")).get("environment"))); + request.put("environment", environment); + Inputs selected = inputs(request); + List arguments = new java.util.ArrayList<>(selected.optionArguments); + arguments.addAll(MavenRunPreparation.modelArguments(request)); + MavenRuns.Loaded loaded = runs.load(new Inputs(selected.root, selected.maven, arguments, selected.environment, + selected.hostEnvironment, selected.extensionJar), Boolean.TRUE.equals(request.get("refresh")), context.cancellation()); + context.throwIfCancelled(); + return MavenRunPreparation.prepare(request, root(request), workspaceRoot, loaded, extensionJar()); + }); backend.listen(); } diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecution.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecution.java index cd6594b..194d82a 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecution.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenExecution.java @@ -120,7 +120,7 @@ static List optionArguments(Map params, boolean skipTest return result; } - private static Path selectedProject(Object selected, Path root, Path workspace, MavenRuns.Loaded loaded) throws IOException { + static Path selectedProject(Object selected, Path root, Path workspace, MavenRuns.Loaded loaded) throws IOException { if (selected == null) return null; if (!(selected instanceof Map)) throw invalid("Expected a Maven project selector."); Map selection = Json.object(selected); diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java new file mode 100644 index 0000000..aa1a142 --- /dev/null +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java @@ -0,0 +1,114 @@ +package io.github.litheidea.maven.backend; + +import io.github.litheidea.plugin.sdk.Json; +import io.github.litheidea.plugin.sdk.PluginError; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** Validates a current Maven target and returns a host-owned Maven launch. */ +final class MavenRunPreparation { + private MavenRunPreparation() {} + + static Map prepare(Map params, Path root, Path workspace, + MavenRuns.Loaded loaded, Path extension) throws Exception { + Map options = Json.object(params.get("launchOptions")); + String run = Json.string(params, "run"); + boolean framework = "framework".equals(run); + if (!(framework || "module".equals(run)) || !(framework ? "service" : "task").equals(options.get("execution")) + || !strings(params.get("userArguments")).isEmpty()) throw invalid("Select a Maven run with typed launch options."); + Path project = MavenExecution.selectedProject(params.get("project"), root, workspace, loaded); + if (project == null) throw invalid("A Maven run needs one current project."); + Map selected = Json.object(params.get("target")); + Map target = null; + for (Object candidate : list(loaded.model().get("targets"))) { + Map known = Json.object(candidate); + String path = Json.string(known, "path"); + if (path != null && root.resolve(path).toRealPath().equals(project) + && known.get("name").equals(selected.get("name")) + && workspace.resolve(Json.string(selected, "path")).toRealPath().equals(project) + && strings(known.get("tags")).contains(framework ? "maven-service" : "maven-module")) target = known; + } + if (target == null) throw invalid("The run target is absent from the current Maven model."); + Map properties = Json.object(target.get("properties")); + String cwd = options.containsKey("workingDirectory") ? Json.string(options, "workingDirectory") : relative(workspace, root); + Path directory = workspace.resolve(cwd).toRealPath(); + if (!directory.startsWith(workspace) || !Files.isDirectory(directory)) throw invalid("The run working directory leaves the workspace."); + List arguments = new ArrayList<>(Arrays.asList("-B", "-ntp", "--file", root.resolve("pom.xml").toString())); + arguments.addAll(MavenExecution.optionArguments(params, true)); + if (!project.equals(root)) { arguments.add("-pl"); arguments.add(root.relativize(project).toString()); arguments.add("-am"); } + List runtimeArguments = strings(options.get("runtimeArguments")); + List programArguments = strings(options.get("arguments")); + if (framework) { + if (!"1".equals(properties.get("run.preparationVersion"))) throw invalid("The Maven model cannot prepare this framework run. Refresh or update the plugin."); + addArguments(arguments, "runtime", runtimeArguments); + addArguments(arguments, "arguments", programArguments); + String entrypoint = Json.string(options, "entrypoint"); + if (entrypoint != null) addProperty(arguments, properties, "run.entrypointProperty", entrypoint); + if (options.containsKey("workingDirectory")) { + if (!properties.containsKey("run.workingDirectoryParameter")) throw invalid("This framework cannot override its application working directory."); + arguments.add("-Dlithe.run.workingDirectory=" + directory); + } + arguments.add("-Dmaven.ext.class.path=" + extension); + arguments.add("-Dlithe.run.project=" + project); + arguments.add("-Dlithe.run.goal=" + properties.get("run.goal")); + arguments.add("test-compile"); + } else { + if (!runtimeArguments.isEmpty() || options.containsKey("entrypoint")) throw invalid("Maven module goals do not accept application runtime or entrypoint options."); + if (programArguments.isEmpty()) throw invalid("A Maven module run needs one or more goals."); + modelArguments(params); // The same checked properties were supplied to the model read. + arguments.addAll(programArguments); + } + Map environment = new LinkedHashMap<>(); + if (params.get("environment") instanceof Map) environment.putAll(Json.object(params.get("environment"))); + environment.putAll(Json.object(options.get("environment"))); + Map result = new LinkedHashMap<>(); + Map executable = new LinkedHashMap<>(); executable.put("kind", "toolchain"); executable.put("value", "project-maven"); + result.put("executable", executable); result.put("arguments", arguments); result.put("workingDirectory", cwd); result.put("environment", environment); + return result; + } + + /** Maven parses property values itself; model reads and goal execution receive identical argv. */ + static List modelArguments(Map params) { + List properties = new ArrayList<>(); + if (!"module".equals(params.get("run"))) return properties; + for (String argument : strings(Json.object(params.get("launchOptions")).get("arguments"))) { + if (argument.startsWith("-D") && argument.length() > 2 && !argument.startsWith("-Dlithe.") + && !argument.startsWith("-Dmaven.ext.class.path") && !argument.startsWith("-Dmaven.repo.local")) properties.add(argument); + else if (argument.startsWith("-")) throw invalid("Configure Maven profiles, settings, repositories and project selection through the build options before running goals."); + } + return properties; + } + + private static void addProperty(List arguments, Map properties, String field, String value) { + if (value.isEmpty()) return; + String property = Json.string(properties, field); + if (property == null || !property.matches("[A-Za-z][A-Za-z0-9._-]*")) throw invalid("The framework cannot accept this launch choice."); + arguments.add("-D" + property + "=" + value); + } + + /** Indexed Maven user properties preserve argv until the actual Mojo descriptor is available. */ + private static void addArguments(List arguments, String kind, List values) { + if (values.stream().anyMatch(value -> value.trim().isEmpty())) throw invalid("This Maven framework cannot preserve empty application arguments."); + arguments.add("-Dlithe.run." + kind + ".count=" + values.size()); + for (int index = 0; index < values.size(); index++) arguments.add("-Dlithe.run." + kind + "." + index + "=" + values.get(index)); + } + + private static String relative(Path workspace, Path path) { + String value = workspace.relativize(path).toString().replace(java.io.File.separatorChar, '/'); + return value.isEmpty() ? "." : value; + } + private static List list(Object value) { return value instanceof List ? (List) value : Collections.emptyList(); } + private static List strings(Object value) { + List result = new ArrayList<>(); + for (Object item : list(value)) { if (!(item instanceof String)) throw invalid("Expected an argument array."); result.add((String) item); } + return result; + } + private static PluginError invalid(String message) { return new PluginError("maven.invalidRun", message); } +} diff --git a/extension/src/main/java/io/github/litheidea/maven/FrameworkLaunch.java b/extension/src/main/java/io/github/litheidea/maven/FrameworkLaunch.java new file mode 100644 index 0000000..1f6dd11 --- /dev/null +++ b/extension/src/main/java/io/github/litheidea/maven/FrameworkLaunch.java @@ -0,0 +1,36 @@ +package io.github.litheidea.maven; + +import org.apache.maven.model.Plugin; +import org.apache.maven.project.MavenProject; + +/** Framework invocation metadata comes only from Maven's effective applied plugins. */ +final class FrameworkLaunch { + final Plugin plugin; + final String provider, goal, runtimeProperty, argumentsProperty, entrypointProperty; + + private FrameworkLaunch(Plugin plugin, String[] kind) { + this.plugin = plugin; provider = kind[2]; goal = kind[3]; runtimeProperty = kind[4]; + argumentsProperty = kind[5]; entrypointProperty = kind.length > 6 ? kind[6] : null; + } + + static FrameworkLaunch find(MavenProject project) { + if ("pom".equals(project.getPackaging())) return null; + String[][] kinds = { + {"org.springframework.boot", "spring-boot-maven-plugin", "spring-boot.maven", "run", "spring-boot.run.jvmArguments", "spring-boot.run.arguments", "spring-boot.run.main-class"}, + {"io.quarkus", "quarkus-maven-plugin", "quarkus.maven", "dev", "jvm.args", "quarkus.args"}, + {"io.quarkus.platform", "quarkus-maven-plugin", "quarkus.maven", "dev", "jvm.args", "quarkus.args"}, + {"io.micronaut.build", "micronaut-maven-plugin", "micronaut.maven", "run", "mn.jvmArgs", "mn.appArgs"}, + {"io.micronaut.maven", "micronaut-maven-plugin", "micronaut.maven", "run", "mn.jvmArgs", "mn.appArgs"} + }; + for (String[] kind : kinds) for (Plugin plugin : project.getBuildPlugins()) { + if (kind[0].equals(plugin.getGroupId()) && kind[1].equals(plugin.getArtifactId())) return new FrameworkLaunch(plugin, kind); + } + return null; + } + + boolean accepts(String qualifiedGoal) { + String coordinates = plugin.getGroupId() + ":" + plugin.getArtifactId(); + return (coordinates + ":" + goal).equals(qualifiedGoal) + || plugin.getVersion() != null && (coordinates + ":" + plugin.getVersion() + ":" + goal).equals(qualifiedGoal); + } +} 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 0dfb824..e9e3199 100644 --- a/extension/src/main/java/io/github/litheidea/maven/ModelExport.java +++ b/extension/src/main/java/io/github/litheidea/maven/ModelExport.java @@ -57,6 +57,7 @@ Map document() { List projects = new ArrayList<>(); List tasks = new ArrayList<>(); List contentRoots = new ArrayList<>(); + List targets = new ArrayList<>(); Map aggregators = aggregators(); Map wrapper = new LinkedHashMap<>(); WrapperRequirements.add(session, wrapper); @@ -82,8 +83,18 @@ Map document() { properties.putAll(wrapper); String minimumJava = CompilerRequirements.minimumJava(session, project, executionPlans); if (minimumJava != null) properties.put("java.minimumVersion", minimumJava); - String provider = runProvider(project); - if (provider != null) properties.put("run.provider", provider); + FrameworkLaunch framework = FrameworkLaunch.find(project); + if (framework != null) { + properties.put("run.provider", framework.provider); + properties.put("run.goal", goals(project, framework.plugin).coordinates + ":" + framework.goal); + properties.put("run.runtimeArgumentsProperty", framework.runtimeProperty); + properties.put("run.argumentsProperty", framework.argumentsProperty); + if (framework.entrypointProperty != null) properties.put("run.entrypointProperty", framework.entrypointProperty); + properties.put("run.preparationVersion", "1"); + if ("spring-boot.maven".equals(framework.provider)) properties.put("run.workingDirectoryParameter", "workingDirectory"); + addTarget(targets, path, framework.provider, "maven-service", properties); + } + addTarget(targets, path, "maven.module", "maven-module", properties); entry.put("properties", properties); projects.add(entry); if (!"pom".equals(project.getPackaging())) { @@ -98,6 +109,7 @@ Map document() { document.put("version", 1); document.put("projects", projects); document.put("tasks", tasks); + document.put("targets", targets); document.put("contentRoots", contentRoots); document.put("optionValues", optionValues); return document; @@ -127,21 +139,11 @@ private Map aggregators() { * Plugin management alone does not apply a plugin. Coordinate precedence * preserves the host's existing service identity if several are applied. */ - private static String runProvider(MavenProject project) { - if ("pom".equals(project.getPackaging())) return null; - String[][] providers = { - {"org.springframework.boot", "spring-boot-maven-plugin", "spring-boot.maven"}, - {"io.quarkus", "quarkus-maven-plugin", "quarkus.maven"}, - {"io.quarkus.platform", "quarkus-maven-plugin", "quarkus.maven"}, - {"io.micronaut.build", "micronaut-maven-plugin", "micronaut.maven"}, - {"io.micronaut.maven", "micronaut-maven-plugin", "micronaut.maven"} - }; - for (String[] provider : providers) { - for (Plugin plugin : project.getBuildPlugins()) { - if (provider[0].equals(plugin.getGroupId()) && provider[1].equals(plugin.getArtifactId())) return provider[2]; - } - } - return null; + private static void addTarget(List targets, String project, String name, String tag, Map properties) { + Map target = new LinkedHashMap<>(); + target.put("project", project); target.put("path", project); target.put("name", name); + target.put("tags", Collections.singletonList(tag)); target.put("properties", new LinkedHashMap<>(properties)); + targets.add(target); } private void addContentRoots(MavenProject project, String owner, List roots) { diff --git a/extension/src/main/java/io/github/litheidea/maven/RunExecutionEvents.java b/extension/src/main/java/io/github/litheidea/maven/RunExecutionEvents.java new file mode 100644 index 0000000..84d852b --- /dev/null +++ b/extension/src/main/java/io/github/litheidea/maven/RunExecutionEvents.java @@ -0,0 +1,115 @@ +package io.github.litheidea.maven; + +import java.io.File; +import java.util.Collections; +import java.util.List; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Properties; +import org.apache.maven.plugin.MojoExecution; +import org.apache.maven.plugin.descriptor.Parameter; +import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.codehaus.plexus.util.cli.CommandLineUtils; +import java.util.concurrent.atomic.AtomicBoolean; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; +import org.apache.maven.execution.ProjectExecutionEvent; +import org.apache.maven.execution.ProjectExecutionListener; +import org.apache.maven.lifecycle.LifecycleExecutionException; +import org.apache.maven.lifecycle.internal.GoalTask; +import org.apache.maven.lifecycle.internal.LifecycleExecutionPlanCalculator; +import org.apache.maven.lifecycle.internal.MojoExecutor; +import org.apache.maven.lifecycle.internal.ProjectIndex; + +/** Maven builds the selected reactor first, then executes a framework only in its owner project. */ +@Named +@Singleton +public final class RunExecutionEvents implements ProjectExecutionListener { + private final LifecycleExecutionPlanCalculator plans; + private final MojoExecutor executor; + private final AtomicBoolean launched = new AtomicBoolean(); + + @Inject + public RunExecutionEvents(LifecycleExecutionPlanCalculator plans, MojoExecutor executor) { + this.plans = plans; this.executor = executor; + } + + @Override public void beforeProjectExecution(ProjectExecutionEvent event) {} + @Override public void beforeProjectLifecycleExecution(ProjectExecutionEvent event) {} + @Override public void afterProjectExecutionFailure(ProjectExecutionEvent event) {} + + @Override public void afterProjectExecutionSuccess(ProjectExecutionEvent event) throws LifecycleExecutionException { + String owner = event.getSession().getUserProperties().getProperty("lithe.run.project"); + String goal = event.getSession().getUserProperties().getProperty("lithe.run.goal"); + if (owner == null || goal == null) return; + try { + if (!event.getProject().getBasedir().getCanonicalFile().equals(new File(owner).getCanonicalFile())) return; + FrameworkLaunch framework = FrameworkLaunch.find(event.getProject()); + if (framework == null || !framework.accepts(goal)) throw new IllegalArgumentException("The framework goal is absent from the current Maven project."); + if (!launched.compareAndSet(false, true)) return; + // Maven retains its reactor workspace reader, dependency scopes, lifecycle + // forks and plugin configuration. No second classpath or artifact model. + List executions = plans.calculateExecutionPlan(event.getSession(), event.getProject(), + Collections.singletonList(new GoalTask(goal)), true).getMojoExecutions(); + for (MojoExecution execution : executions) { + if (goal.endsWith(":" + execution.getGoal()) && framework.plugin.getArtifactId().equals(execution.getArtifactId())) { + configure(execution, framework.runtimeProperty, arguments(event, "runtime")); + configure(execution, framework.argumentsProperty, arguments(event, "arguments")); + String cwd = event.getSession().getUserProperties().getProperty("lithe.run.workingDirectory"); + if (cwd != null) { + if (!"spring-boot.maven".equals(framework.provider) || execution.getMojoDescriptor().getParameters().stream() + .noneMatch(parameter -> "workingDirectory".equals(parameter.getName()) && "java.io.File".equals(parameter.getType()))) { + throw new IllegalArgumentException("The framework has no application working directory parameter."); + } + Xpp3Dom directory = execution.getConfiguration().getChild("workingDirectory"); + if (directory == null) { directory = new Xpp3Dom("workingDirectory"); execution.getConfiguration().addChild(directory); } + directory.setValue(cwd); + } + } + } + executor.execute(event.getSession(), executions, new ProjectIndex(event.getSession().getProjects())); + } catch (Exception error) { + if (error instanceof LifecycleExecutionException) throw (LifecycleExecutionException) error; + throw new LifecycleExecutionException("Lithe could not prepare the current Maven framework goal.", null, event.getProject(), error); + } + } + private static List arguments(ProjectExecutionEvent event, String kind) { + Properties properties = event.getSession().getUserProperties(); + int count = Integer.parseInt(properties.getProperty("lithe.run." + kind + ".count", "0")); + if (count < 0 || count > 1024) throw new IllegalArgumentException("Invalid run argument count."); + List values = new ArrayList<>(); + for (int index = 0; index < count; index++) { + String value = properties.getProperty("lithe.run." + kind + "." + index); + if (value == null || value.trim().isEmpty()) throw new IllegalArgumentException("A framework cannot preserve empty run arguments."); + values.add(value); + } + return values; + } + + /** Maven's descriptor selects string versus collection conversion for each plugin version. */ + private static void configure(MojoExecution execution, String property, List values) throws Exception { + if (values.isEmpty()) return; + Parameter selected = null; + for (Parameter parameter : execution.getMojoDescriptor().getParameters()) { + if (("${" + property + "}").equals(parameter.getExpression())) selected = parameter; + } + if (selected == null) throw new IllegalArgumentException("The framework has no parameter for " + property); + Xpp3Dom configuration = execution.getConfiguration(); + Xpp3Dom value = configuration.getChild(selected.getName()); + if (value == null) { value = new Xpp3Dom(selected.getName()); configuration.addChild(value); } + while (value.getChildCount() > 0) value.removeChild(0); + if ("java.lang.String[]".equals(selected.getType()) || "java.util.List".equals(selected.getType())) { + value.setValue(null); + for (String argument : values) { Xpp3Dom child = new Xpp3Dom("argument"); child.setValue(argument); value.addChild(child); } + } else if ("java.lang.String".equals(selected.getType())) { + String encoded = CommandLineUtils.toString(values.toArray(new String[0])); + if (!Arrays.equals(values.toArray(new String[0]), CommandLineUtils.translateCommandline(encoded)) + || values.stream().anyMatch(argument -> argument.indexOf('\n') >= 0 || argument.indexOf('\t') >= 0 || argument.indexOf('\r') >= 0)) { + throw new IllegalArgumentException("The framework string parameter cannot preserve the requested argument boundaries."); + } + value.setValue(encoded); + } else { throw new IllegalArgumentException("Unsupported framework run parameter type: " + selected.getType()); } + } + +} diff --git a/extension/src/main/resources/META-INF/sisu/javax.inject.Named b/extension/src/main/resources/META-INF/sisu/javax.inject.Named index fb12338..5539bc3 100644 --- a/extension/src/main/resources/META-INF/sisu/javax.inject.Named +++ b/extension/src/main/resources/META-INF/sisu/javax.inject.Named @@ -1,3 +1,4 @@ io.github.litheidea.maven.LitheLifecycleParticipant io.github.litheidea.maven.NativeSettingsEvents io.github.litheidea.maven.ReportCaptureEvents +io.github.litheidea.maven.RunExecutionEvents diff --git a/io.github.lithe-idea.maven-build/plugin.json b/io.github.lithe-idea.maven-build/plugin.json index ff2aa05..7fec8bf 100644 --- a/io.github.lithe-idea.maven-build/plugin.json +++ b/io.github.lithe-idea.maven-build/plugin.json @@ -4,7 +4,7 @@ "displayName": "Maven", "version": "0.1.1", "pluginAPIVersion": 3, - "requires": { "buildProviders": 9, "buildModelInputs": 1, "buildSystems": 3, "executableResolution": 2, "serverProcess": 1 }, + "requires": { "buildProviders": 10, "buildModelInputs": 1, "buildSystems": 3, "executableResolution": 2, "serverProcess": 1 }, "vendor": { "id": "io.github.lithe-idea", "displayName": "Lithe Community", @@ -30,6 +30,30 @@ "version": { "arguments": ["--version"], "pattern": "Apache Maven (\\d+\\.\\d+\\.\\d+)" }, "minimumVersion": "3.6.3" }, + "run": [ + { + "id": "framework", + "source": "provider", + "name": "Run Maven service", + "execution": "service", + "fromTargets": { + "tags": [ + "maven-service" + ] + } + }, + { + "id": "module", + "source": "provider", + "name": "Run Maven goals", + "execution": "task", + "fromTargets": { + "tags": [ + "maven-module" + ] + } + } + ], "options": [ { "id": "profiles", diff --git a/scripts/test-native-core.mjs b/scripts/test-native-core.mjs index 19696af..950af36 100644 --- a/scripts/test-native-core.mjs +++ b/scripts/test-native-core.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node // The production plugin, current Core C ABI, and a real Maven reactor in one workflow. import assert from 'node:assert/strict'; -import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, truncateSync, writeFileSync } from 'node:fs'; +import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, truncateSync, writeFileSync, openSync, closeSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { spawnSync } from 'node:child_process'; @@ -9,7 +9,7 @@ import { BackendClient, bounded } from './backend-client.mjs'; import { coreCommand } from './core-client.mjs'; import { bundleManifest } from './bundle-manifest.mjs'; import { createReport } from './report.mjs'; -import { mavenTimeout, withInterrupts } from './process.mjs'; +import { mavenTimeout, withInterrupts, runCommand } from './process.mjs'; const id = 'io.github.lithe-idea.maven-build'; const pkg = resolve(process.env.LITHE_TEST_PACKAGE ?? resolve('dist/package', id)); @@ -45,7 +45,7 @@ await withInterrupts(async (signal) => { state: join(scratch, 'state'), timeoutMs: mavenTimeout() }); await report.step('Core admits the new Maven capability and produces only Provider plans', async () => { coreCommand('plugins.declarative.validate', { manifest }); - assert.equal((await client.initialize(workspace, [9])).capabilities.experimental.litheBuild.version, 9); + assert.equal((await client.initialize(workspace, [10])).capabilities.experimental.litheBuild.version, 10); for (const task of manifest.buildSystems[0].tasks) { assert.equal(task.source, 'provider'); assert.deepEqual(task.arguments, []); } assert.equal(manifest.buildSystems[0].test.source, 'provider'); }); @@ -346,11 +346,76 @@ await withInterrupts(async (signal) => { writeFileSync(pom, original); } }); + await report.step('current Maven framework target launches only its module with reactor classes, exact argv and application cwd', async () => { + const directory = join(workspace, 'framework reactor'); + const cwd = join(workspace, 'framework cwd'); + mkdirSync(cwd); + cpSync(resolve('test/fixtures/reactor'), directory, { recursive: true }); + const version = 'run-' + process.pid + '-' + Date.now(); + for (const module of ['', 'app', 'core']) { + const pom = join(directory, module, 'pom.xml'); + writeFileSync(pom, readFileSync(pom, 'utf8').replaceAll('1.0.0-SNAPSHOT', version)); + } + const appPom = join(directory, 'app/pom.xml'); + const original = readFileSync(appPom, 'utf8'); + writeFileSync(appPom, original.replace('', `org.springframework.boot + spring-boot-maven-plugin2.2.2.RELEASE`)); + writeFileSync(join(directory, 'app/src/main/java/demo/app/Main.java'), `package demo.app; + import demo.core.Greeter; + public final class Main { public static void main(String[] args) throws Exception { + System.out.println(new Greeter().greet(System.getenv("LITHE_RUN_VALUE"))); + System.out.println("PROP="+System.getProperty("lithe.message")); + System.out.println("CWD="+new java.io.File(".").getCanonicalPath()); + for (String arg : args) System.out.println("ARG="+java.util.Base64.getEncoder().encodeToString(arg.getBytes("UTF-8"))); + } }`); + const selectedRoot = 'framework reactor'; + const readModel = async () => build('build.decodeModel', { workspaceRoot: workspace, root: selectedRoot, + result: await send(build('build.modelPlan', planned({ root: selectedRoot })).plan, 'framework-launch-model') }).model; + const current = await readModel(); + const app = current.projects.find(value => value.name === 'app'); + const target = current.targets.find(value => value.projectID === app.id && value.name === 'spring-boot.maven'); + assert.ok(target, 'the effective plugin publishes a typed service target'); + const launchOptions = { execution: 'service', runtimeArguments: ['-Dlithe.message=hello world'], + arguments: ['a b', '雪', 'C:\\literal', 'comma,value', 'double"quote', "single'quote"], + environment: { LITHE_RUN_VALUE: 'Provider' }, workingDirectory: 'framework cwd', entrypoint: 'demo.app.Main' }; + const request = extra => planned({ root: selectedRoot, workspaceRoot: workspace, run: 'framework', + project: { name: app.name, path: app.path }, target: { name: target.name, path: target.path, tags: target.tags }, launchOptions, ...extra }); + const prepared = await send(build('build.prepareRunPlan', request({})).plan, 'framework-launch'); + const launch = build('build.decodeRunPreparation', { workspaceRoot: workspace, root: selectedRoot, launchOptions, result: prepared }).launch; + assert.deepEqual(launch.executable, { kind: 'toolchain', value: 'project-maven' }); + assert.equal(launch.workingDirectory, 'framework cwd'); + const transcript = join(scratch, 'framework-launch.log'); + const descriptor = openSync(transcript, 'w'); + try { + await runCommand(maven, launch.arguments, { cwd, env: { ...process.env, ...launch.environment }, + stdio: ['ignore', descriptor, descriptor], signal, timeoutMs: mavenTimeout() }); + } finally { closeSync(descriptor); } + const output = readFileSync(transcript, 'utf8'); + assert.ok(output.includes('Hello, Provider'), output); + assert.ok(output.includes('PROP=hello world'), output); + assert.ok(output.includes('CWD=' + cwd), output); + for (const argument of launchOptions.arguments) assert.ok(output.includes('ARG=' + Buffer.from(argument).toString('base64')), output); + assert.ok(!output.includes('spring-boot-maven-plugin:2.2.2.RELEASE:run (default-cli) on project reactor'), output); + await assert.rejects(send(build('build.prepareRunPlan', request({ launchOptions: { ...launchOptions, arguments: [''] } })).plan, 'framework-empty'), /preserve empty/); + const moduleTarget = current.targets.find(value => value.projectID === app.id && value.name === 'maven.module'); + const moduleOptions = { execution: 'task', runtimeArguments: [], arguments: ['validate', '-Dcustom.value=two words'], environment: {} }; + const moduleRequest = request({ run: 'module', target: { name: moduleTarget.name, path: moduleTarget.path, tags: moduleTarget.tags }, launchOptions: moduleOptions }); + const modulePlan = await send(build('build.prepareRunPlan', moduleRequest).plan, 'module-prepare'); + assert.equal(modulePlan.arguments.at(-1), '-Dcustom.value=two words'); + assert.equal(modulePlan.arguments.at(-2), 'validate'); + for (const argument of ['--file=../outside.xml', '-Pother', '-s', '-Dmaven.repo.local=/other', '-Dlithe.run.goal=other']) { + await assert.rejects(send(build('build.prepareRunPlan', { ...moduleRequest, launchOptions: { ...moduleOptions, arguments: ['validate', argument] } }).plan, + 'module-selection-override'), /build options/); + } + writeFileSync(appPom, original); + await assert.rejects(send(build('build.prepareRunPlan', request({})).plan, 'removed-framework'), /absent from the current/); + }); await report.step('publish the same normalized Maven facts and effective options to a declared consumer', () => { const consumer = JSON.parse(JSON.stringify(manifest)); consumer.id = 'org.example.maven-input-consumer'; consumer.requires.buildProviders = 6; delete consumer.buildSystems[0].modelSharing; + delete consumer.buildSystems[0].run; delete consumer.buildSystems[0].configuration; delete consumer.buildSystems[0].test.results; delete consumer.buildSystems[0].test.selectorKinds; diff --git a/scripts/verify-extension.mjs b/scripts/verify-extension.mjs index 517c197..dcdbd91 100644 --- a/scripts/verify-extension.mjs +++ b/scripts/verify-extension.mjs @@ -8,7 +8,7 @@ export function verifyExtension(jar) { { encoding: 'utf8', timeout: 5000, maxBuffer: 65536 }); assert.equal(result.status, 0, result.error?.message ?? result.stderr); const components = new Set(result.stdout.trim().split(/\r?\n/)); - for (const name of ['LitheLifecycleParticipant', 'NativeSettingsEvents', 'ReportCaptureEvents']) { + for (const name of ['LitheLifecycleParticipant', 'NativeSettingsEvents', 'ReportCaptureEvents', 'RunExecutionEvents']) { assert.ok(components.has('io.github.litheidea.maven.' + name), `The clean extension package omits ${name}`); } } From 9d8b927edb987825c082801a4a177eb53b7e489e Mon Sep 17 00:00:00 2001 From: wgw Date: Fri, 30 Oct 2026 17:01:45 +0800 Subject: [PATCH 12/24] feat(maven): prepare suspended framework JVMs through Mojo descriptors --- .../maven/backend/MavenRunPreparation.java | 9 +++ extension/pom.xml | 3 + .../litheidea/maven/RunExecutionEvents.java | 54 +++++++++++++-- .../maven/RunExecutionEventsTest.java | 66 +++++++++++++++++++ io.github.lithe-idea.maven-build/plugin.json | 2 +- scripts/process.mjs | 10 ++- scripts/test-native-core.mjs | 51 +++++++++++++- scripts/test-process.mjs | 10 +++ 8 files changed, 195 insertions(+), 10 deletions(-) create mode 100644 extension/src/test/java/io/github/litheidea/maven/RunExecutionEventsTest.java diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java index aa1a142..33bab92 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java @@ -49,6 +49,14 @@ static Map prepare(Map params, Path root, Path w if (!"1".equals(properties.get("run.preparationVersion"))) throw invalid("The Maven model cannot prepare this framework run. Refresh or update the plugin."); addArguments(arguments, "runtime", runtimeArguments); addArguments(arguments, "arguments", programArguments); + if (options.containsKey("debug")) { + Map debug = Json.object(options.get("debug")); + Object port = debug.get("port"); + if (debug.size() != 2 || !"jvm".equals(debug.get("runtime")) || !(port instanceof Number) + || ((Number) port).doubleValue() != ((Number) port).longValue() + || ((Number) port).longValue() < 1 || ((Number) port).longValue() > 65535) throw invalid("Select a valid JVM debug port."); + arguments.add("-Dlithe.run.debugPort=" + ((Number) port).longValue()); + } String entrypoint = Json.string(options, "entrypoint"); if (entrypoint != null) addProperty(arguments, properties, "run.entrypointProperty", entrypoint); if (options.containsKey("workingDirectory")) { @@ -60,6 +68,7 @@ static Map prepare(Map params, Path root, Path w arguments.add("-Dlithe.run.goal=" + properties.get("run.goal")); arguments.add("test-compile"); } else { + if (options.containsKey("debug")) throw invalid("Select a framework service to debug; arbitrary Maven goals have no JVM debug target."); if (!runtimeArguments.isEmpty() || options.containsKey("entrypoint")) throw invalid("Maven module goals do not accept application runtime or entrypoint options."); if (programArguments.isEmpty()) throw invalid("A Maven module run needs one or more goals."); modelArguments(params); // The same checked properties were supplied to the model read. diff --git a/extension/pom.xml b/extension/pom.xml index af91a24..06d45a9 100644 --- a/extension/pom.xml +++ b/extension/pom.xml @@ -41,6 +41,9 @@ 1.7.29 provided + + junitjunit4.13.2test + diff --git a/extension/src/main/java/io/github/litheidea/maven/RunExecutionEvents.java b/extension/src/main/java/io/github/litheidea/maven/RunExecutionEvents.java index 84d852b..6b96103 100644 --- a/extension/src/main/java/io/github/litheidea/maven/RunExecutionEvents.java +++ b/extension/src/main/java/io/github/litheidea/maven/RunExecutionEvents.java @@ -56,6 +56,8 @@ public RunExecutionEvents(LifecycleExecutionPlanCalculator plans, MojoExecutor e if (goal.endsWith(":" + execution.getGoal()) && framework.plugin.getArtifactId().equals(execution.getArtifactId())) { configure(execution, framework.runtimeProperty, arguments(event, "runtime")); configure(execution, framework.argumentsProperty, arguments(event, "arguments")); + String debugPort = event.getSession().getUserProperties().getProperty("lithe.run.debugPort"); + if (debugPort != null) configureDebug(execution, framework, debugPort); String cwd = event.getSession().getUserProperties().getProperty("lithe.run.workingDirectory"); if (cwd != null) { if (!"spring-boot.maven".equals(framework.provider) || execution.getMojoDescriptor().getParameters().stream() @@ -74,6 +76,52 @@ public RunExecutionEvents(LifecycleExecutionPlanCalculator plans, MojoExecutor e throw new LifecycleExecutionException("Lithe could not prepare the current Maven framework goal.", null, event.getProject(), error); } } + + /** Only Maven's resolved Mojo receives framework switches; the host supplies a port. */ + static void configureDebug(MojoExecution execution, FrameworkLaunch framework, String port) throws Exception { + int number = Integer.parseInt(port); + if (number < 1 || number > 65535) throw new IllegalArgumentException("Invalid JVM debug port."); + Parameter parameter = parameter(execution, framework.runtimeProperty); + Xpp3Dom configured = execution.getConfiguration().getChild(parameter.getName()); + List values = new ArrayList<>(); + if (configured != null) { + if (configured.getValue() != null) values.addAll(Arrays.asList(CommandLineUtils.translateCommandline(configured.getValue()))); + for (Xpp3Dom child : configured.getChildren()) if (child.getValue() != null) values.add(child.getValue()); + } + if (values.stream().anyMatch(value -> value.startsWith("-agentlib:jdwp") || value.startsWith("-Xrunjdwp"))) { + throw new IllegalArgumentException("Remove the existing JDWP agent before starting an IDE-owned debug session."); + } + if ("spring-boot.maven".equals(framework.provider)) { + values.add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:" + number); + configure(execution, framework.runtimeProperty, values); + } else if ("quarkus.maven".equals(framework.provider)) { + scalar(execution, "debug", "java.lang.String", port); + scalar(execution, "suspend", "java.lang.String", "y"); + scalar(execution, "debugHost", "java.lang.String", "127.0.0.1"); + } else if ("micronaut.maven".equals(framework.provider)) { + scalar(execution, "debug", "boolean", "true"); + scalar(execution, "debugSuspend", "boolean", "true"); + scalar(execution, "debugPort", "int", port); + scalar(execution, "debugHost", "java.lang.String", "127.0.0.1"); + } else throw new IllegalArgumentException("The current framework cannot prepare JVM debugging."); + } + + private static void scalar(MojoExecution execution, String name, String type, String text) { + if (execution.getMojoDescriptor().getParameters().stream() + .noneMatch(parameter -> name.equals(parameter.getName()) && type.equals(parameter.getType()))) { + throw new IllegalArgumentException("The framework has no compatible debug parameter: " + name); + } + Xpp3Dom value = execution.getConfiguration().getChild(name); + if (value == null) { value = new Xpp3Dom(name); execution.getConfiguration().addChild(value); } + value.setValue(text); + } + + private static Parameter parameter(MojoExecution execution, String property) { + for (Parameter parameter : execution.getMojoDescriptor().getParameters()) { + if (("${" + property + "}").equals(parameter.getExpression())) return parameter; + } + throw new IllegalArgumentException("The framework has no parameter for " + property); + } private static List arguments(ProjectExecutionEvent event, String kind) { Properties properties = event.getSession().getUserProperties(); int count = Integer.parseInt(properties.getProperty("lithe.run." + kind + ".count", "0")); @@ -90,11 +138,7 @@ private static List arguments(ProjectExecutionEvent event, String kind) /** Maven's descriptor selects string versus collection conversion for each plugin version. */ private static void configure(MojoExecution execution, String property, List values) throws Exception { if (values.isEmpty()) return; - Parameter selected = null; - for (Parameter parameter : execution.getMojoDescriptor().getParameters()) { - if (("${" + property + "}").equals(parameter.getExpression())) selected = parameter; - } - if (selected == null) throw new IllegalArgumentException("The framework has no parameter for " + property); + Parameter selected = parameter(execution, property); Xpp3Dom configuration = execution.getConfiguration(); Xpp3Dom value = configuration.getChild(selected.getName()); if (value == null) { value = new Xpp3Dom(selected.getName()); configuration.addChild(value); } diff --git a/extension/src/test/java/io/github/litheidea/maven/RunExecutionEventsTest.java b/extension/src/test/java/io/github/litheidea/maven/RunExecutionEventsTest.java new file mode 100644 index 0000000..07e5f2f --- /dev/null +++ b/extension/src/test/java/io/github/litheidea/maven/RunExecutionEventsTest.java @@ -0,0 +1,66 @@ +package io.github.litheidea.maven; + +import static org.junit.Assert.*; +import java.util.*; +import org.junit.Test; +import org.apache.maven.model.*; +import org.apache.maven.project.MavenProject; +import org.apache.maven.plugin.MojoExecution; +import org.apache.maven.plugin.descriptor.*; +import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.codehaus.plexus.util.cli.CommandLineUtils; + +/** Descriptor-bound overrides protect framework versions with incompatible debug parameters. */ +public class RunExecutionEventsTest { + @Test(timeout = 5000) public void springPreservesConfiguredArgumentsBeforeAddingOneSuspendedLoopbackAgent() throws Exception { + FrameworkLaunch framework = framework("org.springframework.boot", "spring-boot-maven-plugin"); + MojoExecution execution = execution(parameter("jvmArguments", "java.lang.String", framework.runtimeProperty)); + set(execution, "jvmArguments", "-Dmessage=\"hello world\" -Dkept=true"); + RunExecutionEvents.configureDebug(execution, framework, "51235"); + assertArrayEquals(new String[] {"-Dmessage=hello world", "-Dkept=true", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:51235"}, + CommandLineUtils.translateCommandline(value(execution, "jvmArguments"))); + assertThrows(IllegalArgumentException.class, () -> RunExecutionEvents.configureDebug(execution, framework, "51235")); + } + + @Test(timeout = 5000) public void quarkusOverridesClientModeAndRemoteBindWithOneManagedAgent() throws Exception { + MojoExecution execution = execution(parameter("jvmArgs", "java.lang.String", "jvm.args"), parameter("debug", "java.lang.String", null), parameter("suspend", "java.lang.String", null), parameter("debugHost", "java.lang.String", null)); + set(execution, "debug", "client"); set(execution, "debugHost", "0.0.0.0"); + RunExecutionEvents.configureDebug(execution, framework("io.quarkus.platform", "quarkus-maven-plugin"), "51235"); + assertEquals("51235", value(execution, "debug")); assertEquals("y", value(execution, "suspend")); + assertEquals("127.0.0.1", value(execution, "debugHost")); + } + + @Test(timeout = 5000) public void micronautUsesItsBooleanAndIntegerParameters() throws Exception { + MojoExecution execution = execution(parameter("jvmArgs", "java.lang.String", "mn.jvmArgs"), parameter("debug", "boolean", null), parameter("debugSuspend", "boolean", null), parameter("debugPort", "int", null), parameter("debugHost", "java.lang.String", null)); + RunExecutionEvents.configureDebug(execution, framework("io.micronaut.maven", "micronaut-maven-plugin"), "51235"); + assertEquals("true", value(execution, "debug")); assertEquals("true", value(execution, "debugSuspend")); + assertEquals("51235", value(execution, "debugPort")); assertEquals("127.0.0.1", value(execution, "debugHost")); + } + + @Test(timeout = 5000) public void missingOrIncompatibleHostParameterRefusesDebugInsteadOfLaunchingUnconfigured() throws Exception { + for (String type : new String[] {null, "boolean"}) { + MojoExecution execution = execution(parameter("jvmArgs", "java.lang.String", "jvm.args"), parameter("debug", "java.lang.String", null), parameter("suspend", "java.lang.String", null)); + if (type != null) execution.getMojoDescriptor().getParameters().add(parameter("debugHost", type, null)); + assertThrows(IllegalArgumentException.class, () -> RunExecutionEvents.configureDebug(execution, framework("io.quarkus", "quarkus-maven-plugin"), "51235")); + } + } + + private static FrameworkLaunch framework(String group, String artifact) { + Plugin plugin = new Plugin(); plugin.setGroupId(group); plugin.setArtifactId(artifact); plugin.setVersion("1"); + Build build = new Build(); build.addPlugin(plugin); Model model = new Model(); model.setPackaging("jar"); model.setBuild(build); + return FrameworkLaunch.find(new MavenProject(model)); + } + private static Parameter parameter(String name, String type, String property) { + Parameter parameter = new Parameter(); parameter.setName(name); parameter.setType(type); + if (property != null) parameter.setExpression("${" + property + "}"); return parameter; + } + private static MojoExecution execution(Parameter... parameters) throws Exception { + MojoDescriptor descriptor = new MojoDescriptor(); descriptor.setParameters(new ArrayList<>(Arrays.asList(parameters))); + MojoExecution execution = new MojoExecution(new Plugin(), "run", "default-cli"); execution.setMojoDescriptor(descriptor); + execution.setConfiguration(new Xpp3Dom("configuration")); return execution; + } + private static void set(MojoExecution execution, String key, String text) { + Xpp3Dom value = new Xpp3Dom(key); value.setValue(text); execution.getConfiguration().addChild(value); + } + private static String value(MojoExecution execution, String key) { return execution.getConfiguration().getChild(key).getValue(); } +} diff --git a/io.github.lithe-idea.maven-build/plugin.json b/io.github.lithe-idea.maven-build/plugin.json index 7fec8bf..45b15a0 100644 --- a/io.github.lithe-idea.maven-build/plugin.json +++ b/io.github.lithe-idea.maven-build/plugin.json @@ -4,7 +4,7 @@ "displayName": "Maven", "version": "0.1.1", "pluginAPIVersion": 3, - "requires": { "buildProviders": 10, "buildModelInputs": 1, "buildSystems": 3, "executableResolution": 2, "serverProcess": 1 }, + "requires": { "buildProviders": 11, "buildModelInputs": 1, "buildSystems": 3, "executableResolution": 2, "serverProcess": 1 }, "vendor": { "id": "io.github.lithe-idea", "displayName": "Lithe Community", diff --git a/scripts/process.mjs b/scripts/process.mjs index b552db7..9287b29 100644 --- a/scripts/process.mjs +++ b/scripts/process.mjs @@ -22,6 +22,7 @@ export function mavenTimeout() { export function runCommand(command, args, { cwd = process.cwd(), env = process.env, stdio = "inherit", timeoutMs = MAVEN_TIMEOUT_MS, graceMs = GRACE_MS, killWaitMs = KILL_WAIT_MS, signal, + onOutput, } = {}) { for (const [name, value] of Object.entries({ timeoutMs, graceMs, killWaitMs })) { if (!Number.isSafeInteger(value) || value < 1 || value > 3_600_000) { @@ -34,7 +35,7 @@ export function runCommand(command, args, { const invocation = [command, ...args].map((arg) => JSON.stringify(arg)).join(" "); return new Promise((resolve, reject) => { - const child = spawn(command, args, { cwd, env, stdio, detached: true, shell: false }); + const child = spawn(command, args, { cwd, env, stdio: onOutput ? ["ignore", "pipe", "pipe"] : stdio, detached: true, shell: false }); let closed = false; let code; let exitSignal; @@ -102,6 +103,13 @@ export function runCommand(command, args, { failure ??= diagnostic(`command timed out (limit ${timeoutMs} ms)`); stop(); }, timeoutMs); + if (onOutput) for (const stream of [child.stdout, child.stderr]) { + stream.setEncoding("utf8"); + stream.on("data", chunk => { + try { onOutput(chunk); } + catch (error) { failure ??= diagnostic(`output consumer failed: ${error.message}`); stop(); } + }); + } child.once("error", (error) => { failure ??= diagnostic(`cannot run command: ${error.message}`); stop(); diff --git a/scripts/test-native-core.mjs b/scripts/test-native-core.mjs index 950af36..21b887b 100644 --- a/scripts/test-native-core.mjs +++ b/scripts/test-native-core.mjs @@ -3,8 +3,9 @@ import assert from 'node:assert/strict'; import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, truncateSync, writeFileSync, openSync, closeSync } from 'node:fs'; import { tmpdir } from 'node:os'; -import { join, resolve } from 'node:path'; +import { join, resolve, delimiter } from 'node:path'; import { spawnSync } from 'node:child_process'; +import { createServer } from 'node:net'; import { BackendClient, bounded } from './backend-client.mjs'; import { coreCommand } from './core-client.mjs'; import { bundleManifest } from './bundle-manifest.mjs'; @@ -45,7 +46,7 @@ await withInterrupts(async (signal) => { state: join(scratch, 'state'), timeoutMs: mavenTimeout() }); await report.step('Core admits the new Maven capability and produces only Provider plans', async () => { coreCommand('plugins.declarative.validate', { manifest }); - assert.equal((await client.initialize(workspace, [10])).capabilities.experimental.litheBuild.version, 10); + assert.equal((await client.initialize(workspace, [11])).capabilities.experimental.litheBuild.version, 11); for (const task of manifest.buildSystems[0].tasks) { assert.equal(task.source, 'provider'); assert.deepEqual(task.arguments, []); } assert.equal(manifest.buildSystems[0].test.source, 'provider'); }); @@ -359,12 +360,14 @@ await withInterrupts(async (signal) => { const appPom = join(directory, 'app/pom.xml'); const original = readFileSync(appPom, 'utf8'); writeFileSync(appPom, original.replace('', `org.springframework.boot - spring-boot-maven-plugin2.2.2.RELEASE`)); + spring-boot-maven-plugin2.2.2.RELEASE + -Dlithe.pom=preserved`)); writeFileSync(join(directory, 'app/src/main/java/demo/app/Main.java'), `package demo.app; import demo.core.Greeter; public final class Main { public static void main(String[] args) throws Exception { System.out.println(new Greeter().greet(System.getenv("LITHE_RUN_VALUE"))); System.out.println("PROP="+System.getProperty("lithe.message")); + System.out.println("POMFLAG="+System.getProperty("lithe.pom")); System.out.println("CWD="+new java.io.File(".").getCanonicalPath()); for (String arg : args) System.out.println("ARG="+java.util.Base64.getEncoder().encodeToString(arg.getBytes("UTF-8"))); } }`); @@ -395,6 +398,48 @@ await withInterrupts(async (signal) => { assert.ok(output.includes('PROP=hello world'), output); assert.ok(output.includes('CWD=' + cwd), output); for (const argument of launchOptions.arguments) assert.ok(output.includes('ARG=' + Buffer.from(argument).toString('base64')), output); + // The standard JDI connector proves a real suspended JVM is reachable; + // no second implementation of JDWP or Maven launch semantics is involved. + const allocator = createServer(), allocation = new AbortController(); + const port = await bounded(new Promise((resolve, reject) => { + allocator.once('error', reject); + allocator.listen({ port: 0, host: '127.0.0.1', signal: allocation.signal }, () => { const port = allocator.address().port; allocator.close(error => error ? reject(error) : resolve(port)); }); + }), 'allocate loopback debug port', 5000).finally(() => allocation.abort()); + const debugOptions = { ...launchOptions, runtimeArguments: [], debug: { runtime: 'jvm', port } }; + const debugResult = await send(build('build.prepareRunPlan', request({ launchOptions: debugOptions })).plan, 'framework-debug'); + const debugPlan = build('build.decodeRunPreparation', { workspaceRoot: workspace, root: selectedRoot, launchOptions: debugOptions, result: debugResult }).launch; + const helper = join(scratch, 'ResumeJvm.java'); + writeFileSync(helper, `import com.sun.jdi.*; import com.sun.jdi.connect.*; import java.util.*; + public class ResumeJvm { public static void main(String[] args) throws Exception { + AttachingConnector connector = Bootstrap.virtualMachineManager().attachingConnectors().stream() + .filter(value -> value.name().equals("com.sun.jdi.SocketAttach")).findFirst().get(); + Map options = connector.defaultArguments(); + options.get("hostname").setValue("127.0.0.1"); options.get("port").setValue(args[0]); options.get("timeout").setValue("5000"); + VirtualMachine vm = connector.attach(options); try { vm.resume(); } finally { try { vm.dispose(); } catch (VMDisconnectedException exited) {} } + } }`); + const java = process.env.LITHE_TEST_JAVA ?? 'java'; + const javac = java.includes('/') ? join(resolve(java, '..'), 'javac') : 'javac'; + await runCommand(javac, [helper], { signal, timeoutMs: 10000 }); + let debugOutput = '', ready; + const listening = new Promise(resolve => { ready = resolve; }); + const controller = new AbortController(), abort = () => controller.abort(signal.reason); + signal.addEventListener('abort', abort, { once: true }); + const running = runCommand(maven, debugPlan.arguments, { cwd, env: { ...process.env, ...debugPlan.environment }, + signal: controller.signal, timeoutMs: mavenTimeout(), onOutput: chunk => { + debugOutput = (debugOutput + chunk).slice(-100000); + if (debugOutput.includes('Listening for transport dt_socket at address: ' + port)) ready(); + } }); + try { + await bounded(Promise.race([listening, running.then(() => { throw new Error('JVM exited before the debug listener: ' + debugOutput); })]), 'suspended framework JVM', 20000); + assert.ok(!debugOutput.includes('Hello, Provider'), 'the application must be suspended before attachment'); + const tools = join(process.env.JAVA_HOME ?? resolve(realpathSync(java), '../..'), 'lib/tools.jar'); + await runCommand(java, ['-cp', scratch + (existsSync(tools) ? delimiter + tools : ''), 'ResumeJvm', String(port)], { signal, timeoutMs: 10000 }); + await running; + assert.ok(debugOutput.includes('Hello, Provider') && debugOutput.includes('POMFLAG=preserved'), debugOutput); + } finally { + signal.removeEventListener('abort', abort); controller.abort(); + await running.catch(() => {}); + } assert.ok(!output.includes('spring-boot-maven-plugin:2.2.2.RELEASE:run (default-cli) on project reactor'), output); await assert.rejects(send(build('build.prepareRunPlan', request({ launchOptions: { ...launchOptions, arguments: [''] } })).plan, 'framework-empty'), /preserve empty/); const moduleTarget = current.targets.find(value => value.projectID === app.id && value.name === 'maven.module'); diff --git a/scripts/test-process.mjs b/scripts/test-process.mjs index 171eed8..fe6c07a 100644 --- a/scripts/test-process.mjs +++ b/scripts/test-process.mjs @@ -56,6 +56,16 @@ await withInterrupts(async (signal) => { }; try { + await check("streamed output preserves UTF-8 and a failing consumer reaps its command", async () => { + let output = ""; + await runCommand(process.execPath, ["-e", "process.stdout.write('雪');process.stderr.write('stderr')"], { + onOutput: chunk => { output += chunk; }, timeoutMs: 2000, + }); + assert.ok(output.includes("雪") && output.includes("stderr")); + await assert.rejects(runCommand(process.execPath, ["-e", "process.stdout.write('ready');setInterval(()=>{},1000)"], { + onOutput: () => { throw new Error("consumer rejected output"); }, timeoutMs: 2000, + }), /consumer rejected output/); + }); await check("success and nonzero exit preserve status, cwd, and command diagnostics", async () => { const listeners = [process.listenerCount("SIGINT"), process.listenerCount("SIGTERM")]; await runCommand(process.execPath, ["-e", "process.exit(0)"], { cwd: scratch, stdio: "ignore", timeoutMs: 2_000 }); From 1ace1bdf916a9855c12a5ec4a1bba8985379aea0 Mon Sep 17 00:00:00 2001 From: wgw Date: Fri, 30 Oct 2026 19:20:58 +0800 Subject: [PATCH 13/24] fix(maven): evaluate real framework debug parameters and verify JDI workflows --- .github/workflows/ci.yml | 11 ++ README.md | 12 ++ .../litheidea/maven/RunExecutionEvents.java | 25 ++- .../maven/RunExecutionEventsTest.java | 61 ++++++- scripts/test-framework-debug.mjs | 154 ++++++++++++++++++ scripts/test-native-core.mjs | 6 +- 6 files changed, 256 insertions(+), 13 deletions(-) create mode 100644 scripts/test-framework-debug.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 69695e7..2c7c478 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -181,6 +181,17 @@ jobs: export LITHE_TEST_MAVEN="${MVN:-$(command -v mvn)}" node scripts/test-configuration.mjs node scripts/test-native-core.mjs + - name: Verify Quarkus and Micronaut suspended JVMs with standard JDI + if: inputs.core-revision != '' && matrix.maven == 'runner' + env: + # These pinned framework versions require Java 17 and modern Maven; + # the Java 8 / Maven 3.6.3 Provider lane above remains independent. + LITHE_TEST_JAVA: ${{ env.JAVA_HOME_17_X64 }}/bin/java + LITHE_MAVEN_TIMEOUT_MS: 300000 + run: | + export LITHE_CORE_LIBRARY="$GITHUB_WORKSPACE/.artifacts/core-source/rust/target/debug/liblithe_core.so" + export LITHE_TEST_MAVEN="$(command -v mvn)" + node scripts/test-framework-debug.mjs - name: Prove the release inputs stayed unchanged run: | git diff --exit-code -- sdk.lock.json backend/pom.xml extension/pom.xml io.github.lithe-idea.maven-build diff --git a/README.md b/README.md index def6ee7..b70bb7c 100644 --- a/README.md +++ b/README.md @@ -302,3 +302,15 @@ Wrapper 元数据 `maven.wrapper` / `maven.minimumVersion` 来自所选 reactor 仍经类型化 Build 选项传递,不接受额外 CLI 覆盖制造第二套配置。属性和环境也 参与准备时的有效模型读取。开发组合可用 `scripts/package-development.mjs` 及 `scripts/test-native-core.mjs` 验证;正式 SDK 锁定和发行条件保持不变。 + +开发协议 11 的 JVM 调试由宿主选择本机端口,后端按当前 Mojo 描述符设置回环监听和 +启动前暂停。参数绑定同时识别 Maven 的 `property` 与 `defaultValue` 表达式,例如 +Quarkus 的 `jvm.args` 属于后者。Spring Boot 保留已有 JVM 参数,Quarkus/Micronaut +使用框架自带的调试开关;遇到重复 JDWP 或不兼容描述符明确拒绝。 + +`scripts/test-framework-debug.mjs` 用固定的 Quarkus 3.15.5、Micronaut Maven Plugin +4.7.2 和真实 reactor 验证暂停、标准 JDI 连接/恢复、参数、环境及兄弟模块依赖。 +此集成使用 Java 17+ 和 Maven 3.9+,不改变 Provider 自身的 Java 8 / +Maven 3.6.3 支持声明。用 `LITHE_TEST_PACKAGE`、`LITHE_CORE_LIBRARY` 指向显式开发组合, +`LITHE_TEST_JAVA` 与 `LITHE_TEST_MAVEN` 提供绝对工具路径;输出及逐项报告写入 +`LITHE_REPORT_DIR`,进程退出前清理全部所持 JVM。此测试不代替宿主 Debug UI 验收。 diff --git a/extension/src/main/java/io/github/litheidea/maven/RunExecutionEvents.java b/extension/src/main/java/io/github/litheidea/maven/RunExecutionEvents.java index 6b96103..d0dadf4 100644 --- a/extension/src/main/java/io/github/litheidea/maven/RunExecutionEvents.java +++ b/extension/src/main/java/io/github/litheidea/maven/RunExecutionEvents.java @@ -7,6 +7,7 @@ import java.util.Arrays; import java.util.Properties; import org.apache.maven.plugin.MojoExecution; +import org.apache.maven.plugin.PluginParameterExpressionEvaluator; import org.apache.maven.plugin.descriptor.Parameter; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.cli.CommandLineUtils; @@ -15,6 +16,7 @@ import javax.inject.Named; import javax.inject.Singleton; import org.apache.maven.execution.ProjectExecutionEvent; +import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.ProjectExecutionListener; import org.apache.maven.lifecycle.LifecycleExecutionException; import org.apache.maven.lifecycle.internal.GoalTask; @@ -57,7 +59,7 @@ public RunExecutionEvents(LifecycleExecutionPlanCalculator plans, MojoExecutor e configure(execution, framework.runtimeProperty, arguments(event, "runtime")); configure(execution, framework.argumentsProperty, arguments(event, "arguments")); String debugPort = event.getSession().getUserProperties().getProperty("lithe.run.debugPort"); - if (debugPort != null) configureDebug(execution, framework, debugPort); + if (debugPort != null) configureDebug(execution, framework, debugPort, event.getSession()); String cwd = event.getSession().getUserProperties().getProperty("lithe.run.workingDirectory"); if (cwd != null) { if (!"spring-boot.maven".equals(framework.provider) || execution.getMojoDescriptor().getParameters().stream() @@ -78,15 +80,25 @@ public RunExecutionEvents(LifecycleExecutionPlanCalculator plans, MojoExecutor e } /** Only Maven's resolved Mojo receives framework switches; the host supplies a port. */ - static void configureDebug(MojoExecution execution, FrameworkLaunch framework, String port) throws Exception { + static void configureDebug(MojoExecution execution, FrameworkLaunch framework, String port, MavenSession session) throws Exception { int number = Integer.parseInt(port); if (number < 1 || number > 65535) throw new IllegalArgumentException("Invalid JVM debug port."); Parameter parameter = parameter(execution, framework.runtimeProperty); + PluginParameterExpressionEvaluator evaluator = new PluginParameterExpressionEvaluator(session, execution); Xpp3Dom configured = execution.getConfiguration().getChild(parameter.getName()); List values = new ArrayList<>(); if (configured != null) { - if (configured.getValue() != null) values.addAll(Arrays.asList(CommandLineUtils.translateCommandline(configured.getValue()))); - for (Xpp3Dom child : configured.getChildren()) if (child.getValue() != null) values.add(child.getValue()); + Object value = evaluator.evaluate(configured.getValue()); + if (value == null) value = evaluator.evaluate(configured.getAttribute("default-value")); + if (value != null) values.addAll(Arrays.asList(CommandLineUtils.translateCommandline(value.toString()))); + for (Xpp3Dom child : configured.getChildren()) { + Object argument = evaluator.evaluate(child.getValue()); + if (argument != null) values.add(argument.toString()); + } + } else { + Object value = evaluator.evaluate(parameter.getExpression()); + if (value == null) value = evaluator.evaluate(parameter.getDefaultValue()); + if (value != null) values.addAll(Arrays.asList(CommandLineUtils.translateCommandline(value.toString()))); } if (values.stream().anyMatch(value -> value.startsWith("-agentlib:jdwp") || value.startsWith("-Xrunjdwp"))) { throw new IllegalArgumentException("Remove the existing JDWP agent before starting an IDE-owned debug session."); @@ -118,7 +130,10 @@ private static void scalar(MojoExecution execution, String name, String type, St private static Parameter parameter(MojoExecution execution, String property) { for (Parameter parameter : execution.getMojoDescriptor().getParameters()) { - if (("${" + property + "}").equals(parameter.getExpression())) return parameter; + // Plugin tools retain @Parameter(defaultValue="${...}") separately + // from @Parameter(property="..."). Both are Maven-owned bindings. + String binding = "${" + property + "}"; + if (binding.equals(parameter.getExpression()) || binding.equals(parameter.getDefaultValue())) return parameter; } throw new IllegalArgumentException("The framework has no parameter for " + property); } diff --git a/extension/src/test/java/io/github/litheidea/maven/RunExecutionEventsTest.java b/extension/src/test/java/io/github/litheidea/maven/RunExecutionEventsTest.java index 07e5f2f..55136b7 100644 --- a/extension/src/test/java/io/github/litheidea/maven/RunExecutionEventsTest.java +++ b/extension/src/test/java/io/github/litheidea/maven/RunExecutionEventsTest.java @@ -2,9 +2,11 @@ import static org.junit.Assert.*; import java.util.*; +import java.io.StringReader; import org.junit.Test; import org.apache.maven.model.*; import org.apache.maven.project.MavenProject; +import org.apache.maven.execution.*; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.descriptor.*; import org.codehaus.plexus.util.xml.Xpp3Dom; @@ -16,23 +18,40 @@ public class RunExecutionEventsTest { FrameworkLaunch framework = framework("org.springframework.boot", "spring-boot-maven-plugin"); MojoExecution execution = execution(parameter("jvmArguments", "java.lang.String", framework.runtimeProperty)); set(execution, "jvmArguments", "-Dmessage=\"hello world\" -Dkept=true"); - RunExecutionEvents.configureDebug(execution, framework, "51235"); + configureDebug(execution, framework, "51235"); assertArrayEquals(new String[] {"-Dmessage=hello world", "-Dkept=true", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:51235"}, CommandLineUtils.translateCommandline(value(execution, "jvmArguments"))); - assertThrows(IllegalArgumentException.class, () -> RunExecutionEvents.configureDebug(execution, framework, "51235")); + assertThrows(IllegalArgumentException.class, () -> configureDebug(execution, framework, "51235")); } @Test(timeout = 5000) public void quarkusOverridesClientModeAndRemoteBindWithOneManagedAgent() throws Exception { MojoExecution execution = execution(parameter("jvmArgs", "java.lang.String", "jvm.args"), parameter("debug", "java.lang.String", null), parameter("suspend", "java.lang.String", null), parameter("debugHost", "java.lang.String", null)); set(execution, "debug", "client"); set(execution, "debugHost", "0.0.0.0"); - RunExecutionEvents.configureDebug(execution, framework("io.quarkus.platform", "quarkus-maven-plugin"), "51235"); + configureDebug(execution, framework("io.quarkus.platform", "quarkus-maven-plugin"), "51235"); assertEquals("51235", value(execution, "debug")); assertEquals("y", value(execution, "suspend")); assertEquals("127.0.0.1", value(execution, "debugHost")); } + @Test(timeout = 5000) public void quarkusDefaultValueBindingsAreReadThroughMavensDescriptorBuilder() throws Exception { + PluginDescriptor plugin = new PluginDescriptorBuilder().build(new StringReader( + "io.quarkus.platformquarkus-maven-plugin" + + "3.15.5quarkusdev" + + "jvmArgsjava.lang.String" + + "debugjava.lang.String" + + "suspendjava.lang.String" + + "debugHostjava.lang.String" + + "" + + "")); + MojoExecution execution = new MojoExecution(new Plugin(), "dev", "default-cli"); + execution.setMojoDescriptor(plugin.getMojo("dev")); execution.setConfiguration(new Xpp3Dom("configuration")); + assertNull(execution.getMojoDescriptor().getParameters().get(0).getExpression()); + configureDebug(execution, framework("io.quarkus.platform", "quarkus-maven-plugin"), "51235"); + assertEquals("51235", value(execution, "debug")); assertEquals("y", value(execution, "suspend")); + } + @Test(timeout = 5000) public void micronautUsesItsBooleanAndIntegerParameters() throws Exception { MojoExecution execution = execution(parameter("jvmArgs", "java.lang.String", "mn.jvmArgs"), parameter("debug", "boolean", null), parameter("debugSuspend", "boolean", null), parameter("debugPort", "int", null), parameter("debugHost", "java.lang.String", null)); - RunExecutionEvents.configureDebug(execution, framework("io.micronaut.maven", "micronaut-maven-plugin"), "51235"); + configureDebug(execution, framework("io.micronaut.maven", "micronaut-maven-plugin"), "51235"); assertEquals("true", value(execution, "debug")); assertEquals("true", value(execution, "debugSuspend")); assertEquals("51235", value(execution, "debugPort")); assertEquals("127.0.0.1", value(execution, "debugHost")); } @@ -41,10 +60,38 @@ public class RunExecutionEventsTest { for (String type : new String[] {null, "boolean"}) { MojoExecution execution = execution(parameter("jvmArgs", "java.lang.String", "jvm.args"), parameter("debug", "java.lang.String", null), parameter("suspend", "java.lang.String", null)); if (type != null) execution.getMojoDescriptor().getParameters().add(parameter("debugHost", type, null)); - assertThrows(IllegalArgumentException.class, () -> RunExecutionEvents.configureDebug(execution, framework("io.quarkus", "quarkus-maven-plugin"), "51235")); + assertThrows(IllegalArgumentException.class, () -> configureDebug(execution, framework("io.quarkus", "quarkus-maven-plugin"), "51235")); } } + @Test(timeout = 5000) public void mavenEvaluatesConfiguredAndDefaultArgumentsBeforeDuplicateAgentChecks() throws Exception { + for (boolean defaultValue : new boolean[] { false, true }) { + MojoExecution execution = execution(parameter("jvmArguments", "java.lang.String", "spring-boot.run.jvmArguments")); + set(execution, "jvmArguments", "${fixture.jvmArgs}"); + if (defaultValue) { + execution.getConfiguration().getChild("jvmArguments").setValue(null); + execution.getConfiguration().getChild("jvmArguments").setAttribute("default-value", "${fixture.jvmArgs}"); + } + MavenSession session = session(); + session.getUserProperties().setProperty("fixture.jvmArgs", "-Dkept=true"); + FrameworkLaunch framework = framework("org.springframework.boot", "spring-boot-maven-plugin"); + RunExecutionEvents.configureDebug(execution, framework, "51235", session); + assertTrue(value(execution, "jvmArguments").contains("-Dkept=true")); + set(execution, "jvmArguments", "${fixture.jvmArgs}"); + if (defaultValue) execution.getConfiguration().getChild("jvmArguments").setValue(null); + session.getUserProperties().setProperty("fixture.jvmArgs", "-agentlib:jdwp=transport=dt_socket"); + assertThrows(IllegalArgumentException.class, () -> RunExecutionEvents.configureDebug(execution, framework, "51235", session)); + } + } + + private static void configureDebug(MojoExecution execution, FrameworkLaunch framework, String port) throws Exception { + RunExecutionEvents.configureDebug(execution, framework, port, session()); + } + private static MavenSession session() { + MavenSession session = new MavenSession(null, null, new DefaultMavenExecutionRequest(), new DefaultMavenExecutionResult()); + session.setCurrentProject(new MavenProject()); return session; + } + private static FrameworkLaunch framework(String group, String artifact) { Plugin plugin = new Plugin(); plugin.setGroupId(group); plugin.setArtifactId(artifact); plugin.setVersion("1"); Build build = new Build(); build.addPlugin(plugin); Model model = new Model(); model.setPackaging("jar"); model.setBuild(build); @@ -60,7 +107,9 @@ private static MojoExecution execution(Parameter... parameters) throws Exception execution.setConfiguration(new Xpp3Dom("configuration")); return execution; } private static void set(MojoExecution execution, String key, String text) { - Xpp3Dom value = new Xpp3Dom(key); value.setValue(text); execution.getConfiguration().addChild(value); + Xpp3Dom value = execution.getConfiguration().getChild(key); + if (value == null) { value = new Xpp3Dom(key); execution.getConfiguration().addChild(value); } + value.setValue(text); } private static String value(MojoExecution execution, String key) { return execution.getConfiguration().getChild(key).getValue(); } } diff --git a/scripts/test-framework-debug.mjs b/scripts/test-framework-debug.mjs new file mode 100644 index 0000000..5f71450 --- /dev/null +++ b/scripts/test-framework-debug.mjs @@ -0,0 +1,154 @@ +#!/usr/bin/env node +// Real framework Mojos, Core plans, and standard JDI; every owned JVM is reaped. +import assert from 'node:assert/strict'; +import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { delimiter, dirname, join, resolve } from 'node:path'; +import { createServer } from 'node:net'; +import { BackendClient, bounded } from './backend-client.mjs'; +import { coreCommand } from './core-client.mjs'; +import { bundleManifest } from './bundle-manifest.mjs'; +import { createReport } from './report.mjs'; +import { mavenTimeout, runCommand, withInterrupts } from './process.mjs'; + +const pkg = resolve(process.env.LITHE_TEST_PACKAGE ?? 'dist/package/io.github.lithe-idea.maven-build'); +const manifest = JSON.parse(readFileSync(join(pkg, 'plugin.json'))); +const before = bundleManifest(pkg); +const java = process.env.LITHE_TEST_JAVA ?? (process.env.JAVA_HOME && join(process.env.JAVA_HOME, 'bin/java')); +const maven = process.env.LITHE_TEST_MAVEN ?? process.env.MVN; +assert.ok(java?.startsWith('/'), 'Set LITHE_TEST_JAVA to an absolute JDK executable (Java 17+ for these framework fixtures)'); +assert.ok(maven?.startsWith('/'), 'Set LITHE_TEST_MAVEN to an absolute Maven executable (Maven 3.9+ for this acceptance lane)'); +const scratch = realpathSync(mkdtempSync(join(tmpdir(), 'lithe-framework-debug-'))); +const workspace = join(scratch, 'workspace'); +const report = createReport('framework-jvm-debug'); +let client; +let sequence = 0; + +const frameworkCases = [ + { name: 'quarkus', provider: 'quarkus.maven', version: '3.15.5', group: 'io.quarkus.platform', artifact: 'quarkus-maven-plugin', + dependencies: 'io.quarkusquarkus-arc3.15.5', + management: 'io.quarkus.platformquarkus-bom3.15.5pomimport', + lifecycle: 'build', + configuration: '-Dlithe.pom=preserved', + imports: 'import io.quarkus.runtime.QuarkusApplication; import io.quarkus.runtime.annotations.QuarkusMain;', + declaration: '@QuarkusMain public class Main implements QuarkusApplication { public int run(String... args) throws Exception {', + end: 'return 0; } }' }, + { name: 'micronaut', provider: 'micronaut.maven', version: '4.7.2', group: 'io.micronaut.maven', artifact: 'micronaut-maven-plugin', + // The plugin declares this parameter required even when test resources are + // disabled. Use its own 4.7.2 parent POM's version; no Docker server is started. + dependencies: '', configuration: 'demo.app.Main-Dlithe.pom=preserved2.6.2false', + imports: '', declaration: 'public class Main { public static void main(String[] args) throws Exception {', end: '} }' }, +]; + +async function unusedPort() { + const server = createServer(), allocation = new AbortController(); + try { + return await bounded(new Promise((resolve, reject) => { + server.once('error', reject); + server.listen({ host: '127.0.0.1', port: 0, signal: allocation.signal }, () => { + const port = server.address().port; + server.close(error => error ? reject(error) : resolve(port)); + }); + }), 'allocate framework debug port', 5000); + } finally { allocation.abort(); } +} + +await withInterrupts(async signal => { + const stop = () => client?.kill(); + signal.addEventListener('abort', stop, { once: true }); + try { + mkdirSync(workspace); + const helper = join(scratch, 'ResumeFramework.java'); + writeFileSync(helper, `import com.sun.jdi.*; import com.sun.jdi.connect.*; import java.util.*; + public class ResumeFramework { public static void main(String[] args) throws Exception { + AttachingConnector connector = Bootstrap.virtualMachineManager().attachingConnectors().stream() + .filter(value -> value.name().equals("com.sun.jdi.SocketAttach")).findFirst().get(); + Map options = connector.defaultArguments(); + options.get("hostname").setValue("127.0.0.1"); options.get("port").setValue(args[0]); options.get("timeout").setValue("5000"); + VirtualMachine vm = connector.attach(options); try { vm.resume(); } finally { try { vm.dispose(); } catch (VMDisconnectedException exited) {} } + } }`); + const tools = join(resolve(java, '../..'), 'lib/tools.jar'); + await report.step('compile the standard JDI attach/resume helper', () => runCommand(join(dirname(java), 'javac'), + [...(existsSync(tools) ? ['-cp', tools] : []), helper], { signal, timeoutMs: 10000 })); + client = new BackendClient({ java, jar: join(pkg, 'lib/lithe-maven-backend.jar'), state: join(scratch, 'state'), timeoutMs: mavenTimeout() }); + await client.initialize(workspace, [11]); + for (const fixture of frameworkCases) { + await report.step(`${fixture.name} ${fixture.version}: current model, suspended JVM, JDI resume, argv and reactor dependency`, async () => { + const root = `${fixture.name} reactor`, directory = join(workspace, root); + cpSync(resolve('test/fixtures/reactor'), directory, { recursive: true }); + // A fresh version proves the sibling comes from this reactor, never the local repository. + const version = `debug-${fixture.name}-${process.pid}-${Date.now()}`; + for (const module of ['', 'app', 'core']) { + const pom = join(directory, module, 'pom.xml'); + let text = readFileSync(pom, 'utf8').replaceAll('1.0.0-SNAPSHOT', version).replace('8', '17'); + if (module === '') text = text.replace('', (fixture.management ?? '') + ''); + writeFileSync(pom, text); + } + const pom = join(directory, 'app/pom.xml'); + writeFileSync(pom, readFileSync(pom, 'utf8').replace('', fixture.dependencies + '') + .replace('', `${fixture.group}${fixture.artifact} + ${fixture.version}${fixture.lifecycle ?? ''}${fixture.configuration}`)); + const marker = `FRAMEWORK=${fixture.name}:Hello, Provider`; + writeFileSync(join(directory, 'app/src/main/java/demo/app/Main.java'), `package demo.app; import demo.core.Greeter; ${fixture.imports} + ${fixture.declaration} + System.out.println("FRAMEWORK=${fixture.name}:"+new Greeter().greet(System.getenv("LITHE_RUN_VALUE"))); + System.out.println("POMFLAG="+System.getProperty("lithe.pom")); + for (String arg : args) System.out.println("ARG="+java.util.Base64.getEncoder().encodeToString(arg.getBytes("UTF-8"))); + ${fixture.end}`); + const plan = (command, request) => coreCommand(command, { manifest, buildSystemID: 'maven', request }); + const planned = extra => ({ root, options: {}, pluginDirectory: pkg, workspaceStateDirectory: join(scratch, 'state'), tool: { executable: maven }, ...extra }); + const send = async value => client.request(value.provider.method, { ...value.provider.params, operationID: `framework-${++sequence}` }); + const current = plan('build.decodeModel', { workspaceRoot: workspace, root, + result: await send(plan('build.modelPlan', planned({})).plan) }).model; + const app = current.projects.find(value => value.name === 'app'); + const target = current.targets.find(value => value.projectID === app.id && value.name === fixture.provider); + assert.ok(target, `${fixture.name} must publish its real effective target`); + const port = await unusedPort(); + const launchOptions = { execution: 'service', runtimeArguments: [], arguments: ['a b', '雪'], + environment: { LITHE_RUN_VALUE: 'Provider' }, debug: { runtime: 'jvm', port } }; + const prepared = await send(plan('build.prepareRunPlan', planned({ workspaceRoot: workspace, run: 'framework', + project: { name: app.name, path: app.path }, target: { name: target.name, path: target.path, tags: target.tags }, launchOptions })).plan); + const launch = plan('build.decodeRunPreparation', { workspaceRoot: workspace, root, launchOptions, result: prepared }).launch; + let output = '', ready, ran; + const listening = new Promise(resolve => { ready = resolve; }), application = new Promise(resolve => { ran = resolve; }); + const controller = new AbortController(), abort = () => controller.abort(signal.reason); + signal.addEventListener('abort', abort, { once: true }); + const running = runCommand(maven, launch.arguments, { cwd: join(workspace, launch.workingDirectory), + env: { ...process.env, ...launch.environment }, signal: controller.signal, timeoutMs: mavenTimeout(), + onOutput: chunk => { + output = (output + chunk).slice(-500000); + if (output.includes('Listening for transport dt_socket at address: ' + port)) ready(); + if (output.includes(marker) && output.includes('POMFLAG=preserved') + && launchOptions.arguments.every(arg => output.includes('ARG=' + Buffer.from(arg).toString('base64')))) ran(); + } }); + const completed = running.then(() => { throw new Error('Framework exited before acceptance: ' + output); }); + // Attach the rejection handlers before any watchdog can reject the process. + completed.catch(() => {}); + try { + await bounded(Promise.race([listening, completed]), `${fixture.name} suspended JVM`, mavenTimeout()); + assert.ok(!output.includes(marker), 'application must not execute before JDI attachment'); + await runCommand(java, ['-cp', scratch + (existsSync(tools) ? delimiter + tools : ''), 'ResumeFramework', String(port)], { signal, timeoutMs: 10000 }); + await bounded(Promise.race([application, completed]), `${fixture.name} resumed application`, 30000); + } catch (error) { throw new Error(`${error.message}\n${output}`, { cause: error }); } + finally { + signal.removeEventListener('abort', abort); controller.abort(); + await running.catch(error => { + if (/process group did not disappear|cleanup:/.test(error.message)) throw error; + }); + const reports = resolve(process.env.LITHE_REPORT_DIR ?? '.artifacts/test-stability'); + mkdirSync(reports, { recursive: true }); + writeFileSync(join(reports, `${fixture.name}-runtime.log`), output); + } + }); + } + await report.step('stop the backend and preserve installed plugin bytes', async () => { + assert.equal(await client.close(), 0); + assert.deepEqual(bundleManifest(pkg), before); + }); + } catch (error) { process.exitCode = 1; report.failure('framework debug acceptance failed', error); console.error(error.stack); } + finally { + signal.removeEventListener('abort', stop); stop(); + if (client) await bounded(client.exited, 'framework backend cleanup').catch(error => { process.exitCode = 1; console.error(error); }); + rmSync(scratch, { recursive: true, force: true }); report.write(); + } +}); diff --git a/scripts/test-native-core.mjs b/scripts/test-native-core.mjs index 21b887b..8d3ad8c 100644 --- a/scripts/test-native-core.mjs +++ b/scripts/test-native-core.mjs @@ -419,7 +419,10 @@ await withInterrupts(async (signal) => { } }`); const java = process.env.LITHE_TEST_JAVA ?? 'java'; const javac = java.includes('/') ? join(resolve(java, '..'), 'javac') : 'javac'; - await runCommand(javac, [helper], { signal, timeoutMs: 10000 }); + // JDI lives in tools.jar on Java 8, including at javac time. Resolve it + // from the selected helper JDK, not Maven's potentially different JAVA_HOME. + const tools = join(java.includes('/') ? resolve(java, '../..') : process.env.JAVA_HOME ?? '', 'lib/tools.jar'); + await runCommand(javac, [...(existsSync(tools) ? ['-cp', tools] : []), helper], { signal, timeoutMs: 10000 }); let debugOutput = '', ready; const listening = new Promise(resolve => { ready = resolve; }); const controller = new AbortController(), abort = () => controller.abort(signal.reason); @@ -432,7 +435,6 @@ await withInterrupts(async (signal) => { try { await bounded(Promise.race([listening, running.then(() => { throw new Error('JVM exited before the debug listener: ' + debugOutput); })]), 'suspended framework JVM', 20000); assert.ok(!debugOutput.includes('Hello, Provider'), 'the application must be suspended before attachment'); - const tools = join(process.env.JAVA_HOME ?? resolve(realpathSync(java), '../..'), 'lib/tools.jar'); await runCommand(java, ['-cp', scratch + (existsSync(tools) ? delimiter + tools : ''), 'ResumeJvm', String(port)], { signal, timeoutMs: 10000 }); await running; assert.ok(debugOutput.includes('Hello, Provider') && debugOutput.includes('POMFLAG=preserved'), debugOutput); From 8c853473aee6018a40c751c25c4927dec557ffb1 Mon Sep 17 00:00:00 2001 From: wgw Date: Fri, 30 Oct 2026 22:01:45 +0800 Subject: [PATCH 14/24] test: exercise Windows workspace with real Maven Provider --- .github/workflows/ci.yml | 13 +++ README.md | 8 ++ scripts/test-windows-workspace.mjs | 122 +++++++++++++++++++++++++++++ 3 files changed, 143 insertions(+) create mode 100644 scripts/test-windows-workspace.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2c7c478..7baf417 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -181,6 +181,19 @@ jobs: export LITHE_TEST_MAVEN="${MVN:-$(command -v mvn)}" node scripts/test-configuration.mjs node scripts/test-native-core.mjs + - uses: oven-sh/setup-bun@v2 + if: inputs.core-revision != '' && matrix.maven == 'runner' + with: + bun-version-file: .artifacts/core-source/windows/tauri/package.json + - name: Verify the Windows workflow with the real Provider and selected Core + if: inputs.core-revision != '' && matrix.maven == 'runner' + env: + LITHE_TEST_JAVA: ${{ env.JAVA_HOME_8_X64 }}/bin/java + run: | + export LITHE_HOST_SOURCE="$GITHUB_WORKSPACE/.artifacts/core-source" + export LITHE_CORE_LIBRARY="$LITHE_HOST_SOURCE/rust/target/debug/liblithe_core.so" + export LITHE_TEST_MAVEN="$(command -v mvn)" + bun scripts/test-windows-workspace.mjs - name: Verify Quarkus and Micronaut suspended JVMs with standard JDI if: inputs.core-revision != '' && matrix.maven == 'runner' env: diff --git a/README.md b/README.md index b70bb7c..d95f988 100644 --- a/README.md +++ b/README.md @@ -314,3 +314,11 @@ Quarkus 的 `jvm.args` 属于后者。Spring Boot 保留已有 JVM 参数,Quar Maven 3.6.3 支持声明。用 `LITHE_TEST_PACKAGE`、`LITHE_CORE_LIBRARY` 指向显式开发组合, `LITHE_TEST_JAVA` 与 `LITHE_TEST_MAVEN` 提供绝对工具路径;输出及逐项报告写入 `LITHE_REPORT_DIR`,进程退出前清理全部所持 JVM。此测试不代替宿主 Debug UI 验收。 + +`bun scripts/test-windows-workspace.mjs` 加载 `LITHE_HOST_SOURCE` 指定提交的 Windows +TypeScript 工作区编排,连接真实 Provider 和 `LITHE_CORE_LIBRARY` 指定的 Core。 +它覆盖 reactor 模型、成功测试、逐工程依赖、失败报告和退出清理,并确认包字节不变; +工具路径由 `LITHE_TEST_JAVA`、`LITHE_TEST_MAVEN` 明确提供。此 lane 可在 macOS/Linux +运行,不需要安装宿主前端依赖,也不修改正式 SDK 锁定。它不代替 Windows 原生工具发现、 +Job Object 进程清理、Build UI、配置和 Run 消费者迁移;固定提交的开发 CI 在 runner +Maven 组合执行该测试。 diff --git a/scripts/test-windows-workspace.mjs b/scripts/test-windows-workspace.mjs new file mode 100644 index 0000000..4f210e4 --- /dev/null +++ b/scripts/test-windows-workspace.mjs @@ -0,0 +1,122 @@ +// The Windows TypeScript workflow, production Maven Provider and current Core. +// Runs on macOS/Linux; native Windows launch/process acceptance is separate. +import assert from 'node:assert/strict'; +import { cpSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { delimiter, join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { BackendClient, bounded } from './backend-client.mjs'; +import { coreCommand } from './core-client.mjs'; +import { bundleManifest } from './bundle-manifest.mjs'; +import { createReport } from './report.mjs'; +import { mavenTimeout, withInterrupts } from './process.mjs'; + +if (!process.versions.bun) throw new Error('Run with Bun to load the production Windows TypeScript source.'); +if (!process.env.LITHE_HOST_SOURCE) throw new Error('Set LITHE_HOST_SOURCE to the exact host checkout under test.'); +if (!process.env.LITHE_TEST_MAVEN || !process.env.LITHE_TEST_JAVA) throw new Error('Set explicit LITHE_TEST_MAVEN and LITHE_TEST_JAVA paths.'); +const { WindowsBuildProviderWorkspace } = await import(pathToFileURL(join(resolve(process.env.LITHE_HOST_SOURCE), + 'windows/tauri/src/features/build/services/build-provider-workspace.ts')).href); +const { createTranslator } = await import(pathToFileURL(join(resolve(process.env.LITHE_HOST_SOURCE), 'windows/tauri/src/i18n/locale.ts')).href); +const pkg = resolve(process.env.LITHE_TEST_PACKAGE ?? 'dist/package/io.github.lithe-idea.maven-build'); +const manifest = JSON.parse(readFileSync(join(pkg, 'plugin.json'), 'utf8')), before = bundleManifest(pkg); +const scratch = realpathSync(mkdtempSync(join(tmpdir(), 'lithe-windows-maven-'))), root = 'nested'; +const workspacePath = join(scratch, 'workspace'), state = join(scratch, 'state'); +mkdirSync(workspacePath); cpSync(new URL('../test/fixtures/reactor', import.meta.url), join(workspacePath, root), { recursive: true }); +const instance = { pluginID: manifest.id, buildSystemID: 'maven', root, options: { profiles: ['ci'] } }; +const report = createReport('windows-provider-workspace'); +let client, workspace, model; +await withInterrupts(async signal => { + const stop = () => client?.kill(); signal.addEventListener('abort', stop, { once: true }); + try { + client = new BackendClient({ java: process.env.LITHE_TEST_JAVA, jar: join(pkg, 'lib/lithe-maven-backend.jar'), state, timeoutMs: mavenTimeout() }); + assert.equal((await client.initialize(workspacePath, [11])).capabilities.experimental.litheBuild.version, 11); + const javaHome = resolve(process.env.LITHE_TEST_JAVA, '../..'), requests = []; + workspace = new WindowsBuildProviderWorkspace(workspacePath, { + translate: createTranslator('en-US'), + core: async (command, manifest, buildSystemID, request, workspaceRoot) => coreCommand(command, { manifest, buildSystemID, workspaceRoot, request }), + tools: async () => ({ manifest, pluginDirectory: pkg, workspaceStateDirectory: state, + tool: { executable: process.env.LITHE_TEST_MAVEN }, executesProjectCode: false, + environment: { JAVA_HOME: javaHome, PATH: join(javaHome, 'bin') + delimiter + process.env.PATH } }), + guard: () => () => {}, + providers: { + send: async (_target, request) => { + requests.push(request.method); + assert.equal(request.params.environment.JAVA_HOME, javaHome); + const operationID = crypto.randomUUID(), sent = client.send(request.method, { ...request.params, operationID }); + const abort = () => client.cancel(sent.id); + const progress = notification => { + if (notification.method === 'lithe/build/progress' && notification.params.operationID === operationID) request.onProgress?.(notification.params); + }; + client.onNotification = progress; request.signal.addEventListener('abort', abort, { once: true }); + try { + const response = await sent.response; + if (response.error) throw new Error(JSON.stringify(response.error)); + return response.result; + } finally { request.signal.removeEventListener('abort', abort); if (client.onNotification === progress) client.onNotification = undefined; } + }, + stop: async () => { await client.close(); }, + }, + }); + await report.step('Windows loads the real reactor through Core and the production Provider', async () => { + model = await workspace.loadModel(instance).completion; + assert.deepEqual(model.projects.map(project => project.name).sort(), ['app', 'core', 'reactor']); + assert.ok(model.contentRoots.some(content => content.path === 'nested/core/src/main/java')); + assert.deepEqual(requests, ['lithe/build/model']); + }); + await report.step('Windows executes real reactor tests and decodes inline reports', async () => { + const operation = workspace.executeTask(instance, 'test'); + const result = await operation.completion; + assert.equal(result.exitCode, 0, result.output); + assert.ok(result.results.tests.some(test => test.suite === 'demo.core.GreeterTest')); + assert.equal(workspace.operations().find(record => record.id === operation.operationID).phase, 'succeeded'); + }); + await report.step('Windows selects dependencies from the same current Provider project', async () => { + const project = model.projects.find(project => project.name === 'core'); + const result = await workspace.dependencies(instance, project.id).completion; + assert.equal(result.dependencies.project, project.path); + assert.ok(result.dependencies.dependencies.some(dependency => dependency.name === 'junit')); + }); + await report.step('Windows executes a current model plugin goal without reconstructing its Maven command', async () => { + const project = model.projects.find(project => project.name === 'core'); + const task = model.tasks.find(task => task.projectID === project.id && + task.properties.goal?.includes(':maven-compiler-plugin:') && task.properties.goal.endsWith(':compile')); + assert.ok(task, 'the effective Maven model publishes the compiler goal'); + const result = await workspace.executeModelTask(instance, task.id).completion; + assert.equal(result.exitCode, 0, result.output); + }); + await report.step('Windows forwards the exact JDT selector and retains only the selected method report', async () => { + const project = model.projects.find(project => project.name === 'core'); + const result = await workspace.executeTests(instance, { projectID: project.id, selectorKind: 'java.test.fullName', + selectors: ['demo.core.GreeterTest#greetsByName()'] }).completion; + assert.equal(result.exitCode, 0, result.output); + assert.equal(result.results.summary.total, 1); + assert.deepEqual(result.results.tests.map(test => [test.project, test.suite, test.case]), + [[project.path, 'demo.core.GreeterTest', 'greetsByName']]); + }); + await report.step('a failed real Maven test retains its exit status, output and decoded failure', async () => { + const source = join(workspacePath, root, 'core/src/test/java/demo/core/GreeterTest.java'); + writeFileSync(source, readFileSync(source, 'utf8').replace('assertEquals("Hello, Lithe", new Greeter().greet("Lithe"));', + 'org.junit.Assert.fail("Windows failure marker");')); + const operation = workspace.executeTask(instance, 'test'); + const result = await operation.completion; + assert.notEqual(result.exitCode, 0); + assert.ok(result.results.tests.some(test => test.status === 'failed')); + const retained = workspace.operations().find(record => record.id === operation.operationID); + assert.equal(retained.phase, 'failed'); + assert.ok(result.output.length > 0, 'Maven failure output is retained'); + assert.equal(retained.output, result.output); + assert.ok(result.results.tests.some(test => test.message?.includes('Windows failure marker')), + 'Surefire owns the detailed assertion message even when Maven uses quiet output'); + }); + await report.step('workspace cleanup reaps its backend and preserves package bytes', async () => { + await workspace.dispose(); + assert.notEqual(client.child.exitCode, null); + assert.deepEqual(bundleManifest(pkg), before); + assert.throws(() => workspace.loadModel(instance), /inputs changed/); + }); + } finally { + signal.removeEventListener('abort', stop); + try { if (workspace) await workspace.dispose(); else if (client) await client.close(); } + finally { client?.kill(); if (client) await bounded(client.exited, 'Windows integration backend cleanup'); rmSync(scratch, { recursive: true, force: true }); report.write(); } + } +}); From b652424d4a6daa7ea92cb0b6de3243039271d0a6 Mon Sep 17 00:00:00 2001 From: wgw Date: Fri, 30 Oct 2026 23:24:19 +0800 Subject: [PATCH 15/24] test: verify native settings and real Micronaut HTTP debugging --- README.md | 7 +++++ scripts/test-framework-debug.mjs | 46 ++++++++++++++++++++++++++---- scripts/test-windows-workspace.mjs | 28 ++++++++++++++++-- 3 files changed, 73 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index d95f988..aac62bd 100644 --- a/README.md +++ b/README.md @@ -310,6 +310,11 @@ Quarkus 的 `jvm.args` 属于后者。Spring Boot 保留已有 JVM 参数,Quar `scripts/test-framework-debug.mjs` 用固定的 Quarkus 3.15.5、Micronaut Maven Plugin 4.7.2 和真实 reactor 验证暂停、标准 JDI 连接/恢复、参数、环境及兄弟模块依赖。 +Micronaut 夹具固定 Platform 4.7.6(Core/注解处理器 4.7.14),使用真实编译期依赖注入、 +Netty HTTP 控制器和 JSON 支持;JDI 恢复后通过回环 HTTP 请求验证注入服务读取未安装的 +reactor 兄弟模块,不再只用普通 main 作为 Micronaut 应用证据。应用异常会立即报告, +HTTP 请求有独立期限。依据为 [Micronaut IoC](https://docs.micronaut.io/4.7.14/guide/#ioc) +与[固定 Platform BOM](https://repo.maven.apache.org/maven2/io/micronaut/platform/micronaut-platform/4.7.6/micronaut-platform-4.7.6.pom)。 此集成使用 Java 17+ 和 Maven 3.9+,不改变 Provider 自身的 Java 8 / Maven 3.6.3 支持声明。用 `LITHE_TEST_PACKAGE`、`LITHE_CORE_LIBRARY` 指向显式开发组合, `LITHE_TEST_JAVA` 与 `LITHE_TEST_MAVEN` 提供绝对工具路径;输出及逐项报告写入 @@ -318,6 +323,8 @@ Maven 3.6.3 支持声明。用 `LITHE_TEST_PACKAGE`、`LITHE_CORE_LIBRARY` 指 `bun scripts/test-windows-workspace.mjs` 加载 `LITHE_HOST_SOURCE` 指定提交的 Windows TypeScript 工作区编排,连接真实 Provider 和 `LITHE_CORE_LIBRARY` 指定的 Core。 它覆盖 reactor 模型、成功测试、逐工程依赖、失败报告和退出清理,并确认包字节不变; +原生配置读取还验证损坏 POM 不妨碍读取、配置来源字节不变、秘密不导出、仓库和构建目录 +不创建,探针临时状态会清理。 工具路径由 `LITHE_TEST_JAVA`、`LITHE_TEST_MAVEN` 明确提供。此 lane 可在 macOS/Linux 运行,不需要安装宿主前端依赖,也不修改正式 SDK 锁定。它不代替 Windows 原生工具发现、 Job Object 进程清理、Build UI、配置和 Run 消费者迁移;固定提交的开发 CI 在 runner diff --git a/scripts/test-framework-debug.mjs b/scripts/test-framework-debug.mjs index 5f71450..f7ac32e 100644 --- a/scripts/test-framework-debug.mjs +++ b/scripts/test-framework-debug.mjs @@ -36,8 +36,17 @@ const frameworkCases = [ { name: 'micronaut', provider: 'micronaut.maven', version: '4.7.2', group: 'io.micronaut.maven', artifact: 'micronaut-maven-plugin', // The plugin declares this parameter required even when test resources are // disabled. Use its own 4.7.2 parent POM's version; no Docker server is started. - dependencies: '', configuration: 'demo.app.Main-Dlithe.pom=preserved2.6.2false', - imports: '', declaration: 'public class Main { public static void main(String[] args) throws Exception {', end: '} }' }, + // Platform 4.7.6 pins Core/processor 4.7.14. The fixture runs real DI and + // Netty HTTP, rather than merely launching a plain main through the Mojo. + management: 'io.micronaut.platformmicronaut-platform4.7.6pomimport', + dependencies: 'io.micronautmicronaut-runtimeio.micronautmicronaut-http-server-nettyio.micronautmicronaut-jackson-databind', + compiler: 'org.apache.maven.pluginsmaven-compiler-pluginio.micronautmicronaut-inject-java4.7.14', + configuration: 'demo.app.Main-Dlithe.pom=preserved2.6.2false', + imports: 'import io.micronaut.context.ApplicationContext; import io.micronaut.runtime.server.EmbeddedServer;', + declaration: 'public class Main { public static void main(String[] args) throws Exception { try (ApplicationContext context = ApplicationContext.run(java.util.Map.of("micronaut.server.host", "127.0.0.1", "micronaut.server.port", -1))) { EmbeddedServer server = context.getBean(EmbeddedServer.class).start();', + greeting: 'context.getBean(GreetingService.class).greet()', + after: 'System.out.println("MICRONAUT_PORT="+server.getPort()); new java.util.concurrent.CountDownLatch(1).await(45, java.util.concurrent.TimeUnit.SECONDS);', + http: true, end: '} } }' }, ]; async function unusedPort() { @@ -87,13 +96,26 @@ await withInterrupts(async signal => { const pom = join(directory, 'app/pom.xml'); writeFileSync(pom, readFileSync(pom, 'utf8').replace('', fixture.dependencies + '') .replace('', `${fixture.group}${fixture.artifact} - ${fixture.version}${fixture.lifecycle ?? ''}${fixture.configuration}`)); + ${fixture.version}${fixture.lifecycle ?? ''}${fixture.configuration}${fixture.compiler ?? ''}`)); + if (fixture.http) { + writeFileSync(join(directory, 'app/src/main/java/demo/app/GreetingService.java'), `package demo.app; + @jakarta.inject.Singleton public class GreetingService { + public String greet() { return new demo.core.Greeter().greet(System.getenv("LITHE_RUN_VALUE")); } + }`); + writeFileSync(join(directory, 'app/src/main/java/demo/app/GreetingController.java'), `package demo.app; + @io.micronaut.http.annotation.Controller("/lithe") public class GreetingController { + private final GreetingService service; + public GreetingController(GreetingService service) { this.service = service; } + @io.micronaut.http.annotation.Get(produces = "text/plain") public String index() { return service.greet(); } + }`); + } const marker = `FRAMEWORK=${fixture.name}:Hello, Provider`; writeFileSync(join(directory, 'app/src/main/java/demo/app/Main.java'), `package demo.app; import demo.core.Greeter; ${fixture.imports} ${fixture.declaration} - System.out.println("FRAMEWORK=${fixture.name}:"+new Greeter().greet(System.getenv("LITHE_RUN_VALUE"))); + System.out.println("FRAMEWORK=${fixture.name}:"+${fixture.greeting ?? 'new Greeter().greet(System.getenv("LITHE_RUN_VALUE"))'}); System.out.println("POMFLAG="+System.getProperty("lithe.pom")); for (String arg : args) System.out.println("ARG="+java.util.Base64.getEncoder().encodeToString(arg.getBytes("UTF-8"))); + ${fixture.after ?? ''} ${fixture.end}`); const plan = (command, request) => coreCommand(command, { manifest, buildSystemID: 'maven', request }); const planned = extra => ({ root, options: {}, pluginDirectory: pkg, workspaceStateDirectory: join(scratch, 'state'), tool: { executable: maven }, ...extra }); @@ -109,16 +131,19 @@ await withInterrupts(async signal => { const prepared = await send(plan('build.prepareRunPlan', planned({ workspaceRoot: workspace, run: 'framework', project: { name: app.name, path: app.path }, target: { name: target.name, path: target.path, tags: target.tags }, launchOptions })).plan); const launch = plan('build.decodeRunPreparation', { workspaceRoot: workspace, root, launchOptions, result: prepared }).launch; - let output = '', ready, ran; - const listening = new Promise(resolve => { ready = resolve; }), application = new Promise(resolve => { ran = resolve; }); + let output = '', ready, ran, applicationFailed; + const listening = new Promise(resolve => { ready = resolve; }), application = new Promise((resolve, reject) => { ran = resolve; applicationFailed = reject; }); + application.catch(() => {}); const controller = new AbortController(), abort = () => controller.abort(signal.reason); signal.addEventListener('abort', abort, { once: true }); const running = runCommand(maven, launch.arguments, { cwd: join(workspace, launch.workingDirectory), env: { ...process.env, ...launch.environment }, signal: controller.signal, timeoutMs: mavenTimeout(), onOutput: chunk => { output = (output + chunk).slice(-500000); + if (output.includes('Exception in thread "main"')) applicationFailed(new Error('Application main failed: ' + output)); if (output.includes('Listening for transport dt_socket at address: ' + port)) ready(); if (output.includes(marker) && output.includes('POMFLAG=preserved') + && (!fixture.http || /MICRONAUT_PORT=\d+/.test(output)) && launchOptions.arguments.every(arg => output.includes('ARG=' + Buffer.from(arg).toString('base64')))) ran(); } }); const completed = running.then(() => { throw new Error('Framework exited before acceptance: ' + output); }); @@ -129,6 +154,15 @@ await withInterrupts(async signal => { assert.ok(!output.includes(marker), 'application must not execute before JDI attachment'); await runCommand(java, ['-cp', scratch + (existsSync(tools) ? delimiter + tools : ''), 'ResumeFramework', String(port)], { signal, timeoutMs: 10000 }); await bounded(Promise.race([application, completed]), `${fixture.name} resumed application`, 30000); + if (fixture.http) { + const port = Number(/MICRONAUT_PORT=(\d+)/.exec(output)?.[1]); + assert.ok(Number.isInteger(port) && port > 0 && port <= 65535); + const response = await fetch(`http://127.0.0.1:${port}/lithe`, { signal: AbortSignal.timeout(5000) }); + assert.equal(response.status, 200); + assert.equal(await response.text(), 'Hello, Provider', 'real Micronaut HTTP dispatch uses the injected reactor dependency'); + assert.ok(existsSync(join(directory, 'app/target/classes/demo/app/$GreetingService$Definition.class')), + 'the real Micronaut annotation processor generated the bean definition'); + } } catch (error) { throw new Error(`${error.message}\n${output}`, { cause: error }); } finally { signal.removeEventListener('abort', abort); controller.abort(); diff --git a/scripts/test-windows-workspace.mjs b/scripts/test-windows-workspace.mjs index 4f210e4..2cad3fe 100644 --- a/scripts/test-windows-workspace.mjs +++ b/scripts/test-windows-workspace.mjs @@ -1,7 +1,7 @@ // The Windows TypeScript workflow, production Maven Provider and current Core. // Runs on macOS/Linux; native Windows launch/process acceptance is separate. import assert from 'node:assert/strict'; -import { cpSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { delimiter, join, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; @@ -57,11 +57,35 @@ await withInterrupts(async signal => { stop: async () => { await client.close(); }, }, }); + await report.step('Windows reads real native settings before a broken POM without writing sources or creating the repository', async () => { + const pom = join(workspacePath, root, 'pom.xml'), original = readFileSync(pom); + const mavenConfiguration = join(workspacePath, root, '.mvn/maven.config'); + const user = join(scratch, 'user settings.xml'), global = join(scratch, 'global.xml'), repository = join(scratch, 'unused-repository'); + writeFileSync(user, 'fixturefixture-private-value'); + writeFileSync(global, `${repository}`); + const before = [readFileSync(user), readFileSync(global)]; + mkdirSync(join(workspacePath, root, '.mvn'), { recursive: true }); + writeFileSync(mavenConfiguration, `-gs\n${global}\n`); + writeFileSync(pom, ' source.id === 'user'); + const field = selected.fields.find(field => field.id === 'localRepository'); + assert.equal(field.value, null); assert.equal(field.effectiveValue, repository); + assert.equal(configuration.sources.find(source => source.id === 'installation').writable, false); + assert.ok(!JSON.stringify(configuration).includes('fixture-private-value')); + assert.deepEqual([readFileSync(user), readFileSync(global)], before); + assert.equal(existsSync(repository), false); + assert.equal(existsSync(join(workspacePath, root, 'target')), false); + assert.deepEqual(readdirSync(state).filter(name => name.startsWith('configuration-')), []); + assert.equal(workspace.model(instance), undefined); + } finally { writeFileSync(pom, original); rmSync(mavenConfiguration); } + }); await report.step('Windows loads the real reactor through Core and the production Provider', async () => { model = await workspace.loadModel(instance).completion; assert.deepEqual(model.projects.map(project => project.name).sort(), ['app', 'core', 'reactor']); assert.ok(model.contentRoots.some(content => content.path === 'nested/core/src/main/java')); - assert.deepEqual(requests, ['lithe/build/model']); + assert.deepEqual(requests, ['lithe/build/configuration', 'lithe/build/model']); }); await report.step('Windows executes real reactor tests and decodes inline reports', async () => { const operation = workspace.executeTask(instance, 'test'); From 793216b3034010481983a80ecbfa36b3d378dd9f Mon Sep 17 00:00:00 2001 From: wgw Date: Sat, 31 Oct 2026 11:40:56 +0800 Subject: [PATCH 16/24] test(maven): verify Windows native sources and module Run plans --- scripts/test-windows-workspace.mjs | 49 ++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/scripts/test-windows-workspace.mjs b/scripts/test-windows-workspace.mjs index 2cad3fe..8e37149 100644 --- a/scripts/test-windows-workspace.mjs +++ b/scripts/test-windows-workspace.mjs @@ -1,10 +1,11 @@ // The Windows TypeScript workflow, production Maven Provider and current Core. // Runs on macOS/Linux; native Windows launch/process acceptance is separate. import assert from 'node:assert/strict'; -import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { closeSync, cpSync, existsSync, fstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { createHash } from 'node:crypto'; import { tmpdir } from 'node:os'; import { delimiter, join, resolve } from 'node:path'; -import { pathToFileURL } from 'node:url'; +import { fileURLToPath, pathToFileURL } from 'node:url'; import { BackendClient, bounded } from './backend-client.mjs'; import { coreCommand } from './core-client.mjs'; import { bundleManifest } from './bundle-manifest.mjs'; @@ -38,6 +39,32 @@ await withInterrupts(async signal => { tool: { executable: process.env.LITHE_TEST_MAVEN }, executesProjectCode: false, environment: { JAVA_HOME: javaHome, PATH: join(javaHome, 'bin') + delimiter + process.env.PATH } }), guard: () => () => {}, + // Test-only native I/O port: private XML is hashed here, never returned to + // the production TypeScript workflow or sent back over Provider RPC. + configurationCheck: async (_target, sources) => { + const paths = [], revisions = []; + for (const source of sources) { + const file = fileURLToPath(source.uri); paths.push(file); + let descriptor; + try { + const metadata = statSync(file); + assert.ok(metadata.isFile() && metadata.size <= 2 * 1024 * 1024, 'bounded regular configuration source'); + descriptor = openSync(file, 'r'); + const opened = fstatSync(descriptor); assert.ok(opened.isFile() && opened.size <= 2 * 1024 * 1024); + const buffer = Buffer.alloc(2 * 1024 * 1024 + 1); + let length = 0; + while (length < buffer.length) { + const count = readSync(descriptor, buffer, length, buffer.length - length, null); + if (count === 0) break; + length += count; + } + assert.ok(length <= 2 * 1024 * 1024); + revisions.push('sha256:' + createHash('sha256').update(buffer.subarray(0, length)).digest('hex')); + } catch (error) { if (error.code !== 'ENOENT') throw error; revisions.push('missing'); } + finally { if (descriptor !== undefined) closeSync(descriptor); } + } + return { current: sources.every((source, index) => source.revision === revisions[index]), paths }; + }, providers: { send: async (_target, request) => { requests.push(request.method); @@ -85,7 +112,7 @@ await withInterrupts(async signal => { model = await workspace.loadModel(instance).completion; assert.deepEqual(model.projects.map(project => project.name).sort(), ['app', 'core', 'reactor']); assert.ok(model.contentRoots.some(content => content.path === 'nested/core/src/main/java')); - assert.deepEqual(requests, ['lithe/build/configuration', 'lithe/build/model']); + assert.deepEqual(requests, ['lithe/build/configuration', 'lithe/build/configuration', 'lithe/build/model']); }); await report.step('Windows executes real reactor tests and decodes inline reports', async () => { const operation = workspace.executeTask(instance, 'test'); @@ -94,6 +121,22 @@ await withInterrupts(async signal => { assert.ok(result.results.tests.some(test => test.suite === 'demo.core.GreeterTest')); assert.equal(workspace.operations().find(record => record.id === operation.operationID).phase, 'succeeded'); }); + await report.step('Windows prepares a real module Run through public Core plans without replacing the default model', async () => { + const project = model.projects.find(project => project.name === 'core'); + const run = manifest.buildSystems[0].run.find(run => run.execution === 'task'); + const target = model.targets.find(target => target.projectID === project.id && target.tags.some(tag => run.fromTargets.tags.includes(tag))); + assert.ok(target, 'a current module target is published by the Provider'); + const defaults = structuredClone(workspace.model(instance)); + const prepared = await workspace.prepareRun(instance, { run: run.id, projectID: project.id, targetID: target.id, + launchOptions: { execution: 'task', runtimeArguments: [], arguments: ['compile'], environment: {}, workingDirectory: root } }).completion; + assert.deepEqual(prepared.launch.executable, { kind: 'toolchain', value: 'project-maven' }); + assert.ok(prepared.launch.arguments.includes('compile')); + assert.equal(prepared.languageImport.kind, 'maven'); + assert.equal(prepared.languageImport.mavenContext.mavenExecutablePath, process.env.LITHE_TEST_MAVEN); + prepared.assertCurrent(); await prepared.validate(); + assert.deepEqual(workspace.model(instance), defaults); + assert.deepEqual(instance.options, { profiles: ['ci'] }); + }); await report.step('Windows selects dependencies from the same current Provider project', async () => { const project = model.projects.find(project => project.name === 'core'); const result = await workspace.dependencies(instance, project.id).completion; From 5124e2cd79159ff19271a372293c9a21b0843bc8 Mon Sep 17 00:00:00 2001 From: wgw Date: Sat, 31 Oct 2026 14:07:29 +0800 Subject: [PATCH 17/24] test(maven): verify isolated Run tools through current Core --- scripts/test-windows-workspace.mjs | 64 +++++++++++++++++++++++++++--- 1 file changed, 58 insertions(+), 6 deletions(-) diff --git a/scripts/test-windows-workspace.mjs b/scripts/test-windows-workspace.mjs index 8e37149..8c11692 100644 --- a/scripts/test-windows-workspace.mjs +++ b/scripts/test-windows-workspace.mjs @@ -1,10 +1,10 @@ // The Windows TypeScript workflow, production Maven Provider and current Core. // Runs on macOS/Linux; native Windows launch/process acceptance is separate. import assert from 'node:assert/strict'; -import { closeSync, cpSync, existsSync, fstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { closeSync, cpSync, existsSync, fstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'; import { createHash } from 'node:crypto'; import { tmpdir } from 'node:os'; -import { delimiter, join, resolve } from 'node:path'; +import { delimiter, dirname, join, resolve } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { BackendClient, bounded } from './backend-client.mjs'; import { coreCommand } from './core-client.mjs'; @@ -25,7 +25,7 @@ const workspacePath = join(scratch, 'workspace'), state = join(scratch, 'state') mkdirSync(workspacePath); cpSync(new URL('../test/fixtures/reactor', import.meta.url), join(workspacePath, root), { recursive: true }); const instance = { pluginID: manifest.id, buildSystemID: 'maven', root, options: { profiles: ['ci'] } }; const report = createReport('windows-provider-workspace'); -let client, workspace, model; +let client, workspace, model, scopedTool; await withInterrupts(async signal => { const stop = () => client?.kill(); signal.addEventListener('abort', stop, { once: true }); try { @@ -35,9 +35,13 @@ await withInterrupts(async signal => { workspace = new WindowsBuildProviderWorkspace(workspacePath, { translate: createTranslator('en-US'), core: async (command, manifest, buildSystemID, request, workspaceRoot) => coreCommand(command, { manifest, buildSystemID, workspaceRoot, request }), - tools: async () => ({ manifest, pluginDirectory: pkg, workspaceStateDirectory: state, - tool: { executable: process.env.LITHE_TEST_MAVEN }, executesProjectCode: false, - environment: { JAVA_HOME: javaHome, PATH: join(javaHome, 'bin') + delimiter + process.env.PATH } }), + tools: async (_target, instanceRoot, _check, configurationId) => { + const selected = configurationId ? coreCommand('runConfig.projectToolchain', { root: workspacePath, path: instanceRoot, configurationId }, null).toolchain : {}; + const home = selected.mavenJavaHomePath || selected.javaHomePath || javaHome; + return { manifest, pluginDirectory: pkg, workspaceStateDirectory: state, + tool: { executable: selected.mavenExecutablePath || process.env.LITHE_TEST_MAVEN }, executesProjectCode: false, + environment: { JAVA_HOME: home, PATH: join(home, 'bin') + delimiter + process.env.PATH } }; + }, guard: () => () => {}, // Test-only native I/O port: private XML is hashed here, never returned to // the production TypeScript workflow or sent back over Provider RPC. @@ -143,6 +147,54 @@ await withInterrupts(async signal => { assert.equal(result.dependencies.project, project.path); assert.ok(result.dependencies.dependencies.some(dependency => dependency.name === 'junit')); }); + await report.step('Windows per-Run Profiles use a private real model and preserve the default model and options', async () => { + const project = model.projects.find(project => project.name === 'core'), defaults = structuredClone(workspace.model(instance)); + const prepared = await workspace.prepareConfigurationRun(instance, { provider: 'maven.module', projectPath: project.path, + optionOverrides: { profiles: [], skipTests: false }, + launchOptions: { execution: 'task', runtimeArguments: [], arguments: ['compile'], environment: {} } }).completion; + assert.ok(prepared.launch.arguments.includes('compile')); + assert.equal(prepared.languageImport.kind, 'maven'); + assert.deepEqual(prepared.languageImport.mavenContext.profiles, []); + // False contributes no option; the optional public import field may be absent. + assert.equal(prepared.languageImport.mavenContext.skipTests ?? false, false); + assert.ok(!prepared.launch.arguments.includes('-DskipTests')); + await prepared.validate(); + assert.deepEqual(workspace.model(instance), defaults); assert.deepEqual(instance.options, { profiles: ['ci'] }); + }); + await report.step('a configuration-owned private Run model preserves explicit Maven selection and leaves the shared backend alive', async () => { + const project = model.projects.find(project => project.path === root), defaults = structuredClone(workspace.model(instance)); + const target = model.targets.find(target => target.projectID === project.id && target.name === 'maven.module'); + assert.ok(target); + const scopedTool = join(scratch, 'selected Run Maven'); symlinkSync(process.env.LITHE_TEST_MAVEN, scopedTool); + const local = join(workspacePath, '.lithe/run/local.json'), original = existsSync(local) ? readFileSync(local) : undefined; + mkdirSync(dirname(local), { recursive: true }); + // An explicit saved selector makes this test workspace readable without + // an in-memory detector layer; the ordinary module entry uses real Core merge. + writeFileSync(local, JSON.stringify({ version: 2, configurations: [ + { id: 'user:anchor', name: 'Saved task', provider: 'build.provider', execution: 'task', extensions: { build: { + pluginID: manifest.id, buildSystemID: 'maven', root, run: 'module', projectID: project.id, targetID: target.id, execution: 'task', userArguments: ['compile'] } } }, + { id: 'user:scoped', name: 'Scoped module', provider: 'maven.module', execution: 'task', cwd: root, args: ['compile'], + toolchains: { java: 'project-jdk', maven: 'project-maven' }, extensions: { maven: { module: '.', skipTests: false }, + java: { mavenExecutablePath: scopedTool, mavenJavaHomePath: javaHome } } }, + ] })); + let scope; + try { + const input = coreCommand('runConfig.providerLaunchInputs', { root: workspacePath, configurationId: 'user:scoped', providerRoot: root }, null); + scope = workspace.createRunScope(instance, input, 'user:scoped'); + await scope.domain.loadModel(scope.instance, scope.requiredOptions).completion; + const prepared = await scope.domain.prepareConfigurationRun(scope.instance, input).completion; + assert.equal(prepared.tool.tool.executable, scopedTool); + assert.equal(prepared.languageImport.mavenContext.mavenExecutablePath, scopedTool); + assert.deepEqual(prepared.languageImport.mavenContext.profiles, ['ci']); + await prepared.validate(); + assert.deepEqual(workspace.model(instance), defaults); assert.deepEqual(instance.options, { profiles: ['ci'] }); + } finally { + try { await scope?.dispose(); } + finally { if (original) writeFileSync(local, original); else rmSync(local, { force: true }); } + } + assert.equal(client.child.exitCode, null, 'the backend is still owned by the main workspace'); + assert.deepEqual(workspace.model(instance), defaults); + }); await report.step('Windows executes a current model plugin goal without reconstructing its Maven command', async () => { const project = model.projects.find(project => project.name === 'core'); const task = model.tasks.find(task => task.projectID === project.id && From 6c6eee1ed32c43a29a2463ab996e6b16111e600d Mon Sep 17 00:00:00 2001 From: wgw Date: Sat, 31 Oct 2026 18:24:38 +0800 Subject: [PATCH 18/24] fix(maven): own settings editing and declare preparation roles --- README.md | 12 +- .../maven/backend/ConfigurationEditor.java | 198 ++++++++++++++++++ .../litheidea/maven/backend/MavenBackend.java | 1 + .../litheidea/maven/SettingsExport.java | 4 - io.github.lithe-idea.maven-build/plugin.json | 4 +- scripts/test-configuration.mjs | 41 +++- scripts/test-native-core.mjs | 11 +- scripts/test-native.mjs | 10 +- .../ConfigurationEditorRegression.java | 71 +++++++ 9 files changed, 328 insertions(+), 24 deletions(-) create mode 100644 backend/src/main/java/io/github/litheidea/maven/backend/ConfigurationEditor.java create mode 100644 test/fixtures/configuration-editor/ConfigurationEditorRegression.java diff --git a/README.md b/README.md index aac62bd..a67b294 100644 --- a/README.md +++ b/README.md @@ -225,8 +225,11 @@ node scripts/verify-scripts.mjs --host-bundle /Applications/Lithe.app 通用的构建系统设置页通过 `lithe/build/configuration` 读取 Maven 实际选中的安装级和用户级 settings.xml,显示非敏感的 localRepository、activeProfiles 原值及实际生效值。打开页面只读; 只有显式开启覆盖并保存,宿主才修改所列来源。安装来源以及与安装文件相同的用户来源始终只读。 -保存使用源字节哈希防止覆盖外部编辑,保留其他内容、注释、权限和凭据,再由 Maven 重新读取 -生效值。命令行覆盖值单独显示,不能将保存的原值直接当成生效值。 +保存通过 `lithe/build/editConfiguration` 交给本插件的 JDK 安全 DOM 读写器,只生成 +宿主已有私有暂存文件的替换内容,不直接改原文件;协议没有 XML 根或路径绑定。返回 +来源 ID 和 SHA-256 回执后,宿主核对原字节、配置代次与输出哈希,以保留元数据的原子 +替换发布,再由 Maven 重新读取生效值。注释、无关内容和凭据留在原生文件边界内, +Core 不解析或编辑 Maven XML。提供者禁止 CREATE 暂存文件,取消后不能重新生成它。命令行覆盖值单独显示,不能将保存的原值直接当成生效值。 扩展观察 Maven 官方的 SettingsBuildingRequest/Result 事件,不重新实现配置优先级; 会话执行请求提供最终 CLI 值。配置读取在 reactor 导入前结束,因此损坏 POM 不会阻止查看 @@ -269,8 +272,9 @@ Maven 后端才把类或 `类#方法()` 映射成 Surefire 的精确选择器; 已配置的测试 Mojo 通过公开 setter 跳过未选工程;原始 `-Dtest=*` 不会扩大类型化选择。 没有明确整类选择时,继承的上游筛选可能仍有效,所以只声明报告中返回的方法覆盖。 -Java 启动前的公开项目任务 `java-prepare-run-main`/`java-prepare-run-test` -分别通过 Maven 的 `resources:resources`,或再加 `resources:testResources` 处理资源。 +清单以 `buildSystems: 4` 声明 `preparation.purpose: "run"` 和适用的模型源码角色, +宿主按用途和角色选择准备任务。`java-prepare-run-main`/`java-prepare-run-test` +只是本插件内部任务 ID,不是宿主约定。它们分别通过 Maven 的 `resources:resources`,或再加 `resources:testResources` 处理资源。 自定义目录、过滤和 Profile 由当前 Maven 模型处理;依赖仍按 `-am` 参与,不在宿主 重新解析 POM。任务需要当前工程且不接受附加目标,失败或取消不能作为启动成功。 diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/ConfigurationEditor.java b/backend/src/main/java/io/github/litheidea/maven/backend/ConfigurationEditor.java new file mode 100644 index 0000000..c91dfd4 --- /dev/null +++ b/backend/src/main/java/io/github/litheidea/maven/backend/ConfigurationEditor.java @@ -0,0 +1,198 @@ +package io.github.litheidea.maven.backend; + +import io.github.litheidea.plugin.sdk.Cancellation; +import io.github.litheidea.plugin.sdk.Json; +import io.github.litheidea.plugin.sdk.PluginError; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.net.URI; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.helpers.DefaultHandler; + +/** Maven owns settings syntax; host-owned staging keeps private documents off RPC. */ +final class ConfigurationEditor { + private static final int MAX_BYTES = 2 * 1024 * 1024; + + static Map edit(Inputs inputs, Path state, Map params, Cancellation cancellation) throws Exception { + Map snapshot = Json.object(params.get("snapshot")); + Map edits = Json.object(params.get("edits")); + String sourceID = Json.string(edits, "sourceID"), revision = Json.string(edits, "revision"); + Map selected = source(snapshot, sourceID); + Map current = source(ConfigurationProbe.read(inputs, state, cancellation), sourceID); + if (!selected.equals(current) || !revision.equals(current.get("revision"))) throw NativeSources.changed(); + if (!Boolean.TRUE.equals(current.get("writable")) || "installation".equals(current.get("scope"))) throw invalid(); + Path source = Paths.get(new URI(Json.string(current, "uri"))); + if (!NativeSources.current(Arrays.asList(current))) throw NativeSources.changed(); + byte[] original = "missing".equals(revision) ? null : Files.readAllBytes(source); + if (original != null && original.length > MAX_BYTES) throw invalid(); + Map values = Json.object(edits.get("values")); + if (values.size() > 2) throw invalid(); + boolean changed = false; + for (Map.Entry edit : values.entrySet()) { + Map field = field(current, edit.getKey()); + Object value = edit.getValue(); + if ("localRepository".equals(edit.getKey())) { + if (value != null && (!(value instanceof String) || ((String) value).length() > 8192 + || ((String) value).indexOf('\0') >= 0 || ((String) value).indexOf('\n') >= 0 || ((String) value).indexOf('\r') >= 0)) throw invalid(); + } else if ("activeProfiles".equals(edit.getKey())) { + if (value != null) { + if (!(value instanceof List) || ((List) value).size() > 64) throw invalid(); + for (Object profile : (List) value) { + if (!(profile instanceof String) || ((String) profile).length() > 8192 + || ((String) profile).indexOf('\0') >= 0 || ((String) profile).indexOf('\n') >= 0 || ((String) profile).indexOf('\r') >= 0) throw invalid(); + } + } + } else throw invalid(); + changed |= value == null ? field.get("value") != null : !value.equals(field.get("value")); + } + if (!changed) return receipt(sourceID, revision, false); + byte[] replacement; + try { replacement = replace(original, values); } + catch (Exception error) { throw new PluginError("maven.configurationEdit", "Maven settings cannot be edited safely. The original file was preserved."); } + cancellation.throwIfCancelled(); + if (!NativeSources.current(Arrays.asList(current))) throw NativeSources.changed(); + Path output = Paths.get(Json.string(params, "outputFile")); + if (!output.isAbsolute() || !Files.isRegularFile(output, LinkOption.NOFOLLOW_LINKS) + || source.toAbsolutePath().normalize().equals(output.toAbsolutePath().normalize())) throw invalid(); + // No CREATE: a cancelled host may have removed this staging file. A late + // operation must fail rather than recreate a file containing secrets. + try (SeekableByteChannel channel = Files.newByteChannel(output, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)) { + if (channel.size() != 0) throw invalid(); + ByteBuffer bytes = ByteBuffer.wrap(replacement); + while (bytes.hasRemaining()) { cancellation.throwIfCancelled(); channel.write(bytes); } + } + cancellation.throwIfCancelled(); + return receipt(sourceID, digest(replacement), true); + } + + static byte[] replace(byte[] original, Map values) throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + factory.setAttribute("http://www.oracle.com/xml/jaxp/properties/maxElementDepth", "64"); + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + factory.setFeature("http://xml.org/sax/features/external-general-entities", false); + factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); + javax.xml.parsers.DocumentBuilder builder = factory.newDocumentBuilder(); + builder.setErrorHandler(new DefaultHandler()); + Document document = original == null ? builder.newDocument() : builder.parse(new ByteArrayInputStream(original)); + if (original == null) document.appendChild(document.createElementNS("http://maven.apache.org/SETTINGS/1.0.0", "settings")); + Element root = document.getDocumentElement(); + if (!"settings".equals(local(root))) throw invalid(); + for (Map.Entry edit : values.entrySet()) { + Element field = direct(root, edit.getKey()); + Object value = edit.getValue(); + if (value == null) { + if (field != null) { + // Preserve comments; refuse unknown content rather than deleting it. + for (Node child : children(field)) { + if (child.getNodeType() == Node.COMMENT_NODE) root.insertBefore(child, field); + else if (child.getNodeType() == Node.ELEMENT_NODE && !("activeProfiles".equals(edit.getKey()) && "activeProfile".equals(local(child)))) throw invalid(); + } + root.removeChild(field); + } + continue; + } + if (field == null) { field = element(document, root, edit.getKey()); root.appendChild(field); } + if ("localRepository".equals(edit.getKey())) { + for (Node child : children(field)) { + if (child.getNodeType() == Node.ELEMENT_NODE) throw invalid(); + if (child.getNodeType() != Node.COMMENT_NODE) field.removeChild(child); + } + field.appendChild(document.createTextNode((String) value)); + } else if ("activeProfiles".equals(edit.getKey())) { + for (Node child : children(field)) { + if (child.getNodeType() == Node.ELEMENT_NODE) { + if (!"activeProfile".equals(local(child)) || !sameNamespace(root, child)) throw invalid(); + field.removeChild(child); + } + } + for (Object profile : (List) value) { + Element item = element(document, root, "activeProfile"); + item.appendChild(document.createTextNode((String) profile)); field.appendChild(item); + } + } else throw invalid(); + } + TransformerFactory transformers = TransformerFactory.newInstance(); + transformers.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + transformers.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + transformers.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); + Transformer transformer = transformers.newTransformer(); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty(OutputKeys.INDENT, "no"); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + if (original != null && original.length >= 3 && original[0] == (byte) 0xef && original[1] == (byte) 0xbb && original[2] == (byte) 0xbf) { + output.write(new byte[] {(byte) 0xef, (byte) 0xbb, (byte) 0xbf}); + } + transformer.transform(new DOMSource(document), new StreamResult(output)); + byte[] bytes = output.toByteArray(); + if (bytes.length > MAX_BYTES) throw invalid(); + // Let the same secure upstream parser reject invalid XML characters + // introduced by a value before any replacement can be published. + builder.parse(new ByteArrayInputStream(bytes)); + return bytes; + } + + private static List children(Node parent) { + List nodes = new ArrayList<>(); + for (Node node = parent.getFirstChild(); node != null; node = node.getNextSibling()) nodes.add(node); + return nodes; + } + private static Element direct(Element parent, String name) { + Element found = null; + for (Node node : children(parent)) if (node.getNodeType() == Node.ELEMENT_NODE && name.equals(local(node)) && sameNamespace(parent, node)) { + if (found != null) throw invalid(); found = (Element) node; + } + return found; + } + private static Element element(Document document, Element root, String name) { + String prefix = root.getPrefix(); + return document.createElementNS(root.getNamespaceURI(), prefix == null ? name : prefix + ":" + name); + } + private static String local(Node node) { return node.getLocalName() == null ? node.getNodeName() : node.getLocalName(); } + private static boolean sameNamespace(Node a, Node b) { return a.getNamespaceURI() == null ? b.getNamespaceURI() == null : a.getNamespaceURI().equals(b.getNamespaceURI()); } + private static Map source(Map snapshot, String id) { + Object sources = snapshot.get("sources"); + if (!(sources instanceof List) || ((List) sources).size() > 8) throw invalid(); + for (Object value : (List) sources) { Map source = Json.object(value); if (id.equals(source.get("id"))) return source; } + throw invalid(); + } + private static Map field(Map source, String id) { + for (Object value : (List) source.get("fields")) { Map field = Json.object(value); if (id.equals(field.get("id"))) return field; } + throw invalid(); + } + private static String digest(byte[] bytes) throws Exception { + StringBuilder text = new StringBuilder("sha256:"); + for (byte value : MessageDigest.getInstance("SHA-256").digest(bytes)) text.append(String.format("%02x", value & 0xff)); + return text.toString(); + } + private static Map receipt(String id, String revision, boolean changed) { + Map result = new LinkedHashMap<>(); + result.put("sourceID", id); result.put("revision", revision); result.put("changed", changed); return result; + } + private static PluginError invalid() { return new PluginError("maven.configurationEdit", "Maven configuration edit is invalid or unsafe."); } + private ConfigurationEditor() {} +} diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java index 5e8b26e..e21bd25 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java @@ -60,6 +60,7 @@ private void serve() { runs = new MavenRuns(snapshots, backend, state); }); backend.onConfiguration((params, context) -> ConfigurationProbe.read(inputs(params), workspaceState, context.cancellation())); + backend.onEditConfiguration((params, context) -> ConfigurationEditor.edit(inputs(params), workspaceState, params, context.cancellation())); backend.onModel((params, context) -> copy(load(params, context).model())); backend.onDependencies(this::dependencies); backend.onExecute((params, context) -> execution(params, context, false)); diff --git a/extension/src/main/java/io/github/litheidea/maven/SettingsExport.java b/extension/src/main/java/io/github/litheidea/maven/SettingsExport.java index 7f71307..c1c12e4 100644 --- a/extension/src/main/java/io/github/litheidea/maven/SettingsExport.java +++ b/extension/src/main/java/io/github/litheidea/maven/SettingsExport.java @@ -198,8 +198,6 @@ Map export(String repository, List profiles, String repo Map source = new LinkedHashMap<>(); source.put("id", id); source.put("scope", id); source.put("uri", path.toUri().toString()); source.put("revision", revision); source.put("writable", writable); - Map root = new LinkedHashMap<>(); root.put("name", rootName); root.put("namespace", rootNamespace); - source.put("rootElement", root); List fields = new ArrayList<>(); fields.add(field("localRepository", "directory", settings.getLocalRepository(), repository, repositoryOrigin, null)); fields.add(field("activeProfiles", "stringList", activeProfiles ? settings.getActiveProfiles() : null, @@ -212,8 +210,6 @@ private Map field(String name, String kind, Object value, Object Map field = new LinkedHashMap<>(); field.put("id", name); field.put("kind", kind); field.put("value", value); field.put("effectiveValue", effective); field.put("effectiveSource", origin); - field.put("path", Collections.singletonList(name)); - if (item != null) field.put("itemElement", item); return field; } } diff --git a/io.github.lithe-idea.maven-build/plugin.json b/io.github.lithe-idea.maven-build/plugin.json index 45b15a0..0a62be3 100644 --- a/io.github.lithe-idea.maven-build/plugin.json +++ b/io.github.lithe-idea.maven-build/plugin.json @@ -4,7 +4,7 @@ "displayName": "Maven", "version": "0.1.1", "pluginAPIVersion": 3, - "requires": { "buildProviders": 11, "buildModelInputs": 1, "buildSystems": 3, "executableResolution": 2, "serverProcess": 1 }, + "requires": { "buildProviders": 11, "buildModelInputs": 1, "buildSystems": 4, "executableResolution": 2, "serverProcess": 1 }, "vendor": { "id": "io.github.lithe-idea", "displayName": "Lithe Community", @@ -105,6 +105,7 @@ "tasks": [ { "id": "java-prepare-run-main", + "preparation": { "purpose": "run", "sourceRoles": ["source", "generatedSource", "resource"] }, "displayName": "resources:resources", "group": "build", "category": ["Lifecycle"], @@ -114,6 +115,7 @@ }, { "id": "java-prepare-run-test", + "preparation": { "purpose": "run", "sourceRoles": ["testSource", "generatedTestSource", "testResource"] }, "displayName": "resources:resources + resources:testResources", "group": "build", "category": ["Lifecycle"], diff --git a/scripts/test-configuration.mjs b/scripts/test-configuration.mjs index fe330fc..06d7215 100644 --- a/scripts/test-configuration.mjs +++ b/scripts/test-configuration.mjs @@ -4,11 +4,11 @@ import assert from 'node:assert/strict'; import { createHash } from 'node:crypto'; import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; -import { join, resolve } from 'node:path'; +import { join, resolve, dirname } from 'node:path'; import { BackendClient, bounded } from './backend-client.mjs'; import { bundleManifest } from './bundle-manifest.mjs'; import { coreCommand } from './core-client.mjs'; -import { withInterrupts } from './process.mjs'; +import { withInterrupts, runCommand } from './process.mjs'; import { createReport } from './report.mjs'; const pkg = resolve(process.env.LITHE_TEST_PACKAGE ?? resolve('dist/package', 'io.github.lithe-idea.maven-build')); @@ -44,6 +44,15 @@ await withInterrupts(async signal => { const stop = () => { for (const client of clients) client.kill(); }; signal.addEventListener('abort', stop, { once: true }); try { + const editorTests = join(scratch, 'editor-tests'); mkdirSync(editorTests); + await report.step('compile the production Maven settings editor regressions', () => runCommand(join(dirname(java), 'javac'), + ['-encoding', 'UTF-8', '-source', '8', '-target', '8', '-cp', join(pkg, 'lib/lithe-maven-backend.jar'), '-d', editorTests, + resolve('test/fixtures/configuration-editor/ConfigurationEditorRegression.java')], { signal, timeoutMs: 20000 })); + for (const name of ['preserve', 'namespace', 'list', 'reset-and-missing', 'bom', 'invalid']) { + await report.step('Maven settings editor: ' + name, () => runCommand(java, + ['-cp', editorTests + (process.platform === 'win32' ? ';' : ':') + join(pkg, 'lib/lithe-maven-backend.jar'), + 'io.github.litheidea.maven.backend.ConfigurationEditorRegression', name], { signal, timeoutMs: 10000 })); + } mkdirSync(join(root, '.mvn'), { recursive: true }); mkdirSync(home); // An invalid POM proves that inspection exits before reactor import. @@ -70,15 +79,27 @@ await withInterrupts(async signal => { assert.equal(existsSync(join(root, 'target')), false); assert.equal(existsSync(repository), false, 'Reading inherited configuration must not create its repository'); }); - await report.step('Core edits the approved native field and Maven re-reads the saved source', async () => { + await report.step('the Maven provider edits private staging and Maven re-reads the published source', async () => { const source = snapshot.sources.find(source => source.id === 'user'); - const replacement = coreCommand('build.editConfigurationDocument', payload({ snapshot, - edits: { sourceID: 'user', revision: source.revision, values: { localRepository: join(scratch, 'saved-repository') } }, - document: sourcesBefore[0].toString('utf8') })).edit; - assert.equal(hash(readFileSync(user)), source.revision); - writeFileSync(user, replacement.document); - assert.ok(replacement.document.includes('')); - assert.ok(replacement.document.includes('fixture-secret-sentinel')); + const outputFile = join(state, 'native-edit.json'); + writeFileSync(outputFile, '', { mode: 0o600 }); + const edits = { sourceID: 'user', revision: source.revision, values: { localRepository: join(scratch, 'saved-repository') } }; + const planned = coreCommand('build.configurationEditPlan', payload({ ...request({ settingsFile: user }), + workspaceStateDirectory: state, outputFile, snapshot, edits })).plan; + const raw = await client.request(planned.provider.method, planned.provider.params); + const receipt = coreCommand('build.decodeConfigurationEdit', payload({ snapshot, edits, result: raw })).edit; + assert.equal(hash(readFileSync(user)), source.revision, 'Provider never writes the original source'); + assert.ok(!JSON.stringify(raw).includes('fixture-secret-sentinel')); + const replacement = readFileSync(outputFile); + assert.equal(receipt.revision, hash(replacement)); + assert.ok(replacement.toString().includes('')); + assert.ok(replacement.toString().includes('fixture-secret-sentinel')); + writeFileSync(user, replacement); + rmSync(outputFile); + const fresh = await client.request('lithe/build/configuration', request({ settingsFile: user })); + const laterEdits = { sourceID: 'user', revision: fresh.sources.find(source => source.id === 'user').revision, values: { localRepository: join(scratch, 'late-repository') } }; + await assert.rejects(client.request(planned.provider.method, { ...planned.provider.params, snapshot: fresh, edits: laterEdits })); + assert.equal(existsSync(outputFile), false, 'A late request cannot recreate host staging'); const updated = await client.request('lithe/build/configuration', request({ settingsFile: user })); const field = updated.sources.find(source => source.id === 'user').fields.find(field => field.id === 'localRepository'); assert.equal(field.value, join(scratch, 'saved-repository')); diff --git a/scripts/test-native-core.mjs b/scripts/test-native-core.mjs index 8d3ad8c..2f9ebb2 100644 --- a/scripts/test-native-core.mjs +++ b/scripts/test-native-core.mjs @@ -16,6 +16,11 @@ const id = 'io.github.lithe-idea.maven-build'; const pkg = resolve(process.env.LITHE_TEST_PACKAGE ?? resolve('dist/package', id)); const before = bundleManifest(pkg); const manifest = JSON.parse(readFileSync(join(pkg, 'plugin.json'))); +const preparationTask = role => { + const tasks = manifest.buildSystems[0].tasks.filter(task => task.preparation?.purpose === 'run' && task.preparation.sourceRoles.includes(role)); + assert.equal(tasks.length, 1, `Exactly one run preparation for ${role}`); + return tasks[0].id; +}; const scratch = realpathSync(mkdtempSync(join(tmpdir(), 'lithe-maven-core-'))); const workspace = join(scratch, 'workspace'); const root = 'nested'; @@ -183,14 +188,14 @@ await withInterrupts(async (signal) => { test inputstrue preparedupstream`)); const plan = task => build('build.taskPlan', planned({ task, project, options: { profiles: ['prepared'] } })).plan; - const main = await send(plan('java-prepare-run-main'), 'prepare-main-resources'); + const main = await send(plan(preparationTask('source')), 'prepare-main-resources'); assert.equal(main.exitCode, 0, main.output); assert.equal(readFileSync(join(directory, 'target/classes/runtime.properties'), 'utf8'), 'selected=upstream'); assert.equal(existsSync(join(directory, 'target/test-classes/test.properties')), false); - const tests = await send(plan('java-prepare-run-test'), 'prepare-test-resources'); + const tests = await send(plan(preparationTask('testSource')), 'prepare-test-resources'); assert.equal(tests.exitCode, 0, tests.output); assert.equal(readFileSync(join(directory, 'target/test-classes/test.properties'), 'utf8'), 'test=upstream'); - await assert.rejects(send(build('build.taskPlan', planned({ task: 'java-prepare-run-main', project, userArguments: ['verify'] })).plan, + await assert.rejects(send(build('build.taskPlan', planned({ task: preparationTask('source'), project, userArguments: ['verify'] })).plan, 'reject-extra-resource-goals'), /no raw goals/); } finally { writeFileSync(pom, original); rmSync(resources, { recursive: true, force: true }); rmSync(testResources, { recursive: true, force: true }); } }); diff --git a/scripts/test-native.mjs b/scripts/test-native.mjs index f503628..2b64b4a 100644 --- a/scripts/test-native.mjs +++ b/scripts/test-native.mjs @@ -13,6 +13,12 @@ import { createReport } from './report.mjs'; const id = 'io.github.lithe-idea.maven-build'; const pkg = resolve(process.env.LITHE_TEST_PACKAGE ?? resolve('dist/package', id)); const before = bundleManifest(pkg); +const manifest = JSON.parse(readFileSync(join(pkg, 'plugin.json'))); +const preparationTask = role => { + const tasks = manifest.buildSystems[0].tasks.filter(task => task.preparation?.purpose === 'run' && task.preparation.sourceRoles.includes(role)); + assert.equal(tasks.length, 1, `Exactly one run preparation for ${role}`); + return tasks[0].id; +}; const scratch = realpathSync(mkdtempSync(join(tmpdir(), 'lithe-maven-native-'))); const workspace = join(scratch, 'workspace'); const root = join(workspace, 'nested'); @@ -82,8 +88,8 @@ await withInterrupts(async (signal) => { assert.match(result.output, /\[WARNING\]/); }); await report.step('Java resource tasks preserve effective options and refuse missing projects or injected goals', async () => { - for (const [task, goals] of [['java-prepare-run-main', ['resources:resources']], - ['java-prepare-run-test', ['resources:resources', 'resources:testResources']]]) { + for (const [task, goals] of [[preparationTask('source'), ['resources:resources']], + [preparationTask('testSource'), ['resources:resources', 'resources:testResources']]]) { const result = await client.request('lithe/build/execute', params({ task, project: selected, options: { profiles: ['ci'] }, operationID: task })); assert.equal(result.exitCode, 0); assert.deepEqual(executionRuns().at(-1).argv, ['-B', '-ntp', '-Pci', '-pl', 'core', '-am', ...goals]); diff --git a/test/fixtures/configuration-editor/ConfigurationEditorRegression.java b/test/fixtures/configuration-editor/ConfigurationEditorRegression.java new file mode 100644 index 0000000..487a844 --- /dev/null +++ b/test/fixtures/configuration-editor/ConfigurationEditorRegression.java @@ -0,0 +1,71 @@ +package io.github.litheidea.maven.backend; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; + +/** Process-isolated regressions of the production JDK settings writer. */ +public final class ConfigurationEditorRegression { + public static void main(String[] args) throws Exception { + String name = args[0]; + if ("preserve".equals(name)) { + String original = "fixture-secret-sentinel"; + byte[] bytes = original.getBytes(StandardCharsets.UTF_8), before = bytes.clone(); + String changed = replace(bytes, values("localRepository", "仓库 & value")); + check(changed.contains("mode=\"retained\""), "attribute lost"); + check(changed.contains(""), "comment lost"); + check(changed.contains("fixture-secret-sentinel"), "unrelated secret changed"); + check(changed.contains("仓库 & value"), "text must be escaped"); + check(Arrays.equals(bytes, before), "input buffer changed"); + } else if ("namespace".equals(name)) { + String changed = replace("untouched/before".getBytes(StandardCharsets.UTF_8), values("localRepository", "/after")); + check(changed.contains("untouched"), "foreign namespace changed"); + check(changed.contains("/after"), "namespace binding changed"); + } else if ("list".equals(name)) { + String changed = replace("oldkeep".getBytes(StandardCharsets.UTF_8), values("activeProfiles", Arrays.asList("ci", "Unicode-界 & value"))); + check(!changed.contains(">old<") && changed.contains("ci"), "list was not replaced"); + check(changed.contains("Unicode-界 & value") && changed.contains(""), "list text/comment lost"); + check(changed.contains("keep"), "unrelated node changed"); + } else if ("reset-and-missing".equals(name)) { + String changed = replace("/oldoldkeep".getBytes(StandardCharsets.UTF_8), values("activeProfiles", null)); + check(!changed.contains("activeProfiles") && changed.contains(""), "reset did not preserve comment"); + check(changed.contains("/old"), "reset changed another field"); + changed = replace(null, values("localRepository", "/created")); + check(changed.contains("http://maven.apache.org/SETTINGS/1.0.0") && changed.contains(">/created<"), "missing source creation failed"); + changed = replace("".getBytes(StandardCharsets.UTF_8), values("activeProfiles", Arrays.asList())); + check(changed.contains("activeProfiles"), "explicit empty list became absent"); + } else if ("bom".equals(name)) { + String changed = replace("\ufeff".getBytes(StandardCharsets.UTF_8), values("localRepository", "仓库")); + check(changed.startsWith("\ufeff") && changed.contains("") && changed.contains("仓库"), "BOM/Unicode lost"); + } else if ("invalid".equals(name)) { + for (String document : new String[] { + "]>&x;", + "", + "ab", + "", + "must remain" + }) rejects(document); + StringBuilder deep = new StringBuilder(""); + for (int i = 0; i < 65; i++) deep.append(""); + for (int i = 0; i < 65; i++) deep.append(""); + deep.append(""); rejects(deep.toString()); + boolean invalidCharacter = false; + try { ConfigurationEditor.replace("".getBytes(StandardCharsets.UTF_8), values("localRepository", "invalid" + (char) 1)); } + catch (Exception expected) { invalidCharacter = true; } + check(invalidCharacter, "invalid XML characters reached publication"); + } else throw new AssertionError("unknown regression case"); + } + private static void rejects(String original) throws Exception { + try { ConfigurationEditor.replace(original.getBytes(StandardCharsets.UTF_8), values("localRepository", "/new")); } + catch (Exception expected) { return; } + throw new AssertionError("unsafe settings were accepted"); + } + private static String replace(byte[] original, Map values) throws Exception { + return new String(ConfigurationEditor.replace(original, values), StandardCharsets.UTF_8); + } + private static Map values(String field, Object value) { + Map values = new LinkedHashMap<>(); values.put(field, value); return values; + } + private static void check(boolean condition, String message) { if (!condition) throw new AssertionError(message); } +} From a3ba990dfd963bbdf17b2371264a103d00c445ad Mon Sep 17 00:00:00 2001 From: wgw Date: Sun, 1 Nov 2026 09:24:19 +0800 Subject: [PATCH 19/24] fix(maven): declare public debugger type and consume connection target --- README.md | 4 +++- .../litheidea/maven/backend/MavenRunPreparation.java | 7 +++++-- io.github.lithe-idea.maven-build/plugin.json | 1 + scripts/test-framework-debug.mjs | 2 +- scripts/test-native-core.mjs | 2 +- 5 files changed, 11 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index a67b294..2fd6499 100644 --- a/README.md +++ b/README.md @@ -307,7 +307,9 @@ Wrapper 元数据 `maven.wrapper` / `maven.minimumVersion` 来自所选 reactor 参与准备时的有效模型读取。开发组合可用 `scripts/package-development.mjs` 及 `scripts/test-native-core.mjs` 验证;正式 SDK 锁定和发行条件保持不变。 -开发协议 11 的 JVM 调试由宿主选择本机端口,后端按当前 Mojo 描述符设置回环监听和 +开发协议 11 在清单声明公开 `configurationType: java`,由宿主从当前调试注册表选择 +适配器并传递身份和本机 connection 目标;Maven 不引用其他插件的语言服务器。 +后端按当前 Mojo 描述符设置回环监听和 启动前暂停。参数绑定同时识别 Maven 的 `property` 与 `defaultValue` 表达式,例如 Quarkus 的 `jvm.args` 属于后者。Spring Boot 保留已有 JVM 参数,Quarkus/Micronaut 使用框架自带的调试开关;遇到重复 JDWP 或不兼容描述符明确拒绝。 diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java index 33bab92..8b398dc 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java @@ -51,8 +51,11 @@ static Map prepare(Map params, Path root, Path w addArguments(arguments, "arguments", programArguments); if (options.containsKey("debug")) { Map debug = Json.object(options.get("debug")); - Object port = debug.get("port"); - if (debug.size() != 2 || !"jvm".equals(debug.get("runtime")) || !(port instanceof Number) + Map connection = Json.object(debug.get("target")); + Object port = connection.get("port"); + if (debug.size() != 3 || !"java".equals(debug.get("configurationType")) + || connection.size() != 3 || !"connection".equals(connection.get("kind")) + || !"127.0.0.1".equals(connection.get("host")) || !(port instanceof Number) || ((Number) port).doubleValue() != ((Number) port).longValue() || ((Number) port).longValue() < 1 || ((Number) port).longValue() > 65535) throw invalid("Select a valid JVM debug port."); arguments.add("-Dlithe.run.debugPort=" + ((Number) port).longValue()); diff --git a/io.github.lithe-idea.maven-build/plugin.json b/io.github.lithe-idea.maven-build/plugin.json index 0a62be3..1076d37 100644 --- a/io.github.lithe-idea.maven-build/plugin.json +++ b/io.github.lithe-idea.maven-build/plugin.json @@ -33,6 +33,7 @@ "run": [ { "id": "framework", + "debug": {"configurationType": "java"}, "source": "provider", "name": "Run Maven service", "execution": "service", diff --git a/scripts/test-framework-debug.mjs b/scripts/test-framework-debug.mjs index f7ac32e..0234bb6 100644 --- a/scripts/test-framework-debug.mjs +++ b/scripts/test-framework-debug.mjs @@ -127,7 +127,7 @@ await withInterrupts(async signal => { assert.ok(target, `${fixture.name} must publish its real effective target`); const port = await unusedPort(); const launchOptions = { execution: 'service', runtimeArguments: [], arguments: ['a b', '雪'], - environment: { LITHE_RUN_VALUE: 'Provider' }, debug: { runtime: 'jvm', port } }; + environment: { LITHE_RUN_VALUE: 'Provider' }, debug: { adapterID: 'dev.lithe.plugin.java-support/java', configurationType: 'java', target: { kind: 'connection', host: '127.0.0.1', port } } }; const prepared = await send(plan('build.prepareRunPlan', planned({ workspaceRoot: workspace, run: 'framework', project: { name: app.name, path: app.path }, target: { name: target.name, path: target.path, tags: target.tags }, launchOptions })).plan); const launch = plan('build.decodeRunPreparation', { workspaceRoot: workspace, root, launchOptions, result: prepared }).launch; diff --git a/scripts/test-native-core.mjs b/scripts/test-native-core.mjs index 2f9ebb2..4758d8f 100644 --- a/scripts/test-native-core.mjs +++ b/scripts/test-native-core.mjs @@ -410,7 +410,7 @@ await withInterrupts(async (signal) => { allocator.once('error', reject); allocator.listen({ port: 0, host: '127.0.0.1', signal: allocation.signal }, () => { const port = allocator.address().port; allocator.close(error => error ? reject(error) : resolve(port)); }); }), 'allocate loopback debug port', 5000).finally(() => allocation.abort()); - const debugOptions = { ...launchOptions, runtimeArguments: [], debug: { runtime: 'jvm', port } }; + const debugOptions = { ...launchOptions, runtimeArguments: [], debug: { adapterID: 'dev.lithe.plugin.java-support/java', configurationType: 'java', target: { kind: 'connection', host: '127.0.0.1', port } } }; const debugResult = await send(build('build.prepareRunPlan', request({ launchOptions: debugOptions })).plan, 'framework-debug'); const debugPlan = build('build.decodeRunPreparation', { workspaceRoot: workspace, root: selectedRoot, launchOptions: debugOptions, result: debugResult }).launch; const helper = join(scratch, 'ResumeJvm.java'); From 8751ebce1dad9d1a84b3357c88989635a4883f2c Mon Sep 17 00:00:00 2001 From: wgw Date: Sun, 1 Nov 2026 19:08:39 +0800 Subject: [PATCH 20/24] Delegate implicit module goals to Maven and test opaque Run selectors --- README.md | 3 ++- .../maven/backend/MavenRunPreparation.java | 2 +- scripts/test-native-core.mjs | 22 ++++++++++++++----- scripts/test-windows-workspace.mjs | 6 ++--- 4 files changed, 23 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 2fd6499..51ec81d 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ 为 [Lithe](https://github.com/1lck/Lithe-IDEA) 提供 Maven 项目支持:识别 `pom.xml`,在 Maven 工具窗口里列出 模块、生命周期和插件目标,运行任务和测试,查看依赖树。 -这是一个**社区插件**,用 Lithe 的构建系统接口(插件 API 3 的 `buildSystems` 和 `buildProviders: 7`)实现, +这是一个**社区插件**,用 Lithe 的构建系统接口(插件 API 3 的 `buildSystems` 和 `buildProviders: 11`)实现, 除了下面说的 Maven 扩展 jar 和读取项目用的 Java 后端,没有任何宿主代码。 > English: Maven support for Lithe through the declarative `buildSystems` plugin API — project tree, lifecycle and @@ -25,6 +25,7 @@ | 诊断 | 把编译输出中的 `[ERROR]`/`[WARNING] 文件:[行,列]` 显示为问题 | | 依赖 | 按模块显示依赖树(含作用域和传递依赖),反应堆内未安装的兄弟模块也能解析;一次 Maven 运行读出全部模块,展开模块不再各跑一次 | | 快照 | 项目和依赖保存在工作区状态目录,重新打开项目时直接显示;POM、`.mvn/` 配置、settings.xml、选项或 Maven/Java 变化后才重新运行 Maven,Reload 总是重新运行 | +| 运行配置 | 框架服务保留运行时参数、程序参数与目录;模块任务把目标列表直接交给 Maven,空列表使用 Maven 自己的 defaultGoal 或无目标错误,不补造默认目标;模块任务不接受应用运行时参数或入口,明确报告不支持 | | 同步 | `pom.xml`、`.mvn/maven.config`、`.mvn/extensions.xml` 变化后重新读取项目 | ## 依赖的程序 diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java index 8b398dc..94a398a 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java @@ -73,7 +73,7 @@ static Map prepare(Map params, Path root, Path w } else { if (options.containsKey("debug")) throw invalid("Select a framework service to debug; arbitrary Maven goals have no JVM debug target."); if (!runtimeArguments.isEmpty() || options.containsKey("entrypoint")) throw invalid("Maven module goals do not accept application runtime or entrypoint options."); - if (programArguments.isEmpty()) throw invalid("A Maven module run needs one or more goals."); + // An empty list delegates defaultGoal (or Maven's own no-goal error) to Maven. modelArguments(params); // The same checked properties were supplied to the model read. arguments.addAll(programArguments); } diff --git a/scripts/test-native-core.mjs b/scripts/test-native-core.mjs index 4758d8f..efa1058 100644 --- a/scripts/test-native-core.mjs +++ b/scripts/test-native-core.mjs @@ -154,13 +154,18 @@ await withInterrupts(async (signal) => { const active = await read(['framework']); assert.equal(active.projects.find(project => project.name === 'reactor').properties['run.provider'], undefined, 'aggregators are not services'); assert.ok(active.projects.filter(project => project.name !== 'reactor').every(project => project.properties['run.provider'] === 'quarkus.maven'), 'Maven applies the inherited active Profile'); - const ownership = active.projects.map(project => ({ path: project.path, name: project.name, mavenReactorPath: root, - mavenRunProvider: project.properties['run.provider'], contentRoots: [] })); + const ownership = active.projects.map(project => ({ path: project.path, name: project.name, mavenReactorPath: root, contentRoots: [] })); + const runs = active.projects.flatMap(project => manifest.buildSystems[0].run.flatMap(declaration => active.targets + .filter(target => target.projectID === project.id && declaration.fromTargets.tags.some(tag => target.tags.includes(tag))) + .map(target => ({ projectPath: project.path, name: project.name, reference: { pluginID: manifest.id, buildSystemID: 'maven', root, + run: declaration.id, projectID: project.id, targetID: target.id, execution: declaration.execution, userArguments: [] } })))); writeFileSync(pom, ''); - const generated = coreCommand('runConfig.generate', { root: workspace, paths: [], javaEntrypoints: { schemaVersion: 1, entries: [], diagnostics: [] }, projectOwnership: ownership }, null); - assert.deepEqual(generated.generated.configurations.map(item => item.id).sort(), ['quarkus.maven:nested/app', 'quarkus.maven:nested/core']); + const generated = coreCommand('runConfig.generate', { root: workspace, paths: [], javaEntrypoints: { schemaVersion: 1, entries: [], diagnostics: [] }, projectOwnership: ownership, providerRuns: runs }, null); + assert.equal(generated.generated.configurations.length, runs.length); + const services = generated.generated.configurations.filter(item => item.execution === 'service'); + assert.deepEqual(services.map(item => item.extensions.build.projectID).sort(), active.projects.filter(project => project.name !== 'reactor').map(project => project.id).sort()); for (const item of generated.generated.configurations) { - assert.equal(item.cwd, root); assert.equal(item.execution, 'service'); + assert.equal(item.cwd, root); assert.equal(item.provider, 'build.provider'); assert.equal(item.extensions.maven, undefined); } } finally { writeFileSync(pom, original); } }); @@ -362,6 +367,8 @@ await withInterrupts(async (signal) => { const pom = join(directory, module, 'pom.xml'); writeFileSync(pom, readFileSync(pom, 'utf8').replaceAll('1.0.0-SNAPSHOT', version)); } + const reactorPom = join(directory, 'pom.xml'); + writeFileSync(reactorPom, readFileSync(reactorPom, 'utf8').replace('', 'validate')); const appPom = join(directory, 'app/pom.xml'); const original = readFileSync(appPom, 'utf8'); writeFileSync(appPom, original.replace('', `org.springframework.boot @@ -455,6 +462,11 @@ await withInterrupts(async (signal) => { const modulePlan = await send(build('build.prepareRunPlan', moduleRequest).plan, 'module-prepare'); assert.equal(modulePlan.arguments.at(-1), '-Dcustom.value=two words'); assert.equal(modulePlan.arguments.at(-2), 'validate'); + await assert.rejects(send(build('build.prepareRunPlan', { ...moduleRequest, launchOptions: { ...moduleOptions, runtimeArguments: ['-Dsaved=value'] } }).plan, 'module-runtime-choice'), /do not accept/); + await assert.rejects(send(build('build.prepareRunPlan', { ...moduleRequest, launchOptions: { ...moduleOptions, entrypoint: 'opaque/entry' } }).plan, 'module-entry-choice'), /do not accept/); + const defaultOptions = { ...moduleOptions, arguments: [] }; + const defaultPlan = await send(build('build.prepareRunPlan', { ...moduleRequest, launchOptions: defaultOptions }).plan, 'module-default-goal'); + await runCommand(maven, defaultPlan.arguments, { cwd: directory, env: { ...process.env, ...defaultPlan.environment }, signal, timeoutMs: mavenTimeout() }); for (const argument of ['--file=../outside.xml', '-Pother', '-s', '-Dmaven.repo.local=/other', '-Dlithe.run.goal=other']) { await assert.rejects(send(build('build.prepareRunPlan', { ...moduleRequest, launchOptions: { ...moduleOptions, arguments: ['validate', argument] } }).plan, 'module-selection-override'), /build options/); diff --git a/scripts/test-windows-workspace.mjs b/scripts/test-windows-workspace.mjs index 8c11692..a9eb251 100644 --- a/scripts/test-windows-workspace.mjs +++ b/scripts/test-windows-workspace.mjs @@ -173,9 +173,9 @@ await withInterrupts(async signal => { writeFileSync(local, JSON.stringify({ version: 2, configurations: [ { id: 'user:anchor', name: 'Saved task', provider: 'build.provider', execution: 'task', extensions: { build: { pluginID: manifest.id, buildSystemID: 'maven', root, run: 'module', projectID: project.id, targetID: target.id, execution: 'task', userArguments: ['compile'] } } }, - { id: 'user:scoped', name: 'Scoped module', provider: 'maven.module', execution: 'task', cwd: root, args: ['compile'], - toolchains: { java: 'project-jdk', maven: 'project-maven' }, extensions: { maven: { module: '.', skipTests: false }, - java: { mavenExecutablePath: scopedTool, mavenJavaHomePath: javaHome } } }, + { id: 'user:scoped', name: 'Scoped module', provider: 'build.provider', execution: 'task', cwd: root, args: ['compile'], + extensions: { build: { pluginID: manifest.id, buildSystemID: 'maven', root, run: 'module', projectID: project.id, targetID: target.id, execution: 'task' }, + 'build-run': { options: { skipTests: false } }, java: { mavenExecutablePath: scopedTool, mavenJavaHomePath: javaHome } } }, ] })); let scope; try { From 25755832c8c938d55ba563e4bb22b2fb5018290d Mon Sep 17 00:00:00 2001 From: wgw Date: Sun, 1 Nov 2026 20:38:19 +0800 Subject: [PATCH 21/24] Declare Maven tools and use namespace-owned runtime selections --- README.md | 13 ++ .../maven/backend/MavenRunPreparation.java | 2 +- io.github.lithe-idea.maven-build/plugin.json | 150 +++++++++++++++++- scripts/test-native-core.mjs | 9 +- scripts/test-windows-workspace.mjs | 2 +- 5 files changed, 167 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 51ec81d..d4143b1 100644 --- a/README.md +++ b/README.md @@ -336,3 +336,16 @@ TypeScript 工作区编排,连接真实 Provider 和 `LITHE_CORE_LIBRARY` 指 运行,不需要安装宿主前端依赖,也不修改正式 SDK 锁定。它不代替 Windows 原生工具发现、 Job Object 进程清理、Build UI、配置和 Run 消费者迁移;固定提交的开发 CI 在 runner Maven 组合执行该测试。 + +### Fixed tool-definition integration + +The Stage D development combination uses the host toolchain foundation pinned at +`b87c7f60dd80f851695d7052b5287a5c93c7fa46`. Maven contributes +`io.github.lithe-idea.maven-build:maven` through `toolDefinitions: 1` and selects +it through `executableResolution: 2`. Its Java prerequisite selects the official +Java Support definition `java`; the backend bootstrap remains independent. +Directory pins and project wrappers are resolved by the host's common resolver, +with declared layouts, version probes and environment exports. A community +package does not claim the official short Maven ID or add a host-specific JDK +resolver. Run generation does not consume Maven Wrapper/version ownership fields. +This remains a development-only combination; published SDK locks are unchanged. diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java index 94a398a..558e111 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenRunPreparation.java @@ -81,7 +81,7 @@ static Map prepare(Map params, Path root, Path w if (params.get("environment") instanceof Map) environment.putAll(Json.object(params.get("environment"))); environment.putAll(Json.object(options.get("environment"))); Map result = new LinkedHashMap<>(); - Map executable = new LinkedHashMap<>(); executable.put("kind", "toolchain"); executable.put("value", "project-maven"); + Map executable = new LinkedHashMap<>(); executable.put("kind", "toolchain"); executable.put("value", "io.github.lithe-idea.maven-build:maven"); result.put("executable", executable); result.put("arguments", arguments); result.put("workingDirectory", cwd); result.put("environment", environment); return result; } diff --git a/io.github.lithe-idea.maven-build/plugin.json b/io.github.lithe-idea.maven-build/plugin.json index 1076d37..b088f16 100644 --- a/io.github.lithe-idea.maven-build/plugin.json +++ b/io.github.lithe-idea.maven-build/plugin.json @@ -4,7 +4,7 @@ "displayName": "Maven", "version": "0.1.1", "pluginAPIVersion": 3, - "requires": { "buildProviders": 11, "buildModelInputs": 1, "buildSystems": 4, "executableResolution": 2, "serverProcess": 1 }, + "requires": { "buildProviders": 11, "buildModelInputs": 1, "buildSystems": 4, "executableResolution": 2, "toolDefinitions": 1, "serverProcess": 1 }, "vendor": { "id": "io.github.lithe-idea", "displayName": "Lithe Community", @@ -13,6 +13,150 @@ "permissions": ["languageServer.launch", "process.build"], "activationEvents": ["onBuildSystem:maven"], "languages": [], + "toolDefinitions": [ + { + "id": "io.github.lithe-idea.maven-build:maven", + "displayName": "Maven", + "icon": { + "path": "icons/maven.svg" + }, + "executableLayouts": [ + { + "path": "bin/mvn", + "platforms": [ + "macos", + "linux" + ] + }, + { + "path": "bin/mvn.cmd", + "platforms": [ + "windows" + ] + } + ], + "executables": [ + { + "id": "pinned", + "kind": "setting", + "settingID": "executable", + "layer": "project" + }, + { + "id": "wrapper", + "kind": "projectFile", + "path": "mvnw", + "requires": [ + ".mvn/wrapper/maven-wrapper.properties" + ], + "platforms": [ + "macos", + "linux" + ] + }, + { + "id": "wrapper-windows", + "kind": "projectFile", + "path": "mvnw.cmd", + "requires": [ + ".mvn/wrapper/maven-wrapper.properties" + ], + "platforms": [ + "windows" + ] + }, + { + "id": "project-request", + "kind": "toolchain", + "scope": "project" + }, + { + "id": "default", + "kind": "setting", + "settingID": "executable", + "layer": "global" + }, + { + "id": "global-request", + "kind": "toolchain", + "scope": "global" + }, + { + "id": "home", + "kind": "environment", + "variable": "MAVEN_HOME", + "path": "bin/mvn", + "platforms": [ + "macos", + "linux" + ] + }, + { + "id": "home-windows", + "kind": "environment", + "variable": "MAVEN_HOME", + "path": "bin/mvn.cmd", + "platforms": [ + "windows" + ] + }, + { + "id": "shell", + "kind": "command", + "command": "mvn" + }, + { + "id": "installed", + "kind": "toolchain", + "scope": "installed" + } + ], + "version": { + "arguments": [ + "--version" + ], + "pattern": "Apache Maven (\\d+(?:\\.\\d+)*)" + }, + "homeVariable": "MAVEN_HOME", + "commands": [ + "mvn" + ], + "wrappers": [ + { + "path": "mvnw", + "requires": [ + ".mvn/wrapper/maven-wrapper.properties" + ], + "platforms": [ + "macos", + "linux" + ] + }, + { + "path": "mvnw.cmd", + "requires": [ + ".mvn/wrapper/maven-wrapper.properties" + ], + "platforms": [ + "windows" + ] + } + ], + "exports": [ + { + "name": "MAVEN_HOME", + "value": "${home}" + } + ], + "pathPrepend": [ + "${home}/bin" + ], + "launch": [ + "${executable}", + "${arguments}" + ] + } + ], "buildSystems": [ { "id": "maven", @@ -23,9 +167,9 @@ "nesting": "outermost" }, "invocation": { - "executables": [{ "kind": "toolchain", "toolchainID": "project-maven" }], + "executables": [{ "kind": "toolchain", "toolchainID": "io.github.lithe-idea.maven-build:maven" }], "runtimeDependencies": [{ "id": "java", "minimumVersion": "8", - "executables": [{ "kind": "toolchain", "toolchainID": "project-maven-jdk" }] }], + "executables": [{ "kind": "toolchain", "toolchainID": "java" }] }], "globalArguments": [], "version": { "arguments": ["--version"], "pattern": "Apache Maven (\\d+\\.\\d+\\.\\d+)" }, "minimumVersion": "3.6.3" diff --git a/scripts/test-native-core.mjs b/scripts/test-native-core.mjs index efa1058..3dd0fa3 100644 --- a/scripts/test-native-core.mjs +++ b/scripts/test-native-core.mjs @@ -119,9 +119,8 @@ await withInterrupts(async (signal) => { writeFileSync(properties, 'distributionUrl=https://example.invalid/apache-maven-99.0.0-bin.zip\n'); const generated = coreCommand('runConfig.generate', { root: workspace, paths: [], javaEntrypoints: { schemaVersion: 1, entries: [] }, projectOwnership: current.projects.map(project => ({ path: project.path, name: project.name, mavenReactorPath: root, - mavenMinimumVersion: project.properties['maven.minimumVersion'], mavenWrapper: root + '/' + project.properties['maven.wrapper'], contentRoots: [] })) }, null); - assert.equal(generated.toolchainRequirements.toolchains['project-maven'].minimumVersion, '3.9.9'); - assert.equal(generated.toolchainRequirements.toolchains['project-maven'].wrapper, 'nested/mvnw'); + contentRoots: [] })) }, null); + assert.equal(generated.toolchainRequirements.toolchains['project-maven'], undefined, 'Run generation never interprets provider-owned Wrapper or version facts'); writeFileSync(properties, '# distributionUrl=https://example.invalid/apache-maven-99.0.0-bin.zip\ndistributionUrl=https://example.invalid/custom.zip\n'); current = await read(); assert.ok(current.projects.every(project => project.properties['maven.minimumVersion'] === undefined), 'unrecognized distribution stays unknown'); @@ -397,7 +396,7 @@ await withInterrupts(async (signal) => { project: { name: app.name, path: app.path }, target: { name: target.name, path: target.path, tags: target.tags }, launchOptions, ...extra }); const prepared = await send(build('build.prepareRunPlan', request({})).plan, 'framework-launch'); const launch = build('build.decodeRunPreparation', { workspaceRoot: workspace, root: selectedRoot, launchOptions, result: prepared }).launch; - assert.deepEqual(launch.executable, { kind: 'toolchain', value: 'project-maven' }); + assert.deepEqual(launch.executable, { kind: 'toolchain', value: 'io.github.lithe-idea.maven-build:maven' }); assert.equal(launch.workingDirectory, 'framework cwd'); const transcript = join(scratch, 'framework-launch.log'); const descriptor = openSync(transcript, 'w'); @@ -477,6 +476,8 @@ await withInterrupts(async (signal) => { await report.step('publish the same normalized Maven facts and effective options to a declared consumer', () => { const consumer = JSON.parse(JSON.stringify(manifest)); consumer.id = 'org.example.maven-input-consumer'; + delete consumer.toolDefinitions; + delete consumer.requires.toolDefinitions; consumer.requires.buildProviders = 6; delete consumer.buildSystems[0].modelSharing; delete consumer.buildSystems[0].run; diff --git a/scripts/test-windows-workspace.mjs b/scripts/test-windows-workspace.mjs index a9eb251..7a59bde 100644 --- a/scripts/test-windows-workspace.mjs +++ b/scripts/test-windows-workspace.mjs @@ -133,7 +133,7 @@ await withInterrupts(async signal => { const defaults = structuredClone(workspace.model(instance)); const prepared = await workspace.prepareRun(instance, { run: run.id, projectID: project.id, targetID: target.id, launchOptions: { execution: 'task', runtimeArguments: [], arguments: ['compile'], environment: {}, workingDirectory: root } }).completion; - assert.deepEqual(prepared.launch.executable, { kind: 'toolchain', value: 'project-maven' }); + assert.deepEqual(prepared.launch.executable, { kind: 'toolchain', value: 'io.github.lithe-idea.maven-build:maven' }); assert.ok(prepared.launch.arguments.includes('compile')); assert.equal(prepared.languageImport.kind, 'maven'); assert.equal(prepared.languageImport.mavenContext.mavenExecutablePath, process.env.LITHE_TEST_MAVEN); From 5f701c9669662fd9ad9c0b1c42f1cccbef3743af Mon Sep 17 00:00:00 2001 From: wgw Date: Sun, 1 Nov 2026 21:18:21 +0800 Subject: [PATCH 22/24] test: exercise generic build project ownership through native Core --- scripts/test-native-core.mjs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/test-native-core.mjs b/scripts/test-native-core.mjs index 3dd0fa3..f098d9f 100644 --- a/scripts/test-native-core.mjs +++ b/scripts/test-native-core.mjs @@ -99,7 +99,7 @@ await withInterrupts(async (signal) => { writeFileSync(pom, '99'); const generated = coreCommand('runConfig.generate', { root: workspace, paths: [], javaEntrypoints: { schemaVersion: 1, entries: [] }, - projectOwnership: current.projects.map(project => ({ path: project.path, name: project.name, mavenReactorPath: root, + projectOwnership: current.projects.map(project => ({ path: project.path, name: project.name, build: { pluginID: id, buildSystemID: "maven", root, projectID: project.id }, minimumJavaVersion: version(project), contentRoots: [] })) }, null); assert.equal(generated.toolchainRequirements.toolchains['project-jdk'].minimumVersion, '23'); } finally { writeFileSync(pom, original); writeFileSync(modulePom, originalModule); } @@ -118,7 +118,7 @@ await withInterrupts(async (signal) => { assert.ok(current.projects.every(project => project.properties['maven.minimumVersion'] === '3.9.9'), 'native properties ignore comments and unescape the URL'); writeFileSync(properties, 'distributionUrl=https://example.invalid/apache-maven-99.0.0-bin.zip\n'); const generated = coreCommand('runConfig.generate', { root: workspace, paths: [], javaEntrypoints: { schemaVersion: 1, entries: [] }, - projectOwnership: current.projects.map(project => ({ path: project.path, name: project.name, mavenReactorPath: root, + projectOwnership: current.projects.map(project => ({ path: project.path, name: project.name, build: { pluginID: id, buildSystemID: "maven", root, projectID: project.id }, contentRoots: [] })) }, null); assert.equal(generated.toolchainRequirements.toolchains['project-maven'], undefined, 'Run generation never interprets provider-owned Wrapper or version facts'); writeFileSync(properties, '# distributionUrl=https://example.invalid/apache-maven-99.0.0-bin.zip\ndistributionUrl=https://example.invalid/custom.zip\n'); @@ -153,7 +153,7 @@ await withInterrupts(async (signal) => { const active = await read(['framework']); assert.equal(active.projects.find(project => project.name === 'reactor').properties['run.provider'], undefined, 'aggregators are not services'); assert.ok(active.projects.filter(project => project.name !== 'reactor').every(project => project.properties['run.provider'] === 'quarkus.maven'), 'Maven applies the inherited active Profile'); - const ownership = active.projects.map(project => ({ path: project.path, name: project.name, mavenReactorPath: root, contentRoots: [] })); + const ownership = active.projects.map(project => ({ path: project.path, name: project.name, build: { pluginID: id, buildSystemID: "maven", root, projectID: project.id }, contentRoots: [] })); const runs = active.projects.flatMap(project => manifest.buildSystems[0].run.flatMap(declaration => active.targets .filter(target => target.projectID === project.id && declaration.fromTargets.tags.some(tag => target.tags.includes(tag))) .map(target => ({ projectPath: project.path, name: project.name, reference: { pluginID: manifest.id, buildSystemID: 'maven', root, From 9193bc89700dec54e61267e7b40c897e7fca188d Mon Sep 17 00:00:00 2001 From: wgw Date: Mon, 2 Nov 2026 14:45:40 +0800 Subject: [PATCH 23/24] ci: use the artifact from the fixed SDK source without a hardcoded version --- .github/workflows/ci.yml | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7baf417..c658046 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -132,8 +132,18 @@ jobs: 17 - name: Build the explicit development SDK and isolated plugin package run: | - mvn -B -ntp -q -f .artifacts/sdk-source/sdk/java/pom.xml -DskipTests package - node scripts/package-development.mjs --sdk-jar "$GITHUB_WORKSPACE/.artifacts/sdk-source/sdk/java/plugin-sdk/target/lithe-plugin-sdk-java-0.1.0.jar" + mvn -B -ntp -q -f .artifacts/sdk-source/sdk/java/pom.xml -DskipTests clean package + # The fixed source revision owns its SDK version. A clean build must + # produce exactly one regular SDK JAR; never reuse a stale older JAR. + SDK_JAR=$(node --input-type=module -e ' + import {readdirSync,lstatSync} from "node:fs"; + import {join} from "node:path"; + const directory=process.argv[1]; + const jars=readdirSync(directory).filter(name=>/^lithe-plugin-sdk-java-[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?\.jar$/.test(name)); + if(jars.length!==1 || !lstatSync(join(directory,jars[0])).isFile()) throw Error("Expected one freshly built SDK JAR"); + process.stdout.write(join(directory,jars[0])); + ' "$GITHUB_WORKSPACE/.artifacts/sdk-source/sdk/java/plugin-sdk/target") + node scripts/package-development.mjs --sdk-jar "$SDK_JAR" node --input-type=module -e 'import {readFileSync,appendFileSync} from "node:fs"; const p=JSON.parse(readFileSync(".artifacts/native-development/latest.json")); if(p.developmentOnly!==true) throw Error("Expected a development package"); appendFileSync(process.env.GITHUB_ENV, `LITHE_TEST_PACKAGE=${p.package}\n`);' - name: Check process cleanup run: node scripts/test-process.mjs From 19b6b0103e9bc8c569a3987a09ccd57b69cef966 Mon Sep 17 00:00:00 2001 From: wgw Date: Mon, 2 Nov 2026 16:14:43 +0800 Subject: [PATCH 24/24] test(windows): exercise Agent Build through the real Maven provider --- scripts/test-windows-workspace.mjs | 69 ++++++++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 3 deletions(-) diff --git a/scripts/test-windows-workspace.mjs b/scripts/test-windows-workspace.mjs index 7a59bde..38081b8 100644 --- a/scripts/test-windows-workspace.mjs +++ b/scripts/test-windows-workspace.mjs @@ -18,6 +18,10 @@ if (!process.env.LITHE_TEST_MAVEN || !process.env.LITHE_TEST_JAVA) throw new Err const { WindowsBuildProviderWorkspace } = await import(pathToFileURL(join(resolve(process.env.LITHE_HOST_SOURCE), 'windows/tauri/src/features/build/services/build-provider-workspace.ts')).href); const { createTranslator } = await import(pathToFileURL(join(resolve(process.env.LITHE_HOST_SOURCE), 'windows/tauri/src/i18n/locale.ts')).href); +const { BuildWorkspaceController } = await import(pathToFileURL(join(resolve(process.env.LITHE_HOST_SOURCE), + 'windows/tauri/src/features/build/services/build-workspace-controller.ts')).href); +const { IdeBuildCapabilities } = await import(pathToFileURL(join(resolve(process.env.LITHE_HOST_SOURCE), + 'windows/tauri/src/features/host-api/ide-build-capabilities.ts')).href); const pkg = resolve(process.env.LITHE_TEST_PACKAGE ?? 'dist/package/io.github.lithe-idea.maven-build'); const manifest = JSON.parse(readFileSync(join(pkg, 'plugin.json'), 'utf8')), before = bundleManifest(pkg); const scratch = realpathSync(mkdtempSync(join(tmpdir(), 'lithe-windows-maven-'))), root = 'nested'; @@ -25,7 +29,16 @@ const workspacePath = join(scratch, 'workspace'), state = join(scratch, 'state') mkdirSync(workspacePath); cpSync(new URL('../test/fixtures/reactor', import.meta.url), join(workspacePath, root), { recursive: true }); const instance = { pluginID: manifest.id, buildSystemID: 'maven', root, options: { profiles: ['ci'] } }; const report = createReport('windows-provider-workspace'); -let client, workspace, model, scopedTool; +let client, workspace, controller, model, scopedTool; +const waitForProduct = async (ready, description) => { + let unsubscribe; + try { + await bounded(new Promise(resolve => { + const check = () => { if (ready()) resolve(); }; + unsubscribe = workspace.subscribe(check); check(); + }), description, mavenTimeout()); + } finally { unsubscribe?.(); } +}; await withInterrupts(async signal => { const stop = () => client?.kill(); signal.addEventListener('abort', stop, { once: true }); try { @@ -203,6 +216,56 @@ await withInterrupts(async signal => { const result = await workspace.executeModelTask(instance, task.id).completion; assert.equal(result.exitCode, 0, result.output); }); + await report.step('Windows Agent reads the admitted catalog without starting tooling or reusing a model with different options', async () => { + const core = async (command, manifest, buildSystemID, request, workspaceRoot) => coreCommand(command, { manifest, buildSystemID, workspaceRoot, request }); + controller = new BuildWorkspaceController(workspacePath, { domain: workspace, guard: () => () => {}, + detect: async () => ({ ...coreCommand('build.detect', { workspaceRoot: workspacePath, + plugins: [{ manifest }], options: { maven: instance.options } }), plugins: [{ manifest }], document: { version: 1, systems: {} } }) }); + const agent = new IdeBuildCapabilities(() => controller, () => signal.throwIfAborted(), core); + const count = requests.length; + const inspected = await agent.call('lithe_build_inspect', {}); + const entry = inspected.instances.find(entry => entry.root === root); + assert.ok(entry); assert.equal(entry.modelState, 'unavailable'); + assert.deepEqual(entry.projects, [], 'the earlier manually supplied options are not a catalog-owned model'); + assert.equal(requests.length, count, 'inspect reuses current model and never starts tooling'); + assert.deepEqual(instance.options, { profiles: ['ci'] }); + }); + await report.step('Windows Agent executes an exact real model task and reads its product-owned output', async () => { + const agent = new IdeBuildCapabilities(() => controller, () => signal.throwIfAborted(), + async (command, manifest, buildSystemID, request, workspaceRoot) => coreCommand(command, { manifest, buildSystemID, workspaceRoot, request })); + const entry = controller.snapshot().entries.find(entry => entry.root === root); + assert.equal((await agent.call('lithe_build_reload', { instanceID: entry.id })).reloadRequested, true); + await waitForProduct(() => workspace.hasCurrentModel(entry) || workspace.operationSummaries().some(operation => operation.phase === 'failed'), + 'Agent current model reload'); + const inspected = await agent.call('lithe_build_inspect', {}); + assert.equal(inspected.instances.find(item => item.instanceID === entry.id).modelState, 'ready'); + model = workspace.model(entry); + assert.deepEqual(model.projects.map(project => project.name).sort(), ['app', 'core', 'reactor']); + // Later direct regression steps continue with the catalog's complete + // effective options, never with the former hand-written partial input. + instance.options = structuredClone(entry.options); + const project = model.projects.find(project => project.name === 'core'); + const task = model.tasks.find(task => task.projectID === project.id && + task.properties.goal?.includes(':maven-compiler-plugin:') && task.properties.goal.endsWith(':compile')); + assert.ok(task); + const refused = await agent.call('lithe_build_execute', { instanceID: entry.id, taskID: task.template, + projectID: 'another-project', modelTaskID: task.id }); + assert.equal(refused.error.code, 'NOT_FOUND'); + const started = await agent.call('lithe_build_execute', { instanceID: entry.id, taskID: task.template, + projectID: project.id, modelTaskID: task.id, userArguments: [] }); + assert.equal(started.ok, undefined, JSON.stringify(started)); + const id = started.operationID.slice('build:'.length); + assert.equal(controller.snapshot().operationID, id, 'Agent and Build output use the same slot'); + await waitForProduct(() => { + const record = workspace.operationSummary(id); + return record && !['preparing', 'running'].includes(record.phase); + }, 'Agent product-owned build completion'); + assert.equal(workspace.operationSummary(id).exitCode, 0, agent.output(id)?.output); + assert.equal(agent.operations().find(operation => operation.operationID === started.operationID).state, 'completed'); + assert.equal(agent.output(id).output, workspace.operation(id).output); + assert.equal(agent.stop('expired-operation'), false); + assert.equal(client.child.exitCode, null, 'the original backend remains workspace-owned'); + }); await report.step('Windows forwards the exact JDT selector and retains only the selected method report', async () => { const project = model.projects.find(project => project.name === 'core'); const result = await workspace.executeTests(instance, { projectID: project.id, selectorKind: 'java.test.fullName', @@ -228,14 +291,14 @@ await withInterrupts(async signal => { 'Surefire owns the detailed assertion message even when Maven uses quiet output'); }); await report.step('workspace cleanup reaps its backend and preserves package bytes', async () => { - await workspace.dispose(); + await controller.dispose(); assert.notEqual(client.child.exitCode, null); assert.deepEqual(bundleManifest(pkg), before); assert.throws(() => workspace.loadModel(instance), /inputs changed/); }); } finally { signal.removeEventListener('abort', stop); - try { if (workspace) await workspace.dispose(); else if (client) await client.close(); } + try { if (controller) await controller.dispose(); else if (workspace) await workspace.dispose(); else if (client) await client.close(); } finally { client?.kill(); if (client) await bounded(client.exited, 'Windows integration backend cleanup'); rmSync(scratch, { recursive: true, force: true }); report.write(); } } });