task generateGitProperties {
doLast {
try {
def branch = 'git rev-parse --abbrev-ref HEAD'.execute().text.trim()
def revision = 'git rev-list --max-count 1 --timestamp HEAD'.execute().text.trim()
def commitHash = revision.split(' ').last()
def timestamp = revision ? new java.util.Date(java.util.concurrent.TimeUnit.SECONDS.toMillis(revision.split(' ').first() as long)).format("yyyy-MM-dd'T'HH:mm:ssZ") : null
File resourcesDir = new File(project.getBuildDir(), 'resources/main')
File propertiesFile = new File(resourcesDir, 'git.properties')
if(timestamp) {
// The project may not have any resources, so create the directories and file
if(!propertiesFile.exists()) {
resourcesDir.mkdirs()
propertiesFile.createNewFile()
}
propertiesFile.text = """git.branch=${branch}
git.commit.id=${commitHash}
git.commit.time=${timestamp}
"""
} else {
project.logger.error('Unable to generate Git properties file: revision could not be retrieved from Git.')
}
} catch (e) {
project.logger.error('Unable to generate Git properties file.', e)
}
}
}
...
// Generate the Git commit properties file prior to building the artifact
project.tasks.jar.dependsOn('generateGitProperties')