How can I store the git revision for use in the project?

Essentially I’m looking for an equivalent of the Maven Build Number plugin (http://mojo.codehaus.org/buildnumber-maven-plugin/) – in our Maven projects, we use the Git revision and store it in the jar manifest as “Implementation-Build” as well as include it in some filtered resources.

It is easy enough to get the Git revision via the Exec command:

task gitRevision(type: Exec) {
    commandLine "git", "log", "-n", "1", "--format='%h'"
}

But I’m less clear on how to actually store this in a property that is available to other tasks (e.g. the jar task)

The gradle-about plugin is a nice approach for injecting build details into the artifact. Unfortunately I had to migrate away due to environmental issues, as our QA team is in the habit of generating their deployment artifacts in Eclipse and don’t have git on the path. Ideally local issues would be negated by instead deploying through the CI server after specifying the target environment via a web console (an improvement I’m working on).

The alternative was to adopt the git-state plugin which uses JGit to avoid environmental issues. The property gitHeadHash is available after the plugin is applied, making it easy to add into the jar manifest. It also adds a convenient task checkGitState which can be used as a task’s pre-condition via a dependsOn relationship. If using the task, by its disabled unless git.requireClean is explicitly set to true.

A simple approach if you always generate your artifact and deploy through your CI server is to obtain the git hash from the provided environmental variable. In Jenkins this may require using a parameterized build if the artifact is create late within a build pipeline.

Thanks Benjamin! I ended up doing something simpler:

task buildInfo {
    def cmd = "git rev-parse --short HEAD"
    def proc = cmd.execute()
    ext.revision = proc.text.trim()
    ext.timestamp = (int)(new Date().getTime()/1000)
}

Then I can just add this task as a dependency where needed and access the build information via the task properties.

You can use this: https://gist.github.com/JonasGroeger/7620911

If you don’t have git in the PATH, then you can use this: https://gist.github.com/JonasGroeger/7620911

Or you can use the gradle-git plugin and do something like

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.ajoberstar:gradle-git:0.8.0'
    }
}
  import org.ajoberstar.grgit.*
  task printHeadHash << {
  def grgit=Grgit.open(project.file('.'))
  println grgit.head().id
}