应用本地文件中的Gradle插件

4

我有一个Gradle插件,可以启动Java进程。代码存储在项目的buildSrc目录下的名为startAppServerPlugin.gradle的文件中。

插件代码如下:

    repositories.jcenter()
    dependencies {
        localGroovy()
        gradleApi()
    }
}

public class StartAppServer implements Plugin<Project> {
    @Override
    void apply(Project project) {
        project.task('startServer', type: StartServerTask)
    }
}

public class StartServerTask extends DefaultTask {

    String command
    String ready
    String directory = '.'

    StartServerTask(){
        description = "Spawn a new server process in the background."
    }

    @TaskAction
    void spawn(){
        if(!(command && ready)) {
            throw new GradleException("Ensure that mandatory fields command and ready are set.")
        }

        Process process = buildProcess(directory, command)
        waitFor(process)
    }

    private waitFor(Process process) {
        def line
        def reader = new BufferedReader(new InputStreamReader(process.getInputStream()))
        while ((line = reader.readLine()) != null) {
            logger.quiet line
            if (line.contains(ready)) {
                logger.quiet "$command is ready."
                break
            }
        }
    }

    private static Process buildProcess(String directory, String command) {
        def builder = new ProcessBuilder(command.split(' '))
        builder.redirectErrorStream(true)
        builder.directory(new File(directory))
        def process = builder.start()
        process
    }

}

我正在尝试找到一种将此内容导入我的主要build.gradle文件的方法,因为我迄今为止尝试过的所有方法都没有成功。
到目前为止,我已经尝试过这个:
apply from: 'startAppServerPlugin.gradle'
apply plugin: 'fts.gradle.plugins'

但它一直失败。我尝试在网上搜索例子来做我需要做的事情,但到目前为止都没有成功。请问有人能给个提示,我应该如何做呢?

3个回答

2
你正在走上正确的道路。首要任务是使用以下命令导入外部Gradle构建:
import
apply from: 'startAppServerPlugin.gradle'

然后你可以使用以下代码应用插件:

apply plugin: StartAppServer

请参见脚本插件应用二进制插件


1

buildSrc文件夹用作包含的构建,其中代码被编译并放在周围项目的类路径上。在buildSrc中实际使用的build.gradle文件仅用于编译该项目,并且您在其中放置的内容将不可用于其他地方。

您应该将您的类创建为普通的Java / Groovy / Kotlin项目,位于buildSrc下。我不知道是否可以使用默认包,但通常最好使用包名称。

例如,您的StartAppServer插件应在buildSrc/src/main/groovy/my/package/StartAppServer.groovy中。然后,您可以使用apply plugin: my.package.StartAppServer在构建脚本中应用它。

user guide中有很多很好的例子。


0
startAppServerPlugin.gradle 脚本内,您可以调用:
    apply plugin: StartAppServer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接