Skip to content

Instantly share code, notes, and snippets.

@jabbrwcky
Created November 2, 2012 08:42
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jabbrwcky/3999533 to your computer and use it in GitHub Desktop.
Save jabbrwcky/3999533 to your computer and use it in GitHub Desktop.
Dynamic versions for gradle, git-flow and Java development
/*
* This work is licensed under the Creative Commons Attribution 3.0 Unported License.
*
* To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/
* or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
*/
/*
* Define your version here
*/
version = new Version(project: project, major: 1, minor: 3).toString()
/*
* Print the version
*/
task printVersion {
doFirst {
println "$project.version"
}
}
/**
* <p>
* Implementation of a dynamic version for gradle builds that
* works well in conjunction with the git-flow branching model
* combined with Java development that uses Maven or Ivy
* repositories.
* </p>
* <p>
* Any branch that is not <b>master</b> will automatically have
* <pre>-SNAPSHOT</pre> appended to the produced version string.
* </p>
* <p>
* Feature branches will automatically have inserted the feature
* branch names in their version string to differentiate them
* from the main development branch.
* </p>
* @author Jens Hausherr <a href="https://github.com/jabbrwcky">jabbrwcky@github</a>
*/
class Version {
/* reference to current gradle project */
Project project
/* version number components, major and minor are required,
* the rest is optional.
*/
int major, minor, revision, patch
/**
* Wrapper for git execution.
*
* @param gitArgs list of arguments to the git executable
* @return output of command
*/
def git(List gitArgs) {
def stdout = new ByteArrayOutputStream()
project.exec {
executable = 'git'
args = gitArgs
standardOutput = stdout
}
return stdout
}
String toString() {
def version = "$major.$minor"
/*
* Resolves the git reference.
* Newer git version have the option "--short" which
* makes the regex that strips the "refs/heads/" part
* from the returned branch names unnecessary.
*/
def branch_ = git(["symbolic-ref", /* not supported by current git on jenkins "--short",*/ "-q", "HEAD"])
/* req. if git-symbolic-ref does not support --short */
def bmatcher = branch_ =~ /refs\/heads\/(.+)/
def branch = bmatcher[0][1]
def fbmatch = branch =~ /feature\/(.+)/
if (revision) version += ".$revision"
if (patch) version += ".$patch"
if (fbmatch)
version += "-FB_${fbmatch[0][1]}"
if (branch != 'master') {
version += "-SNAPSHOT"
}
return version
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment