我们在一个中心点使用一些基于Gradle的脚本。这些脚本是通过"apply from:"从大量脚本中包含的。这些基础脚本需要访问相对于脚本的文件。如何找到基础脚本的位置?
一个 build.gradle 的示例:
apply from: "../../gradlebase/base1.gradle"
base1.gradle的示例
println getScriptLocation()
我不确定这是否属于内部接口,但是DefaultScriptHandler
有一个getSourceFile()
方法,而当前实例可以通过buildscript
属性访问,因此您可以使用buildscript.sourceFile
。它是指向当前脚本的File
实例。
println project.buildscript.sourceFile
它提供了当前运行的脚本的完整路径。这是您正在寻找的吗?
build.gradle
中知道base1.gradle
的位置,是吗? - Opalbuildscript {
def root = file('.').toString();
// We have to seek through, since groovy/gradle introduces
// a lot of abstraction that we see in the trace as extra frames.
// Fortunately, the first frame in the build dir is always going
// to be this script.
buildscript.metaClass.__script__ = file(
Thread.currentThread().stackTrace.find { ste ->
ste.fileName?.startsWith root
}.fileName
)
// later, still in buildscript
def libDir = "${buildscript.__script__.parent}/lib"
classpath files("${libDir}/custom-plugin.jar")
}
// This is important to do if you intend to use this path outside of
// buildscript{}, since everything else is pretty asynchronous, and
// they all share the buildscript object.
def __buildscripts__ = buildscript.__script__.parent;
对于不喜欢杂乱无章的人,可以使用精简版:
String r = file('.').toString();
buildscript.metaClass.__script__ = file(Thread.currentThread().stackTrace*.fileName?.find { it.startsWith r })
我的当前解决方法是从调用脚本注入路径。这是丑陋的hack。
调用脚本必须知道基础脚本的位置。在调用之前,我将此路径保存在属性中:
ext.scriptPath = '../../gradlebase'
apply from: "${scriptPath}/base1.gradle"
另一种解决方案是在全局gradle设置中为A.gradle的位置设置一个属性,路径为:{userhome}/.gradle/gradle.properties
这个解决方案尚未使用“apply from”进行测试,但已经在settings.gradle中进行了测试。
Gradle有一个Script.file(String path)函数。我通过以下方式解决了我的问题
def outDir = file("out")
def releaseDir = new File(outDir, "release")
而“out”目录始终位于调用此行的build.gradle旁边。
你可以在相对路径中搜索这些脚本,例如:
if(new File(rootDir,'../path/A.gradle').exists ()){
apply from: '../path/A.gradle'
}
base1.gradle
在base1.gradle
中的完整路径吗?你可以直接从buildscript.sourceFile
获取。或者你需要调用脚本使用的相对路径?如果你知道调用方是一个build.gradle
文件,你可以从buildFile
获取。请问能否在你的问题中添加样例输出? - Aarjav