Gradle/Groovy inheritance

Hi,

I would liked to ask you for help with Groovy/Gradle method inheritance. I have a method defined in root project which lists content of root project directory and I want to be able to use this method in task defined in subproject. Here’s some code: Root project build.gradle:

def list() {
 println("Listing directory ${project.projectDir}")
 exec {
  commandLine 'cmd', '/c', 'ls', '-l'
  workingDir = project.projectDir
 }
}
  task test << {
 println("I'm root project task Test. I was called by ${project.name}")
 list()
}

Root project settings.gradle:

include 'subsys1'
  project(':subsys1').projectDir = file('subsystems/subsys1')

Subproject code build.gradle:

task subTest << {
 println("I'm subTest task from ${project.projectDir}")
 list()
}

Subproject settings.gradle:

include 'system_root'
  project(':system_root').projectDir = file('../..')

Running this command from subproject directory results in:

Execution failed for task ':subTest'.
> Could not find method list() for arguments [] on root project 'subsys1'.

What I want to achieve is running method ‘list’ in directory of subproject that called it. However, it seems to always run agains directory of project, it is defined in (root in this case). Thing is, that I want to “generalize” some methods I use in my script, since they are same (except directory they run in) for all my subsystems. If I think about it in terms of Java, I need to extract my methods like ‘list’ into superclass (gradle root project) and make them more general, so they can be run upon different subproject directories (determined by subproject that actually called it).

If you could bring any light into this for me I would really appreciate it. Thanks in advance.

One solution is to make the directory (or project) a method parameter. Another solution is to “set” the method on all projects (you are really setting a closure here, but it can be called like a method): ‘allprojects { ext.list = { … } }’.