How to get the semver Major part of a Maven version?

Tag: maven Author: thunder427 Date: 2011-03-08

Is it possible to get the major version (<Major>.<Minor>.<Patch>) of the project.version?

For example if my version is 1.3.4, I'd like to get 1 to later use it in a configuration of the same pom.xml

Something like:

<configuration>
  <name>project_name.${project.version:major}</name>
</configuration>

If not, what are the alternatives?

It is worth noting that Maven does not use the SemVer.org versioning specification. It instead uses it's own convention which is very similar. Read about it here (under the 3.3.1 "Project Versions" section)... sonatype.com/books/mvnref-book/reference/…

Best Answer

Found it. The build-helper-maven-plugin has the ability to parse-out the components of the version.

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>1.5</version>
        <executions>
          <execution>
            <phase>initialize</phase>
            <id>parse-version</id>
            <goals>
              <goal>parse-version</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
        <version>1.1</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>run</goal>
            </goals>
            <configuration>
              <tasks>
                <echo>[version] ${project.version}</echo>
                <echo>[majorVersion] ${parsedVersion.majorVersion}</echo>
              </tasks>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

comments:

+1 - I have been using Maven for years and yet did not know about this!

Other Answer1

Versions don't necessarily come in the structure you describe.

Maven has conventions for trailing numbers, but you don't have to use them.

If you have a convention that you like that you want to disassemble, you can write your own maven plugin that sets several properties to the several pieces as you define them.

comments:

According to the Maven reference documentation from Sonatype there is a convention (which you are free to violate).