gnodet-bot commented on code in PR #29663:
URL: https://github.com/apache/camel/pull/29663#discussion_r4543672562


##########
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/PluginHelper.java:
##########
@@ -361,9 +361,25 @@ public static Map<String, Plugin> 
getActivePlugins(CamelJBangMain main, String r
                 final String firstVersion = 
properties.getOrDefault("firstVersion", "").toString();
                 final String gav = properties.getOrDefault("dependency", 
"").toString();
 
+                // auto-migrate old config entries for known plugins that now 
declare appliesTo
+                if (properties.get("appliesTo") == null) {
+                    Optional<PluginType> knownType = 
PluginType.findByName(name);
+                    if (knownType.isPresent() && 
knownType.get().getAppliesTo().length > 0) {
+                        properties.put("appliesTo", 
toJsonArray(knownType.get().getAppliesTo()));
+                        configDirty = true;
+                        main.getOut().printWarn(
+                                ("Plugin '%s' configuration updated with 
'appliesTo' filter. "
+                                 + "Run 'camel plugin add %s' to refresh the 
full configuration.")
+                                        .formatted(name, name));
+                    }
+                }
+
                 // skip plugins that don't match the target command to avoid 
unnecessary downloads
                 if (target != null && !"shell".equals(target) && 
!target.equals(command)) {
-                    continue;
+                    Object appliesToObj = properties.get("appliesTo");
+                    if (!(appliesToObj instanceof Collection<?> appliesToList) 
|| !appliesToList.contains(target)) {
+                        continue;
+                    }
                 }
 

Review Comment:
   **Missing `appliesTo` for community plugins** — the auto-migration block 
(lines 363–375) only populates `appliesTo` for entries that match a 
`PluginType` enum value. For plugins from `known-plugins.json` (e.g. `forage`) 
or added via `--gav`, `PluginType.findByName()` returns empty, so no migration 
happens. Those entries then hit the filter at line 378–382 with `appliesToObj 
== null`, which causes the pattern-match to fail (`null` is not a 
`Collection<?>`) → `continue` → plugin silently dropped.
   
   Forage provides a run customizer and exporter that existing users rely on. 
After this PR, `camel export` with forage in the config silently skips it with 
no message.
   
   Fix: invert the guard — skip filtering when `appliesTo` is absent (treat as 
"always include", preserving the old behaviour), filter only when the field is 
explicitly present:
   
   ```suggestion
                   // skip plugins that don't match the target command to avoid 
unnecessary downloads
                   if (target != null && !"shell".equals(target) && 
!target.equals(command)) {
                       Object appliesToObj = properties.get("appliesTo");
                       // Only filter when appliesTo is explicitly declared; 
absent = legacy, include always
                       if (appliesToObj instanceof Collection<?> appliesToList 
&& !appliesToList.contains(target)) {
                           continue;
                       }
                   }
   ```



##########
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/PluginHelper.java:
##########
@@ -361,9 +361,25 @@ public static Map<String, Plugin> 
getActivePlugins(CamelJBangMain main, String r
                 final String firstVersion = 
properties.getOrDefault("firstVersion", "").toString();
                 final String gav = properties.getOrDefault("dependency", 
"").toString();
 
+                // auto-migrate old config entries for known plugins that now 
declare appliesTo
+                if (properties.get("appliesTo") == null) {
+                    Optional<PluginType> knownType = 
PluginType.findByName(name);
+                    if (knownType.isPresent() && 
knownType.get().getAppliesTo().length > 0) {
+                        properties.put("appliesTo", 
toJsonArray(knownType.get().getAppliesTo()));
+                        configDirty = true;
+                        main.getOut().printWarn(
+                                ("Plugin '%s' configuration updated with 
'appliesTo' filter. "
+                                 + "Run 'camel plugin add %s' to refresh the 
full configuration.")
+                                        .formatted(name, name));

Review Comment:
   **Misleading warning** — by the time this executes, the auto-migration has 
already updated `properties` in memory and set `configDirty = true`. The 
warning tells the user to run `camel plugin add <name>` to refresh the 
configuration, but nothing is needed — the entry is already fixed and will be 
saved at the end of the method.
   
   Also, if an exception is thrown on a later plugin entry before the save 
(line ~406), the warning will have been printed but the config won't be 
persisted. Next run, the warning fires again.
   
   Drop the warning or change it to a debug log: the migration is silent and 
automatic, no user action required.



##########
dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/common/PluginFilteringTest.java:
##########
@@ -0,0 +1,435 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.dsl.jbang.core.common;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import org.aesh.command.Command;
+import org.aesh.command.CommandResult;
+import org.aesh.command.invocation.CommandInvocation;
+import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.commands.CliExportContext;
+import org.apache.camel.dsl.jbang.run.common.StringPrinter;
+import org.apache.camel.dsl.jbang.run.export.ExportContext;
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * Tests that plugins not relevant to the current command are skipped entirely 
— not downloaded, not customized.
+ * <p>
+ * Each test configures cached fake plugins (so no Maven download is needed). 
To detect whether a plugin was loaded or
+ * skipped, some tests use a "broken" plugin entry whose cache points to a 
non-existent jar: if the resolution code
+ * attempts to load the broken plugin, it will fail with a {@link 
CliException}. If the plugin is properly filtered out,
+ * the resolution succeeds.
+ */
+class PluginFilteringTest {
+
+    @TempDir
+    Path tempDir;
+
+    private Path previousHome;
+    private String camelVersion;
+
+    @BeforeEach
+    void setup() {
+        previousHome = CommandLineHelper.getHomeDir();
+        CommandLineHelper.useHomeDir(tempDir.toString());
+        camelVersion = new 
org.apache.camel.catalog.DefaultCamelCatalog().getCatalogVersion();

Review Comment:
   FQCN used without an import. Add `import 
org.apache.camel.catalog.DefaultCamelCatalog;` to the imports and use the 
simple name here.
   
   ```suggestion
           camelVersion = new DefaultCamelCatalog().getCatalogVersion();
   ```



##########
dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/common/PluginFilteringTest.java:
##########
@@ -0,0 +1,435 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.dsl.jbang.core.common;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import org.aesh.command.Command;
+import org.aesh.command.CommandResult;
+import org.aesh.command.invocation.CommandInvocation;
+import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.commands.CliExportContext;
+import org.apache.camel.dsl.jbang.run.common.StringPrinter;
+import org.apache.camel.dsl.jbang.run.export.ExportContext;
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * Tests that plugins not relevant to the current command are skipped entirely 
— not downloaded, not customized.
+ * <p>
+ * Each test configures cached fake plugins (so no Maven download is needed). 
To detect whether a plugin was loaded or
+ * skipped, some tests use a "broken" plugin entry whose cache points to a 
non-existent jar: if the resolution code
+ * attempts to load the broken plugin, it will fail with a {@link 
CliException}. If the plugin is properly filtered out,
+ * the resolution succeeds.
+ */
+class PluginFilteringTest {
+
+    @TempDir
+    Path tempDir;
+
+    private Path previousHome;
+    private String camelVersion;
+
+    @BeforeEach
+    void setup() {
+        previousHome = CommandLineHelper.getHomeDir();
+        CommandLineHelper.useHomeDir(tempDir.toString());
+        camelVersion = new 
org.apache.camel.catalog.DefaultCamelCatalog().getCatalogVersion();
+    }
+
+    @AfterEach
+    void restoreHome() {
+        CommandLineHelper.useHomeDir(previousHome.toString());
+    }
+
+    // ---- Target-based filtering in getActivePlugins ----
+
+    @Test
+    void pluginNotMatchingTargetIsNotLoaded() throws Exception {
+        writeTwoPluginConfig("alpha", "beta");
+
+        CamelJBangMain main = new CamelJBangMain();
+        Map<String, Plugin> plugins = PluginHelper.getActivePlugins(main, 
null, "alpha");
+
+        assertThat(plugins).containsKey("alpha")
+                .doesNotContainKey("beta");
+    }
+
+    @Test
+    void nullTargetLoadsAllPlugins() throws Exception {
+        writeTwoPluginConfig("alpha", "beta");
+
+        CamelJBangMain main = new CamelJBangMain();
+        Map<String, Plugin> plugins = PluginHelper.getActivePlugins(main, 
null, null);
+
+        assertThat(plugins).containsKey("alpha")
+                .containsKey("beta");
+    }
+
+    @Test
+    void shellTargetLoadsAllPlugins() throws Exception {
+        writeTwoPluginConfig("alpha", "beta");
+
+        CamelJBangMain main = new CamelJBangMain();
+        Map<String, Plugin> plugins = PluginHelper.getActivePlugins(main, 
null, "shell");
+
+        assertThat(plugins).containsKey("alpha")
+                .containsKey("beta");
+    }
+
+    // ---- The "run" command should not load unrelated plugins ----
+
+    @Test
+    void runCommandDoesNotLoadUnrelatedPlugin() throws Exception {
+        writeTwoPluginConfig("alpha", "beta");
+
+        CamelJBangMain main = new CamelJBangMain();
+        Map<String, Plugin> plugins = PluginHelper.getActivePlugins(main, 
null, "run");
+
+        assertThat(plugins).doesNotContainKey("alpha")
+                .doesNotContainKey("beta");
+    }
+
+    // ---- The "export" command should not load unrelated plugins ----
+
+    @Test
+    void exportCommandDoesNotLoadUnrelatedPlugin() throws Exception {
+        writeTwoPluginConfig("alpha", "beta");
+
+        CamelJBangMain main = new CamelJBangMain();
+        Map<String, Plugin> plugins = PluginHelper.getActivePlugins(main, 
null, "export");
+
+        assertThat(plugins).doesNotContainKey("alpha")
+                .doesNotContainKey("beta");
+    }
+
+    // ---- A broken unrelated plugin should not break the "run" target ----
+
+    @Test
+    void brokenUnrelatedPluginDoesNotBreakTargetedResolution() throws 
Exception {
+        Path goodJar = tempDir.resolve("fake-good.jar");
+        FakePluginJar.write(goodJar, "good");
+
+        writeConfig(
+                buildEntry("good", camelVersion, goodJar, 
Files.getLastModifiedTime(goodJar).toMillis()),
+                buildBrokenEntry("broken"));
+
+        CamelJBangMain main = new CamelJBangMain();
+
+        // targeting "good" should skip the broken plugin entirely
+        assertThatCode(() -> PluginHelper.getActivePlugins(main, null, "good"))
+                .doesNotThrowAnyException();
+
+        Map<String, Plugin> plugins = PluginHelper.getActivePlugins(main, 
null, "good");
+        assertThat(plugins).containsKey("good")
+                .doesNotContainKey("broken");
+    }
+
+    @Test
+    void brokenUnrelatedPluginBreaksNullTarget() throws Exception {
+        Path goodJar = tempDir.resolve("fake-good.jar");
+        FakePluginJar.write(goodJar, "good");
+
+        writeConfig(
+                buildEntry("good", camelVersion, goodJar, 
Files.getLastModifiedTime(goodJar).toMillis()),
+                buildBrokenEntry("broken"));
+
+        CamelJBangMain main = new CamelJBangMain();
+
+        // null target loads ALL plugins, so the broken one causes a failure
+        assertThatThrownBy(() -> PluginHelper.getActivePlugins(main, null, 
null))
+                .isInstanceOf(CliException.class)
+                .hasMessageContaining("camel-jbang-plugin-broken not found");
+    }
+
+    // ---- appliesTo filtering ----
+
+    @Test
+    void pluginWithAppliesToIsLoadedForMatchingTarget() throws Exception {
+        Path jar = tempDir.resolve("fake-exporter.jar");
+        FakePluginJar.write(jar, "exporter");
+
+        JsonObject entry = buildEntry("exporter", camelVersion, jar, 
Files.getLastModifiedTime(jar).toMillis());
+        entry.put("appliesTo", jsonArray("export"));
+        writeConfig(entry);
+
+        CamelJBangMain main = new CamelJBangMain();
+        Map<String, Plugin> plugins = PluginHelper.getActivePlugins(main, 
null, "export");
+
+        assertThat(plugins).containsKey("exporter");
+    }
+
+    @Test
+    void pluginWithAppliesToIsNotLoadedForNonMatchingTarget() throws Exception 
{
+        Path jar = tempDir.resolve("fake-exporter.jar");
+        FakePluginJar.write(jar, "exporter");
+
+        JsonObject entry = buildEntry("exporter", camelVersion, jar, 
Files.getLastModifiedTime(jar).toMillis());
+        entry.put("appliesTo", jsonArray("export"));
+        writeConfig(entry);
+
+        CamelJBangMain main = new CamelJBangMain();
+        Map<String, Plugin> plugins = PluginHelper.getActivePlugins(main, 
null, "run");
+
+        assertThat(plugins).doesNotContainKey("exporter");
+    }
+
+    @Test
+    void pluginWithAppliesToExportIsLoadedByCliExportContext() throws 
Exception {
+        Path jar = tempDir.resolve("fake-exporter.jar");
+        FakePluginJar.write(jar, "exporter");
+
+        JsonObject entry = buildEntry("exporter", camelVersion, jar, 
Files.getLastModifiedTime(jar).toMillis());
+        entry.put("appliesTo", jsonArray("export"));
+        writeConfig(entry);
+
+        StringPrinter printer = new StringPrinter();
+        CamelJBangMain main = new CamelJBangMain().withPrinter(printer);
+
+        ExportContext context = CliExportContext.create(main, printer, true);
+
+        assertThatCode(() -> context.getPlugins(null))
+                .doesNotThrowAnyException();

Review Comment:
   **Assertion too weak** — `doesNotThrowAnyException()` would pass even if the 
exporter plugin was filtered out and `context.getPlugins(null)` returned an 
empty list. The test name says the plugin *is loaded* by `CliExportContext`, 
but the assertion doesn't verify that. Call `context.getPlugins(null)` and 
assert that the returned `ActivePlugins` contains a non-empty exporters list.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to