get mojo parameters in maven plugin

限于喜欢 提交于 2019-12-24 01:18:57

问题


Is there any way to access a plugins properties within the execution method?

I have a base mojo that has some properties, like so:

@Parameter(defaultValue = "DEV", property = "dbEnvironment", required = true)
protected Environment dbEnvironment;

@Parameter(defaultValue = "true", property = "validate")
protected boolean validate;

The child mojo then adds some additional properties. I'd like to be able to read all of these properties, to validate them, but it's not obvious how to do so. When I run it, with debug, I see this:

[DEBUG] Configuring mojo 'com.company.tools:something-maven-plugin:0.2.11-SNAPSHOT:export-job' with basic configurator -->
[DEBUG]   (f) dbEnvironment = DEV
[DEBUG]   (f) jobName = scrape_extract
[DEBUG]   (f) project = MavenProject: com.company.tools:something-maven-plugin-it:1.0-SNAPSHOT @ /Users/selliott/intellij-workspace/tools-something-maven-plugin/something-maven-plugin/src/it/simple-it/pom.xml
[DEBUG]   (f) session = org.apache.maven.execution.MavenSession@3fd2322d
[DEBUG]   (f) validate = true
[DEBUG] -- end configuration --

So, it looks like those props are somewhere, but where? I've tried getting them from the session, session.settings, session.request to no avail.


回答1:


Ok, after much debugging, I was able to figure it out based on how AbstractConfigurationConverter works, specifically the fromExpression method.

To get the properties you need the following added to your mojo:

@Parameter(defaultValue = "${session}")
protected MavenSession session;

@Parameter(defaultValue = "${mojoExecution}")
protected MojoExecution mojoExecution;

From there, you can now create an evaluator and configuration (maybe you can inject them in directly, I'm not sure), and with that you can do this:

    PluginParameterExpressionEvaluator expressionEvaluator = new PluginParameterExpressionEvaluator(session, mojoExecution);
    PlexusConfiguration pomConfiguration = new XmlPlexusConfiguration(mojoExecution.getConfiguration());

    for (PlexusConfiguration plexusConfiguration : pomConfiguration.getChildren()) {
        String value = plexusConfiguration.getValue();
        String defaultValue = plexusConfiguration.getAttribute("default-value");
        try {
            String evaluated = defaultIfNull(expressionEvaluator.evaluate(defaultIfBlank(value, defaultValue)), "").toString();
            System.out.println(plexusConfiguration.getName() + " -> " + defaultIfBlank(evaluated, defaultValue));
        } catch (ExpressionEvaluationException e) {
            e.printStackTrace();
        }
    }


来源:https://stackoverflow.com/questions/50823602/get-mojo-parameters-in-maven-plugin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!