Gradle的buildSrc和buildscript

11
我们有一个包括自定义插件的buildSrc的Gradle构建。这些插件应用其他插件。例如,我们的插件应用com.android.tools.build:gradle。对于注解处理,该库需要在编译期间出现在Gradle的类路径中。所以,将其放在我们主要的build.gradle中可行:
buildscript {
    repositories {
        google()
    }
    dependencies {
       classpath "com.android.tools.build:gradle:$gToolsVersion"
    }
}

然而,这意味着用户要应用此插件必须(1)应用我们的插件并且(2)添加buildscript样板文件。这似乎是不必要的。我们也可以在我们的插件内部添加一个project.buildscript块,但是由于这个bug,这也似乎是不必要的:https://developer.android.com/studio/build/gradle-plugin-3-0-0.html?utm_source=android-studio#known_issues

我将com.android.tools.build:gradle依赖项作为runtime依赖项添加到buildSrc/build.gradle中。这似乎应该可以工作:我认为这告诉Gradle,为了运行我的插件,该库(及其依赖项)需要在类路径上。然而,gradle buildEnvironment(以及我们的构建失败事实)表明情况并非如此。

所以,问题:

  1. buildSrc/build.gradle指定的runtime依赖项和常规build.gradlebuildscript块中指定的classpath依赖项有什么区别?
  2. 我该如何安排事情,以便用户可以从buildSrc应用插件,并且不必也添加buildscript块到他们的build.gradle中?
2个回答

3

我遇到了一个略有不同的问题,并找到了一个可接受的解决方案,也许可以对你的第二个问题有所帮助:我想在buildSrc/build.gradle和根目录build.gradle中应用相同的存储库。

项目根目录下的repositories.gradle文件:

repositories {
    if (project.hasProperty('nexus')) {
        maven {
            url 'http://localhost:8081/repository/JCenter/'
        }
        maven {
            url 'http://localhost:8081/repository/Maven_Google/'
        }
    } else {
        jcenter()
        google()
    }
}

ext {
    androidGradleBuildToolsDependency = 'com.android.tools.build:gradle:3.1.3'
}

buildSrc/build.gradle:

buildscript {
    apply from: '../repositories.gradle'
}

allprojects {
    apply from: '../repositories.gradle'
}

dependencies {
    // androidGradleBuildToolsDependency is defined in repositories.gradle
    implementation androidGradleBuildToolsDependency
}

根目录下的build.gradle文件:

buildscript {
    apply from: 'repositories.gradle'
}

allprojects {
    // this line will also be executed from the build.gradles in subprojects, so the working
    // directory isn't always the same, so we use the absolute path here
    apply from: "${rootProject.projectDir}/repositories.gradle"
}

请注意,通常情况下您不需要在根build.gradlebuildscript块中添加classpath依赖项。在repositories.gradle中添加implementation依赖项似乎会自动应用它。
当使用依赖项提供build.gradle时,我的解决方案可能无法正常工作。

1

在探索一个相关问题时偶然发现了这个。

我已经成功地在几个项目中使用 buildSrc/build.gradle 来定义本应属于根项目构建脚本类路径的依赖项。

您可以在这里看到一个工作示例:https://github.com/episode6/chop/blob/develop/buildSrc/build.gradle

我以前使用 compile 依赖项,但刚刚切换到了感觉更合适且有效的 runtimeClasspath。我认为您的 classpath 依赖项无法正常工作,因为它们将位于 buildSrc 项目的类路径上,但不会被编译或与之并行运行。

如果您决定采用这种方法,您可能会遇到我刚刚遇到的问题,这仅仅是因为这种方法而出现的问题。

当我尝试使用 dokka 插件进行此操作时,我遇到了以下错误:

Could not resolve all files for configuration ':detachedConfiguration1'.
   > Cannot resolve external dependency org.jetbrains.dokka:dokka-fatjar:0.9.17 because no repositories are defined

我通过将jcenter()添加到根项目的buildscript仓库中来解决了这个问题:https://github.com/episode6/chop/blob/develop/build.gradle#L2


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