How to access a function defined in init.gradle in build script

in my init.gradle I have

import java.text.SimpleDateFormat
...
  // the last thing in init.gradle
def buildTime() {
   def df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") //you can change it
   df.setTimeZone(TimeZone.getTimeZone("UTC"))
   return df.format(new Date())
}

In my build.gradle I want to do something like this:

task showTime() << {
    println buildTime()
}

But I get “Could not find method buildTime() for arguments [] on root project…”

Hello Mike,

the init file is a different context than the build.gradle file. But you can extend a project object (build.gradle delegates to) with a custom property or method (using a closure):

import java.text.SimpleDateFormat
  gradle.allprojects{
 ext.buildTime = {
    def df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
    df.setTimeZone(TimeZone.getTimeZone("UTC"))
    return df.format(new Date())
 }
 }

now you can call buildTime() in your build scripts

1 Like

How cool is this - Thanks!

Published the answer also on Stackverflow: http://goo.gl/zI9J4K

I have multiple methods defined like buildTime(), but I cant figure how to call one from other? It is not possib le use just buldTime() and if I use project.ext.buldTime() it fail with

Error:(74, 0) No signature of method: org.gradle.api.internal.plugins.DefaultExtraPropertiesExtension.buildTime() is applicable for argument types: () values: [] Possible solutions: getClass()