Invoking master's build task from a subproject

I have a multiproject build where I want to refer from a subproject to a master task, which will then invoke the task on all subprojects.

The subproject build script has something like:

task compileAll {
  dependsOn ':build'
}

mySubProjectTask {
  dependsOn compileAll
}

but this doesn’t work. It runs ‘:buildscript’ in master instead of the equivalent of ‘cd master; ./gradlew build’

How do I refer to the same task in the master project that would invoke the ‘build’ task on all subprojects in this way, as if I was in master?

It’s easy to refer to another subproject’s task, with ‘:SubProject:taskName’, but I can’t do ‘:build’ or ‘::build’, both run the wrong task.

Thanks.

This almost works, but the project dependency order doesn’t work correctly:

task compileAll {
  project.rootProject.subprojects.each { p ->
    if (p.tasks.findByPath('build')) {
      dependsOn p.tasks.findByPath('build')
    }
  }
}

i.e. if project A dependsOn B, using this method doesn’t run :B:build before :A:Build