This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch CAMEL-27232-aesh-processor in repository https://gitbox.apache.org/repos/asf/camel.git
commit 58c5394a09f4bdec85e27a6e654a1286c219a373 Author: Claus Ibsen <[email protected]> AuthorDate: Thu Nov 19 10:16:34 2026 +0100 CAMEL-27232: camel-jbang - the aesh metadata of the CLI commands is generated at compile time The aesh annotation processor generates the metadata of the commands of camel-jbang-core, so aesh no longer reads their annotations at run time (which creates a proxy class for each kind of annotation). CommandMetadataRegistry finds the metadata of a command by its class name in the packages of the commands; the registry of the processor is removed from the jar, as it is in a package that depends on the order the processor sees the commands. CommandTree takes the name and aliases of a command from the metadata. aesh looks up the metadata of a command and then of its super classes, so Export (which KubernetesExport extends with options of its own) is read at run time, and CommandTree fails when a command would get the metadata of a super class while it has options of its own. The option fields that the generated code sets are no longer private, and the fields of mixins used from other packages are public. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Claus Ibsen <[email protected]> --- .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 5 +- dsl/camel-jbang/camel-jbang-core/pom.xml | 50 +++++++++ .../dsl/jbang/core/commands/CamelJBangMain.java | 33 +++++- .../dsl/jbang/core/commands/DurationMixin.java | 2 +- .../apache/camel/dsl/jbang/core/commands/Init.java | 14 +-- .../jbang/core/commands/MavenResolverMixin.java | 6 +- .../apache/camel/dsl/jbang/core/commands/Nano.java | 2 +- .../commands/QuarkusExtensionRegistryMixin.java | 2 +- .../jbang/core/commands/QuarkusPlatformMixin.java | 6 +- .../jbang/core/commands/TransformDataWeave.java | 8 +- .../dsl/jbang/core/commands/TransformRoute.java | 2 +- .../core/commands/action/CamelReceiveAction.java | 2 +- .../commands/action/TransformMessageAction.java | 12 +- .../dsl/jbang/core/commands/infra/InfraLog.java | 2 +- .../jbang/core/commands/infra/InfraRestart.java | 2 +- .../dsl/jbang/core/commands/infra/InfraRun.java | 2 +- .../dsl/jbang/core/commands/update/UpdateRun.java | 2 +- .../jbang/core/common/CommandMetadataRegistry.java | 74 ++++++++++++ .../camel/dsl/jbang/core/common/CommandTree.java | 54 +++++++++ .../commands/GeneratedCommandMetadataTest.java | 124 +++++++++++++++++++++ .../kubernetes/KubernetesExportMetadataTest.java | 50 +++++++++ 21 files changed, 418 insertions(+), 36 deletions(-) diff --git a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc index d552fbdb2309..2f39194dcca9 100644 --- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc +++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc @@ -2009,7 +2009,10 @@ A plugin of the Camel CLI (an implementation of `org.apache.camel.dsl.jbang.core built for Camel 4.24: * `Plugin.customize` takes a `CommandTree` instead of a picocli `CommandLine`. A command is added with - `commandLine.addSubcommand("mycommand", new CommandTree(new MyCommand(main)))`. + `commandLine.addSubcommand("mycommand", new CommandTree(main.command(new MyCommand())))`. +* A command that extends `CamelCommand` has a no-arg constructor: the constructor with the `CamelJBangMain` is removed. + The main is set after the command is created, with `main.command(new MyCommand())`, and `getMain()` fails when it was + not set. The CLI generates the aesh metadata of its commands at compile time, which needs the no-arg constructor. * The command classes use the aesh annotations: `@CommandDefinition` instead of `@Command` (the `footer` of the help is an attribute of it; aesh wraps the lines of the footer at 80 columns, except indented lines such as examples, so keep a line of text within 80 columns), `@Option(name = "my-option")` instead of `@Option(names = "--my-option")` (with diff --git a/dsl/camel-jbang/camel-jbang-core/pom.xml b/dsl/camel-jbang/camel-jbang-core/pom.xml index ee1c840f6b31..dc029a2d8767 100644 --- a/dsl/camel-jbang/camel-jbang-core/pom.xml +++ b/dsl/camel-jbang/camel-jbang-core/pom.xml @@ -299,6 +299,56 @@ <build> <plugins> + <!-- the aesh annotation processor generates the metadata of the commands at compile time (see + CommandMetadataRegistry); not for the tests: aesh would also generate it for their sub classes of + commands, which it cannot reach when they are private nested classes --> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <configuration> + <annotationProcessorPaths combine.children="append"> + <path> + <groupId>org.aesh</groupId> + <artifactId>aesh-processor</artifactId> + <version>${aesh-version}</version> + </path> + </annotationProcessorPaths> + <compilerArgs combine.children="append"> + <arg>-AaeshNativeImageDisable=true</arg> + </compilerArgs> + </configuration> + <executions> + <execution> + <id>default-testCompile</id> + <configuration> + <proc>none</proc> + </configuration> + </execution> + </executions> + </plugin> + <!-- the CLI uses its own registry of the generated metadata (CommandMetadataRegistry): the one of the + processor must not be found, as it has the metadata of commands that a plugin extends with options of + its own (and it is in the package of the command the processor happens to see first) --> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-antrun-plugin</artifactId> + <executions> + <execution> + <id>remove-aesh-metadata-registry</id> + <!-- after the recompile execution (process-classes), which runs the processor again --> + <phase>generate-test-sources</phase> + <goals> + <goal>run</goal> + </goals> + <configuration> + <target> + <delete file="${project.build.outputDirectory}/META-INF/aesh/registry"/> + <delete file="${project.build.outputDirectory}/META-INF/services/org.aesh.command.metadata.MetadataRegistry"/> + </target> + </configuration> + </execution> + </executions> + </plugin> <!-- the tests jar has only the helpers the tests of the plugins use too --> <plugin> <artifactId>maven-jar-plugin</artifactId> diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelJBangMain.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelJBangMain.java index e52720674f7d..86a64493efa7 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelJBangMain.java +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelJBangMain.java @@ -75,6 +75,7 @@ import org.apache.camel.dsl.jbang.core.commands.version.VersionSet; import org.apache.camel.dsl.jbang.core.common.CliException; import org.apache.camel.dsl.jbang.core.common.CliExitCode; import org.apache.camel.dsl.jbang.core.common.CommandLineHelper; +import org.apache.camel.dsl.jbang.core.common.CommandMetadataRegistry; import org.apache.camel.dsl.jbang.core.common.CommandTree; import org.apache.camel.dsl.jbang.core.common.EnvironmentHelper; import org.apache.camel.dsl.jbang.core.common.JsonOutput; @@ -102,6 +103,26 @@ public class CamelJBangMain implements Command<CommandInvocation> { private static CommandTree commandLine; + /** + * The aesh metadata of the commands of the CLI, which the aesh annotation processor generates: the packages of all + * the commands of camel-jbang-core. Export is extended by KubernetesExport, which has options of its own (and its + * super classes have no metadata, so they are not looked up). + */ + static final CommandMetadataRegistry COMMAND_METADATA = new CommandMetadataRegistry( + CamelJBangMain.class.getClassLoader(), + Set.of("org.apache.camel.dsl.jbang.core.commands", + "org.apache.camel.dsl.jbang.core.commands.action", + "org.apache.camel.dsl.jbang.core.commands.catalog", + "org.apache.camel.dsl.jbang.core.commands.config", + "org.apache.camel.dsl.jbang.core.commands.infra", + "org.apache.camel.dsl.jbang.core.commands.plugin", + "org.apache.camel.dsl.jbang.core.commands.process", + "org.apache.camel.dsl.jbang.core.commands.update", + "org.apache.camel.dsl.jbang.core.commands.version"), + Set.of("org.apache.camel.dsl.jbang.core.commands.Export", + "org.apache.camel.dsl.jbang.core.commands.ExportBaseCommand", + "org.apache.camel.dsl.jbang.core.commands.CamelCommand")); + @Option(name = "version", shortName = 'V', hasValue = false, description = "Print version information and exit") boolean versionRequested; @@ -125,6 +146,14 @@ public class CamelJBangMain implements Command<CommandInvocation> { main.execute(args); } + /** + * Tells aesh to use the metadata of the commands that is generated at compile time, and not to look through every + * JAR on the class path for other registries of it. + */ + public static void useCommandMetadata() { + MetadataProviderRegistry.useOnly(new InternalCommandMetadataRegistry(), COMMAND_METADATA); + } + public void execute(String... args) { // set pid as system property as logging ${sys:pid} needs to be resolved on windows try { @@ -134,9 +163,7 @@ public class CamelJBangMain implements Command<CommandInvocation> { // ignore } - // the commands of the CLI have no generated aesh metadata, so aesh does not need to look through every JAR on - // the class path for registries of it (a plugin with generated metadata registers its own registry) - MetadataProviderRegistry.useOnly(new InternalCommandMetadataRegistry()); + useCommandMetadata(); args = expandArgumentFiles(args); if (args == null) { diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/DurationMixin.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/DurationMixin.java index ad00dfa9afe3..e0ed6d61f082 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/DurationMixin.java +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/DurationMixin.java @@ -28,7 +28,7 @@ public class DurationMixin { @Option(name = "duration", description = "How long to keep watching or following, in millis or as a duration such as 30s" + " (default: until Enter is pressed)", converter = TimeoutConverter.class) - long duration; + public long duration; /** * How long to keep going, in millis, or 0 to keep going until Enter is pressed. diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Init.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Init.java index 2b04b350ca72..95a487b28439 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Init.java +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Init.java @@ -66,28 +66,28 @@ public class Init extends CamelCommand { private Path filePath; // Defined only for file path completion; the field never used @Argument(description = "Name of integration file (or a github link)", paramLabel = "file") - private String file; + String file; @Option(name = "list", hasValue = false, description = "List available templates") - private boolean list; + boolean list; @Option(name = "dir", aliases = { "directory" }, description = "Directory relative path where the new Camel integration will be saved", defaultValue = ".") - private String directory; + String directory; @Option(name = "clean-dir", aliases = { "clean-directory" }, hasValue = false, description = "Whether to clean directory first (deletes all files in directory)") - private boolean cleanDirectory; + boolean cleanDirectory; @Option(name = "force", hasValue = false, description = "Overwrite a file that exists already (by default the command fails instead)") - private boolean force; + boolean force; @Option(name = "from-kamelet", description = "To be used when extending an existing Kamelet") - private String fromKamelet; + String fromKamelet; @Option(name = "kamelets-version", description = "Apache Camel Kamelets version (auto-detected from classpath if not set)") - private String kameletsVersion; + String kameletsVersion; @Option(name = "repo", aliases = { "repos" }, description = "Additional maven repositories (Use commas to separate multiple repositories)") diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/MavenResolverMixin.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/MavenResolverMixin.java index 6b0950845a7a..3be5a42f7cd2 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/MavenResolverMixin.java +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/MavenResolverMixin.java @@ -31,15 +31,15 @@ import org.apache.camel.tooling.maven.MavenDownloader; public class MavenResolverMixin implements MavenResolverMixinSpec { @Option(name = "download", hasValue = false, description = "Whether to allow automatic downloading JAR dependencies (over the internet)", defaultValue = "true") - boolean download = true; + public boolean download = true; @Option(name = "repo", aliases = { "repos" }, description = "Additional maven repositories for download on-demand (Use commas to separate multiple repositories)") - String repos; + public String repos; @Option(name = "fresh", hasValue = false, description = "Make sure we use fresh (i.e. non-cached) resources", defaultValue = "false") - boolean fresh; + public boolean fresh; // not an option: set by an export through the Java API, else the camel.extra.repos system property is in use String extraRepos; diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Nano.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Nano.java index 6ce011fe6607..54c6861c0957 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Nano.java +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Nano.java @@ -35,7 +35,7 @@ public class Nano extends CamelCommand { private Path filePath; // Defined only for file path completion; the field never used @Argument(required = true, description = "Name of file", paramLabel = "file") - private String file; + String file; @Override public Integer doCall() throws Exception { diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/QuarkusExtensionRegistryMixin.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/QuarkusExtensionRegistryMixin.java index 66482cf5fd27..ffb6799adc10 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/QuarkusExtensionRegistryMixin.java +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/QuarkusExtensionRegistryMixin.java @@ -33,7 +33,7 @@ public class QuarkusExtensionRegistryMixin { + RuntimeType.QUARKUS_EXTENSION_REGISTRY_BASE_URL + " unless camel.jbang.quarkus.platform.url system property is set" + " (the \"/client/platforms\" suffix is removed if present).") - String quarkusExtensionRegistryBaseUri; + public String quarkusExtensionRegistryBaseUri; public static QuarkusExtensionRegistryMixin of(Path localRegistry) { QuarkusExtensionRegistryMixin result = new QuarkusExtensionRegistryMixin(); diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/QuarkusPlatformMixin.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/QuarkusPlatformMixin.java index 2d7a3b16235f..b909fb754f81 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/QuarkusPlatformMixin.java +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/QuarkusPlatformMixin.java @@ -35,17 +35,17 @@ public class QuarkusPlatformMixin extends QuarkusExtensionRegistryMixin implemen @Option(name = "quarkus-group-id", description = "groupId of Quarkus Platform BOM; honored only if --quarkus-version is set", defaultValue = "io.quarkus.platform") - String quarkusGroupId = "io.quarkus.platform"; + public String quarkusGroupId = "io.quarkus.platform"; @Option(name = "quarkus-artifact-id", description = "Deprecated. This value is not used anymore. It is kept only for backwards compatibility and will be removed in Camel 5.x. Camel commands may use either 'quarkus-bom' or 'quarkus-camel-bom' artifactIds depending on the context.", defaultValue = "quarkus-bom") @Deprecated(forRemoval = true, since = "4.21.0") - String quarkusArtifactId = "quarkus-bom"; + public String quarkusArtifactId = "quarkus-bom"; @Option(name = "quarkus-version", description = "version of Quarkus Platform BOM; the default value is looked up in Quarkus Extension Registry") - String quarkusVersion; + public String quarkusVersion; /** * If {@link #quarkusVersion} is set, returns {@link QuarkusPlatformBom} with that version and diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/TransformDataWeave.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/TransformDataWeave.java index a78d2a19b0d9..72399b3c9411 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/TransformDataWeave.java +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/TransformDataWeave.java @@ -36,17 +36,17 @@ import org.apache.camel.dsl.jbang.core.common.CliExitCode; public class TransformDataWeave extends CamelCommand { @Option(name = "input", shortName = 'i', description = "Input .dwl file or directory containing .dwl files") - private String input; + String input; @Option(name = "output", shortName = 'o', description = "Output .ds file or directory (defaults to stdout)") - private String output; + String output; @Option(name = "expression", shortName = 'e', description = "Inline DataWeave expression to convert") - private String expression; + String expression; @Option(name = "include-comments", hasValue = false, description = "Include conversion notes as comments in output", defaultValue = "true") - private boolean includeComments = true; + boolean includeComments = true; @Override public Integer doCall() throws Exception { diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/TransformRoute.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/TransformRoute.java index 4a31f06767d5..e0780981c86b 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/TransformRoute.java +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/TransformRoute.java @@ -71,7 +71,7 @@ public class TransformRoute extends CamelCommand { @Option(name = "output", description = "File or directory to store transformed files. If none provide then output is printed to console. Use clipboard as name to copy content into clipboard.") - private String output; + String output; @Option(name = "format", description = "Output format (${COMPLETION-CANDIDATES}), if only yaml files are provided, the format defaults to xml and vice versa." diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReceiveAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReceiveAction.java index f67b41c57448..7b4be55e062d 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReceiveAction.java +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReceiveAction.java @@ -225,7 +225,7 @@ public class CamelReceiveAction extends ActionBaseCommand { @Option(name = "output", description = "Output format (${COMPLETION-CANDIDATES})", completer = OutputFormatCompletionCandidates.class) - private String output; + String output; @Mixin MavenResolverMixin mavenResolver; diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/TransformMessageAction.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/TransformMessageAction.java index 1b4fb9c99ae1..9c404e80b796 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/TransformMessageAction.java +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/TransformMessageAction.java @@ -63,27 +63,27 @@ public class TransformMessageAction extends ActionWatchCommand { @Option(name = "source", description = "Instead of using external template file then refer to an existing Camel route source with inlined Camel language expression in a route. (use :line-number or :id to refer to the exact location of the EIP to use)") - private String source; + String source; @Option(name = "language", description = "The language to use for message transformation") - private String language; + String language; @Option(name = "component", description = "The component to use for message transformation") - private String component; + String component; @Option(name = "dataformat", description = "The dataformat to use for message transformation") - private String dataformat; + String dataformat; @Option(name = "template", description = "The template to use for message transformation (prefix with file: to refer to loading template from file)") - private String template; + String template; @OptionList(name = "option", valueSeparator = OptionList.NO_SEPARATOR, description = "Option for additional configuration of the used language, component or dataformat (key=value)") List<String> options; @Option(name = "output", description = "File to store output. If none provide then output is printed to console.") - private String output; + String output; @Option(name = "show-exchange-properties", hasValue = false, description = "Show exchange properties from the output message", defaultValue = "false") diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraLog.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraLog.java index 0e3f2899ec18..200c165dc991 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraLog.java +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraLog.java @@ -52,7 +52,7 @@ public class InfraLog extends InfraBaseCommand { @Option(name = "lines", description = "The number of lines from the end of the log to use as starting offset", defaultValue = "50") - private int logLines = 50; + int logLines = 50; @Option(name = "follow", hasValue = false, description = "Keep following and outputting new log lines (press enter to exit)." diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRestart.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRestart.java index 3826d4764d5f..455a6014c290 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRestart.java +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRestart.java @@ -39,7 +39,7 @@ import org.apache.camel.dsl.jbang.run.common.PathUtils; public class InfraRestart extends InfraBaseCommand { @Arguments(paramLabel = "service", required = true, description = "Service name (and optional implementation)") - private List<String> serviceName; + List<String> serviceName; @Option(name = "port", description = "Override the default port for the service") Integer port; diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRun.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRun.java index 9cfd46e150ee..b54c3e38f915 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRun.java +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRun.java @@ -71,7 +71,7 @@ public class InfraRun extends InfraBaseCommand { private static final long STARTUP_POLL_INTERVAL = 200; @Arguments(paramLabel = "service", required = true, description = "Service name") - private List<String> serviceName; + List<String> serviceName; @Option(name = "log", hasValue = false, description = "Log container output to console") boolean logToStdout; diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/update/UpdateRun.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/update/UpdateRun.java index e8d4ee9fba3b..bdbbb10fac17 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/update/UpdateRun.java +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/update/UpdateRun.java @@ -45,7 +45,7 @@ import org.apache.camel.main.download.MavenDependencyDownloader; public class UpdateRun extends CamelCommand { @Mixin - private CamelUpdateMixin updateMixin; + CamelUpdateMixin updateMixin; // the directory of the Maven project to update Path projectDir = Path.of("."); diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/CommandMetadataRegistry.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/CommandMetadataRegistry.java new file mode 100644 index 000000000000..c26829d80f88 --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/CommandMetadataRegistry.java @@ -0,0 +1,74 @@ +/* + * 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.util.Set; + +import org.aesh.command.metadata.CommandMetadataProvider; +import org.aesh.command.metadata.MetadataRegistry; + +/** + * The aesh metadata of the commands in the given packages, which the aesh annotation processor generates at compile + * time: aesh then does not read the annotations of a command at run time, which creates a proxy class for each kind of + * annotation. + * <p> + * The metadata of a command is the class {@code <command class>_AeshMetadata} in the package of the command (a nested + * class {@code Outer$Inner} has {@code Outer_Inner_AeshMetadata}). The registry that the processor generates is not + * used, as it is in the package of the command that the processor happens to see first. + * <p> + * Only the commands of the given packages are looked up: all the commands of the CLI and its plugins are in packages of + * {@code org.apache.camel.dsl.jbang.core.commands}, and a class that is not there costs a search of the whole class + * path. + * <p> + * aesh looks up the metadata of a command class, and then of its super classes, so a command without metadata of its + * own gets the metadata of the command it extends, which misses its own options. A command that a plugin extends with + * options of its own (Export, by KubernetesExport) is therefore excluded: aesh reads the annotations of both at run + * time. CommandTree fails when a command would get the metadata of its super class while it has options of its own. + * + * @param classLoader the class loader of the commands + * @param packages the packages of the commands + * @param excluded the classes to read the annotations of at run time (and their super classes without metadata) + */ +public record CommandMetadataRegistry(ClassLoader classLoader, Set<String> packages, Set<String> excluded) + implements + MetadataRegistry { + + private static final String SUFFIX = "_AeshMetadata"; + + @Override + public CommandMetadataProvider<?> get(String commandClassName) { + int dot = commandClassName.lastIndexOf('.'); + if (dot < 0 || !packages.contains(commandClassName.substring(0, dot)) || excluded.contains(commandClassName)) { + return null; + } + String simpleName = commandClassName.substring(dot + 1); + int nested = simpleName.indexOf('$'); + if (nested >= 0 && nested + 1 < simpleName.length() && Character.isDigit(simpleName.charAt(nested + 1))) { + // an anonymous or local class has no metadata of its own (aesh uses the one of its super class) + return null; + } + String name = commandClassName.substring(0, dot + 1) + simpleName.replace('$', '_') + SUFFIX; + try { + Class<?> type = Class.forName(name, true, classLoader); + return (CommandMetadataProvider<?>) type.getDeclaredConstructor().newInstance(); + } catch (ClassNotFoundException e) { + return null; + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("Cannot create the aesh metadata " + name, e); + } + } +} diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/CommandTree.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/CommandTree.java index 02cbbf342deb..10db1ed18582 100644 --- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/CommandTree.java +++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/CommandTree.java @@ -16,6 +16,7 @@ */ package org.apache.camel.dsl.jbang.core.common; +import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -44,6 +45,14 @@ import org.aesh.command.impl.internal.ProcessedCommand; import org.aesh.command.impl.parser.CommandLineParser; import org.aesh.command.impl.registry.AeshCommandRegistryBuilder; import org.aesh.command.invocation.CommandInvocation; +import org.aesh.command.metadata.CommandMetadataProvider; +import org.aesh.command.metadata.MetadataProviderRegistry; +import org.aesh.command.option.Argument; +import org.aesh.command.option.Arguments; +import org.aesh.command.option.Mixin; +import org.aesh.command.option.Option; +import org.aesh.command.option.OptionGroup; +import org.aesh.command.option.OptionList; import org.aesh.command.registry.CommandRegistry; import org.aesh.complete.AeshCompleteOperation; import org.aesh.terminal.formatting.TerminalString; @@ -327,6 +336,7 @@ public final class CommandTree { * metadata of the commands. */ public ProcessedCommand<?, ?> processedCommand() throws Exception { + checkMetadataOf(getCommand()); return newBuilder().create(getCommand(), getName(), aliasesOf(getCommand())) .getParser().getProcessedCommand(); } @@ -366,6 +376,7 @@ public final class CommandTree { private CommandContainer<CommandInvocation> container( AeshCommandContainerBuilder<CommandInvocation> builder, String[] args) throws Exception { + checkMetadataOf(getCommand()); CommandContainer<CommandInvocation> container = builder.create(getCommand(), getName(), aliases != null ? aliases : aliasesOf(getCommand())); if (helpGroup != null) { @@ -391,15 +402,58 @@ public final class CommandTree { } private static String[] aliasesOf(Object command) { + CommandMetadataProvider<?> provider = providerOf(command); + if (provider != null) { + return provider.commandAliases(); + } CommandDefinition definition = definitionOf(command.getClass()); return definition != null ? definition.aliases() : new String[0]; } private static String nameOf(Object command) { + CommandMetadataProvider<?> provider = providerOf(command); + if (provider != null) { + return provider.commandName(); + } CommandDefinition definition = definitionOf(command.getClass()); return definition != null ? definition.name() : null; } + /** + * Fails when aesh would use the generated metadata of a super class for the command (aesh looks up the class, and + * then its super classes), while the command has options of its own, which aesh would then not know: such as a + * plugin command that extends a command of the CLI. See {@link CommandMetadataRegistry}. + */ + public static void checkMetadataOf(Object command) { + CommandMetadataProvider<?> provider = providerOf(command); + if (provider == null || provider.commandType() == command.getClass()) { + return; + } + for (Class<?> c = command.getClass(); c != null && c != provider.commandType(); c = c.getSuperclass()) { + for (Field field : c.getDeclaredFields()) { + if (field.isAnnotationPresent(Option.class) || field.isAnnotationPresent(OptionList.class) + || field.isAnnotationPresent(OptionGroup.class) || field.isAnnotationPresent(Argument.class) + || field.isAnnotationPresent(Arguments.class) || field.isAnnotationPresent(Mixin.class)) { + throw new IllegalStateException( + "The command " + command.getClass().getName() + " has options of its own (" + field.getName() + + "), but no generated aesh metadata, so aesh would use the metadata of " + + provider.commandType().getName() + + ", which does not have them: add the class of the command it extends to" + + " the excluded classes of the CommandMetadataRegistry"); + } + } + } + } + + /** + * The aesh metadata of the command, generated at compile time (see {@link CommandMetadataRegistry}): reading the + * annotation instead creates a proxy class at run time. + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static CommandMetadataProvider<?> providerOf(Object command) { + return command instanceof Command ? MetadataProviderRegistry.getProvider((Class) command.getClass()) : null; + } + /** * The CommandDefinition of the command class, or of the class it extends (such as a sub class in a test): it is not * an inherited annotation. diff --git a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/GeneratedCommandMetadataTest.java b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/GeneratedCommandMetadataTest.java new file mode 100644 index 000000000000..850b3312ae44 --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/GeneratedCommandMetadataTest.java @@ -0,0 +1,124 @@ +/* + * 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.commands; + +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; + +import org.aesh.command.Command; +import org.aesh.command.internal.InternalCommandMetadataRegistry; +import org.aesh.command.metadata.CommandMetadataProvider; +import org.aesh.command.metadata.MetadataProviderRegistry; +import org.aesh.command.option.Option; +import org.apache.camel.dsl.jbang.core.commands.process.ListProcess; +import org.apache.camel.dsl.jbang.core.common.CommandTree; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * The commands of the CLI have aesh metadata that the aesh annotation processor generates at compile time. + */ +class GeneratedCommandMetadataTest { + + @AfterEach + void resetRegistries() { + MetadataProviderRegistry.reset(); + } + + @Test + void everyCommandHasGeneratedMetadataOfItsOwn() { + Map<Command<?>, String> commands = new IdentityHashMap<>(); + collect(new CamelJBangMain().newCommandLine(), commands); + + List<String> missing = new ArrayList<>(); + for (Command<?> command : commands.keySet()) { + String name = command.getClass().getName(); + if (CamelJBangMain.COMMAND_METADATA.excluded().contains(name)) { + continue; + } + CommandMetadataProvider<?> provider = CamelJBangMain.COMMAND_METADATA.get(name); + if (provider == null || provider.commandType() != command.getClass()) { + // a command in a package that is not in COMMAND_METADATA, or that the processor did not see + missing.add(name); + } + } + + assertThat(commands).hasSizeGreaterThan(150); + assertThat(missing).isEmpty(); + } + + @Test + void theCommandNameComesFromTheMetadata() { + CommandMetadataProvider<?> provider = CamelJBangMain.COMMAND_METADATA.get(ListProcess.class.getName()); + + assertThat(provider.commandName()).isEqualTo("ps"); + } + + @Test + void excludedAnonymousAndOtherClassesHaveNone() { + CommandMetadataProvider<?> anonymous = CamelJBangMain.COMMAND_METADATA.get(new ListProcess() { + }.getClass().getName()); + + assertThat(CamelJBangMain.COMMAND_METADATA.get(Export.class.getName())).isNull(); + assertThat(CamelJBangMain.COMMAND_METADATA.get("org.apache.camel.dsl.jbang.core.commands.kubernetes.Some")) + .isNull(); + assertThat(anonymous).isNull(); + } + + @Test + void aSubClassWithOptionsOfItsOwnAndNoMetadataFails() { + MetadataProviderRegistry.useOnly(new InternalCommandMetadataRegistry(), CamelJBangMain.COMMAND_METADATA); + + assertThatThrownBy(() -> CommandTree.checkMetadataOf(new ListProcessWithOption())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(ListProcessWithOption.class.getName()) + .hasMessageContaining(ListProcess.class.getName()); + // without options of its own, the metadata of the command it extends is right + assertThatCode(() -> CommandTree.checkMetadataOf(new ListProcess() { + })).doesNotThrowAnyException(); + } + + @Test + void aCommandIsCreatedWithoutTheMainAndGetsItAfterwards() { + CamelJBangMain main = new CamelJBangMain(); + + assertThatThrownBy(() -> new ListProcess().getMain()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(ListProcess.class.getName()); + assertThat(main.command(new ListProcess()).getMain()).isSameAs(main); + } + + private static void collect(CommandTree tree, Map<Command<?>, String> commands) { + commands.put(tree.getCommand(), ""); + for (CommandTree sub : tree.getSubcommands().values()) { + collect(sub, commands); + } + } + + // a sub class without generated metadata (the tests are compiled without the processor), as a plugin command + static class ListProcessWithOption extends ListProcess { + + @Option(name = "extra", description = "An option of the sub class") + String extra; + } +} diff --git a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/test/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesExportMetadataTest.java b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/test/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesExportMetadataTest.java new file mode 100644 index 000000000000..816a76c187f1 --- /dev/null +++ b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/test/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesExportMetadataTest.java @@ -0,0 +1,50 @@ +/* + * 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.commands.kubernetes; + +import org.aesh.command.impl.internal.ProcessedCommand; +import org.aesh.command.metadata.MetadataProviderRegistry; +import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain; +import org.apache.camel.dsl.jbang.core.common.CommandTree; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * KubernetesExport extends Export, and has options of its own: aesh must not use the generated metadata of Export for + * it, which does not have them. + */ +class KubernetesExportMetadataTest { + + @AfterEach + void resetRegistries() { + MetadataProviderRegistry.reset(); + } + + @Test + void kubernetesExportHasItsOwnOptionsAndTheOnesOfExport() throws Exception { + CamelJBangMain.useCommandMetadata(); + + ProcessedCommand<?, ?> command = new CommandTree(new CamelJBangMain().command(new KubernetesExport())) + .processedCommand(); + + // an option of KubernetesExport, and one of Export + assertNotNull(command.findLongOptionNoActivatorCheck("image-registry")); + assertNotNull(command.findLongOptionNoActivatorCheck("runtime")); + } +}
