How to get the semver Major part of a Maven versio

2020-02-25 07:59发布

问题:

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?

回答1:

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>


回答2:

This works on Maven 3.3.9:

${project.artifact.selectedVersion.majorVersion}


回答3:

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.