Wednesday, May 6, 2015

How to create `git.properties` file for Spring Boot Actuator's `info` endpoint in Gradle

In Gradle, to create `git.properties` file for Spring Boot Actuator's `info` endpoint,

add the following to `build.gradle`:

import org.ajoberstar.grgit.operation.OpenOp

buildscript {
    repositories {
        mavenLocal()
        jcenter()
    }

    dependencies {
        classpath("org.ajoberstar:gradle-git:1.1.0")
    }
}

task generateGitProperties {
    doLast {
        def openOp = new OpenOp()
        openOp.setDir('.')

        def repo = openOp.call()
        def headCommit = repo.head()
        ext.gitBranch = repo.branch.current.name
        ext.gitCommitId = headCommit.abbreviatedId
        ext.gitCommitTime = new Date(headCommit.time * 1000L).format("yyyy-MM-dd'T'HH:mm:ssZ")
       
        File resourcesMainDir = new File(project.buildDir, 'resources/main')
        File gitPropertiesFile = new File(resourcesMainDir, 'git.properties')
        gitPropertiesFile.text = """git.branch=${gitBranch}
git.commit.id=${gitCommitId}
git.commit.time=${gitCommitTime}
"""
    }
}

project.tasks.jar.dependsOn('generateGitProperties')

References:
https://github.com/ajoberstar/gradle-git/wiki/Grgit%20Usage
https://jdpgrailsdev.github.io/blog/2014/10/14/spring_boot_gradle_git_info.html

No comments:

Post a Comment