如何从初始化脚本中应用Gradle版本插件?

Lau*_*ves 4 gradle

我正在尝试进行设置,以便可以使用Gradle版本插件,而不必将其添加到我的所有build.gradle文件中。

基于对相关问题的回答,我尝试创建一个文件~/.gradle/init.d/50-ben-manes-versions.gradle

initscript {
    repositories {
       jcenter()
    }

    dependencies {
        classpath 'com.github.ben-manes:gradle-versions-plugin:0.17.0'
    }
}

allprojects {
    apply plugin: com.github.ben-manes.versions
}
Run Code Online (Sandbox Code Playgroud)

如果然后尝试./gradlew dependencyUpdates在回购中调用,则会得到:

FAILURE: Build failed with an exception.

* Where:
Initialization script '~/.gradle/init.d/50-ben-manes-versions.gradle' line: 13

* What went wrong:
Could not get unknown property 'com' for root project 'project-name' of type org.gradle.api.Project.
Run Code Online (Sandbox Code Playgroud)

这个答案说不要在插件名称周围使用引号,但是由于这样不起作用,我尝试添加引号(即:)apply plugin: 'com.github.ben-manes.versions'。这样我得到:

FAILURE: Build failed with an exception.

* Where:
Initialization script '~/.gradle/init.d/50-ben-manes-versions.gradle' line: 13

* What went wrong:
Plugin with id 'com.github.ben-manes.versions' not found.
Run Code Online (Sandbox Code Playgroud)

有什么方法可以从初始化脚本中应用Gradle版本插件吗?

顺便说一下,我正在使用Gradle 4.3.1。

mko*_*bit 5

可以通过几种不同的方式来应用插件。在问题的引用答案中,它们按类型应用。您也可以通过插件ID(即)进行申请String

在通过ID进行申请的第二次尝试中,您做对了,但是构建错误出在以下方面:

找不到ID为“ com.github.ben-manes.versions”的插件。

这里的问题是,您当前无法通过init脚本(#gradle / 1322)通过ID应用插件

解决方案是改为按类型应用插件。

幸运的是,该插件是开源的,因此发现插件的类型相对简单。插件ID为com.github.ben-manes.versions,将我们引至META-INF/gradle-plugins/com.github.ben-manes.versions.properties文件。该文件包含一行implementation-class=com.github.benmanes.gradle.versions.VersionsPlugin,告诉我们该插件的类型为 com.github.benmanes.gradle.versions.VersionsPlugin。也可以通过将插件应用于构建(而不是通过init脚本)并检查项目中的pluginsor或pluginManager列出插件类型来确定。

要进行修复,请更改此行:

apply plugin: 'com.github.ben-manes.versions'
Run Code Online (Sandbox Code Playgroud)

至:

apply plugin: com.github.benmanes.gradle.versions.VersionsPlugin
Run Code Online (Sandbox Code Playgroud)

因此,完整的有效初始化脚本为:

initscript {                                                                    
    repositories {                                                              
       jcenter()                                                                
    }                                                                           

    dependencies {                                                              
        classpath 'com.github.ben-manes:gradle-versions-plugin:0.17.0'          
    }                                                                           
}                                                                               


allprojects {                                                                   
    apply plugin: com.github.benmanes.gradle.versions.VersionsPlugin            
}                                                                               
Run Code Online (Sandbox Code Playgroud)