Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function from init.gradle in build script

Tags:

gradle

in my init.gradle I have

...
// 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..."

Thx in advance!

like image 230
Mike Mitterer Avatar asked Oct 08 '13 16:10

Mike Mitterer


People also ask

How do I run a Gradle init task?

Right click on "init" and select "Run Gradle Tasks". Then in the project explorer, right click on your project and select "Gradle", then select "Refresh Gradle Project". And voila! You must be able to see your build.

What does Gradle init do?

Gradle comes with a built-in task, called init , that initializes a new Gradle project in an empty folder. The init task uses the (also built-in) wrapper task to create a Gradle wrapper script, gradlew . The first step is to create a folder for the new project and change directory into it.

How do I run a Gradle task from the command line?

You can use -x option or --exclude-task switch to exclude task from task graph. But it's good idea to provide runnable example. gradle taskA -x taskB will run both the tasks.


1 Answers

Got the answer from Gradle-Support. http://goo.gl/5uYInH

Maybe it helps someone else...

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):

init.gradle

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())
   }    
}

build.gradle

task showBuildTime() << {
   println buildTime()
}
like image 67
Mike Mitterer Avatar answered Oct 01 '22 08:10

Mike Mitterer