0
votes

Let's say I have:

  • project A containing a build.gradle script which applies another script build-A.gradle containing a bunch of tasks
  • project B where I want to use tasks from build-A.gradle

build-A.gradle looks like this:

task someTask << {
   // do stuff
}

It seems that solution is to create a standalone custom Gradle plugin, so I've created project C for that. It contains copypasted build-A.gradle script and MyPlugin class extending Plugin with apply(Project project) method.

  1. Is there any way to refer to tasks declared in my build-A.gradle from MyPlugin?
  2. If not, how can I "convert" my script into task classes? E.g. how can get hold of the properties like configurations, ant, etc. from the classes?
1

1 Answers

1
votes

Is there any way to refer to tasks declared in my build-A.gradle from MyPlugin?

Since you've created ProjectC you could put build-A.gradle in ProjectC/src/main/resources/build-A.gradle so that it's packed inside the plugin jar and available on the classpath. Then you could do the following in ProjectC/src/main/groovy/.../MyPlugin.groovy

class MyPlugin implements Plugin<Project> {
    void apply(Project project) {
        applyFromClasspath(project, 'build-A.gradle')
    }

    void applyFromClasspath(Project project, String path) {
        InputStream in = getClass().classloader.getResourceAsStream(path)
        if (in == null) throw new RuntimeException("No such resource $path")
        in.withStream { InputStream stream ->
            File localFile = project.file("${project.buildDir}/MyPlugin/$path")
            localFile.parentFile.mkdirs()
            localFile.bytes = stream.bytes
        }
        project.apply(from: localFile)
    }
}

how can get hold of the properties like configurations, ant, etc. from the classes?

These are available from the Project instance (eg project.configurations and project.ant etc). The Project object is implicit in a build.gradle file so configurations will delegate to project.configurations etc. If you'd like the same in a plugin you can use project.with { ... }. Eg:

void apply(Project project) {
    project.with {
        configurations { ... }
        ant.echo(message: 'Hello')
    }
}

@see Object.with(Closure)