ewok ewok - 2 months ago 18x
Groovy Question

gradle: how to write a groovy task

I've been trying to work through the user guide. This seems like an incredibly simple thing I want to do, but I just can't figure out how to make it work.

I want to write an external groovy file to define a task, then call that task in

. Here's my

// Apply the groovy plugin to add support for Groovy
apply plugin: 'groovy'

// In this section you declare where to find the dependencies of your project
repositories {
// Use 'jcenter' for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.

// In this section you declare the dependencies for your production and test code
dependencies {
// We use the latest groovy 2.x version for building this library
compile 'org.codehaus.groovy:groovy-all:2.4.7'
compile gradleApi()
compile localGroovy()
// We use the awesome Spock testing and specification framework
testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
testCompile 'junit:junit:4.12'

task myTask (type: my.package.MyTask)

Then, under
I have

package my.package

import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction

class MyTask extends DefaultTask {
String greeting = 'hello from MyTask'

def greet(){
println greeting

I can't even list the tasks:

$ gradle tasks

FAILURE: Build failed with an exception.

* Where:
Build file '/projects/gradle/build.gradle' line: 21

* What went wrong:
A problem occurred evaluating root project 'gradle'.
> Could not get unknown property 'my' for root project 'gradle' of type org.gradle.api.Project.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.


Total time: 3.193 secs

At this point, I have absolutely no idea what's going on or how to do what I want. This seems like the most simple possible example but following the user guide has gotten me nowhere. No matter what I do, I can't get past that exception.

How do I write a groovy file and use that to define a new task in the build file?


You have to place your groovy files under:


Reference: https://docs.gradle.org/current/userguide/custom_tasks.html#N14573


I never tried changing the location of buildSrc but it appears to be an unresolved issue:

(correct it if I'm wrong)