Search code examples
javamavenmaven-pluginmaven-mojo

How do you get the maven binary version from within a custom Mojo?


I'm referring to the maven binary version that is returned when you usually run

mvn --version

from the command line which returns an output like the below,

Apache Maven 3.0.4
Maven home: /usr/share/maven
Java version: 1.6.0_45, vendor: Sun Microsystems Inc.
Java home: /home/uvindra/Apps/java6/jdk1.6.0_45/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.11.0-15-generic", arch: "amd64", family: "unix"

Note the maven version 3.0.4. What's best way of accessing this from within a custom Maven Mojo in Java? Is there a property available for this?

I want to run a validation against current maven version that is executing my Mojo, Thanks


Solution

  • Using getApplicationVersion() as mentioned by khmarbaise has been deprecated, getMavenVersion() is the recommended function to be used. You need to include maven-core 3.0.2 or higher as a dependency to use the RuntimeInformation class.

    here is the complete usage example,

    Required pom dependency

    <dependency>
       <groupId>org.apache.maven</groupId>
       <artifactId>maven-core</artifactId>
       <version>3.0.2</version>
    </dependency>
    

    Package import

    import org.apache.maven.rtinfo.RuntimeInformation;
    

    Usage

     /**
     *
     * @component
     */
    private RuntimeInformation runtime;
    
    public void execute() {
         String version = runtime.getMavenVersion();
         getLog().info("Maven Version: " + version);
         ...
    }
    

    @khmarbaise, Thanks for pointing me in the right direction