58

Apologies in advance for my ignorance. I'm very new to gradle.

My is goal is to have some task in my build.gradle file, wherein a file 'version.txt' is created in my project directory whenever I run the gradle terminal command in my project root. This 'version.txt' file needs to contain version metadata of the build, such as:

Version: 1.0 Revision: 1z7g30jFHYjl42L9fh0pqzmsQkF Buildtime: 2016-06-14 07:16:37 EST Application-name: foobarbaz app

(^Revision would be the git commit hash of the HEAD)

I've tried to reuse snippets from the following resources, but to no avail, possibly because these resources are out of date: http://mrhaki.blogspot.com/2015/04/gradle-goodness-use-git-commit-id-in.html http://mrhaki.blogspot.com/2010/10/gradle-goodness-add-incremental-build.html

I'm using gradle version 2.14 (which is the latest version).

Any help and/or insight would be very much appreciated. Thanks!

Chris Covney
  • 819
  • 1
  • 7
  • 11

1 Answers1

93

The example you're referring to is almost correct. With a couple of minor tweaks it works as expected:

import java.text.SimpleDateFormat
import org.ajoberstar.grgit.Grgit

plugins {
    id "org.ajoberstar.grgit" version "1.7.2"
}

version = 1.0

task versionTxt()  {
    doLast {
        new File(projectDir, "version.txt").text = """
Version: $version
Revision: ${grgit.head().abbreviatedId}
Buildtime: ${new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(new Date())}
Application-name: foobarbaz app
"""
    }
}

Run gradle versionTxt to get the desired output.

lepe
  • 24,677
  • 9
  • 99
  • 108
Jk1
  • 11,233
  • 9
  • 54
  • 64
  • This worked as expected. The example I was referring to was indeed almost correct. Thanks again! – Chris Covney Jul 11 '16 at 15:08
  • 2
    Minor tweaks: the leftShift is deprecated and should be replaced with `doLast` inner closure. Also, you can shorten the file creation to a one-liner `new File(filename).text = "blah"` – MarkHu Nov 29 '17 at 01:33
  • 5
    You could use `file(...).text = ...` instead of `new File(...).text = ...`. – deamon Jan 26 '18 at 08:34
  • @deamon but only in newer Gradle versions... e.g. 2.14 (used by ForgeGradle) doesn't have the file method – kb1000 Jan 17 '19 at 15:22
  • I updated the version (to the latest stable) and the code. – lepe Jul 10 '19 at 03:35
  • 2
    In Kotlin based DSL, it would be `file("filePath").writeText("file content")` – AnT Mar 13 '20 at 02:19