从本地文件中应用Gradle插件

问题描述 投票:0回答:1

我有以下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'

但是它一直失败。我尝试过在线搜索有关我需要做的事的示例,但到目前为止,我一直没有成功。谁能提供一个提示,提示我应该怎么做?

gradle build.gradle gradle-plugin gradlew
1个回答
0
投票

buildSrc文件夹被视为包含的内部版本,其中代码被编译并放置在周围项目的类路径中。 buildSrc中的实际build.gradle文件仅用于编译该项目,并且您放入其中的内容在其他地方不可用。

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.