Deriving maven artifact version from git branch

前端 未结 7 2038
眼角桃花
眼角桃花 2020-12-12 11:07

We have a workflow requirement that essentially mean that we need to have the artifact version of a module externally defined from the current branch in git.

I.e. if

7条回答
  •  一整个雨季
    2020-12-12 11:39

    From maven-3.5.0 on there is support for ${revision}, ${sha1} and ${changelist} properties within the version tag. This feature may be sufficient for your purpose if, for example you want to incorporate the Git branchname into the version for a CI build job. See Maven CI Friendly Versions

    Basically, in your pom.xml replace the fixed version by:

    ${revision}${changelist}
    

    Set default values for revision and changelist in the project root dir by creating a file .mvn/maven.config containing:

    -Drevision=1.2.3
    -Dchangelist=-SNAPSHOT
    

    Check this file into version control, update it when you bump your project revision.

    In your CI system you can then override the changelist variable using a cleaned-up representation of the Git branch name, eg.

    # sed regex replaces non-(alphanumeric, dot or dash) char sequences with a dash
    BRANCHNAME=$(git rev-parse --abbrev-ref HEAD | sed -E -e 's@[^0-9A-Za-z.-]+@-@g')
    mvn clean install -Dchangelist="-${BRANCHNAME}"
    

    (You may prefer git symbolic-ref --short HEAD for fetching the branchname, YMMV)

    Your artifact built by the CI system for branch feature/branchname will then have a versioned-branch suffix like:

    yourproject-1.2.3-feature-branchname.jar
    

    whilst developers who do not use any overrides will still build it as:

    yourproject-1.2.3-SNAPSHOT.jar
    

提交回复
热议问题