Search code examples
javamavengroovygmavenplus

GMavenPlus - How to get Maven property value in script executed by gmavenplus-plugin


My pom.xml looks like this:

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>mygroup</groupId>
<artifactId>myartefact</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
    <my.property>defaultValue</my.property>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.gmavenplus</groupId>
            <artifactId>gmavenplus-plugin</artifactId>
            <version>1.5</version>
            <executions>
                <execution>
                    <phase>validate</phase>
                    <goals>
                        <goal>execute</goal>
                    </goals>
                    <configuration>
                        <scripts>
                            <script>file:///${basedir}/script.groovy</script>
                        </scripts>
                    </configuration>
                </execution>
            </executions>
            <dependencies>
                <dependency>
                    <groupId>org.codehaus.groovy</groupId>
                    <artifactId>groovy-all</artifactId>
                    <version>2.4.7</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>
</project>

and script.groovy looks like this:

def value = project.properties['my.property']
log.info "my.property value = $value"

When i run mvn validate -Dmy.property=cmdValue script will write

[INFO] my.property value = defaultValue

It will write "defaultValue", but i definitively need overridden value "cmdValue".


Solution

  • I have solution, that works for me, but is little bit disappointing. Write script like this:

    def value = getPropertyValue('my.property')
    log.info "my.property value = $value"
    
    String getPropertyValue(String name) {
        def value = session.userProperties[name]
        if (value != null) return value //property was defined from command line e.g.: -DpropertyName=value
        return project.properties[name]
    }
    

    session.userProperties('my.property') will return value defined in command line. Unfortunately it will return null, when it is not defined on command line. In this case I use value from project.properties['my.property'].

    I wonder, if there is some better solution?

    It is sad, that in examples from GMavenPlus plugin is project.properties['my.property'], but it doesn't work well :(