gitflow publish with gradle
Gradle is a very cool build system I like very much. But versioning and artifact upload is not very convenience. How to handle versions, repositories and branches in a quite simple way?
Branching
When using gitflow there is a simple rule: develop and future branches create snapshots, master creates releases.
ext { branch = getBranch() buildType = getBuildType(branch) }
But how to get the branch and build type? That is simple in groovy:
def getBranch() { return "git rev-parse --abbrev-ref HEAD".execute().text.trim() } def getBuildType(branch) { switch (branch) { case ~/^(master|version.*)/: return 'RELEASE' default: return 'SNAPSHOT' } }
Versioning
Following semantic versioning I created the following entries in gradle.properties:
majorVersion=1 minorVersion=0 patchVersion=0
The build.gradle defines the full version (outside of ext):
version = "${majorVersion}.${minorVersion}.${patchVersion}.${buildType}"
The tricky part is: when to change the version on which branch? Using release branches, this would be a good choice as any change will also be merged to master and develop, but: the snapshots will have the wrong version! So you will have to change the version on develop after a release (or its branch) has been taken. When changing the patch version on a hotfix branch, do not merge that change of gradle.properties back to develop!
Publishing
The rest is using the maven-publish plugin. Now it is easy to upload artifacts to a binary repository like artifactory:
apply plugin: 'maven-publish'
Typically repositories have different parts for snapshots and releases. This can be determined automatically depending on the branch in build.gradle:
ext { repo = "${buildType}" == 'SNAPSHOT' ? 'libs-snapshot-local' : 'libs-release-local' } publishing { publications { mavenJava(MavenPublication) { artifactId "${archivesBaseName}" from components.java artifact sourcesJar artifact javadocJar } } repositories { maven { credentials { username "${artifactoryUser}" password "${artifactoryPassword}" } url "${artifactoryUrl}/${repo}" } } } publish.dependsOn build
You only need some more entries in gradle.properties:
artifactoryUrl=http://server:8081/artifactory artifactoryUser=deployer artifactoryPassword=
You should define the password with an option when calling the script which is now also easy to use from local and CI servers:
gradle clean publish -PartifactoryPassword=xyz
Continious builds for master and develop can always publish with this aproch.
PS: the ext parts above have to be combined to one in a real build file.














