首页 > 解决方案 > 从本地文件应用 Gradle 插件

问题描述

我有以下 gradle 插件来完成启动 java 进程的工作。代码startAppServerPlugin.gradle位于项目 buildSrc 目录下的一个文件中。

该插件的代码如下所示:

    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'

但它一直失败。我试过在网上搜索做我需要做的事情的例子,但到目前为止我一直没有成功。任何人都可以提供关于我应该如何做的提示吗?

标签: gradlebuild.gradlegradle-plugingradlew

解决方案


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

您应该在 buildSrc 下将您的类创建为普通的 Java/Groovy/Kotlin 项目。我不知道你是否可以使用默认包,但通常最好的做法是有一个包名。

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

用户指南中有很多很好的例子。


推荐阅读