我试图在BuildConfig.java中列出我的所有Android Gradle项目的实际依赖项(请参阅How to determine during the build which exactly version of dependency is used)。为此,我使用类似的代码:
def getProjectAndBuildscriptDependencies() {
project.allprojects.collectMany{ proj ->
def configurations = (proj.configurations + proj.buildscript.configurations)
configurations.collectMany { it.allDependencies }
}.findAll { it instanceof ExternalDependency }
}
private def resolveActualDependencyVersion(Dependency dependency) {
def version = dependency.version
boolean mightBeDynamicVersion = version != null && (version.endsWith('+') || version.endsWith(']') || version.endsWith(')') || version.startsWith('latest.'))
if (!mightBeDynamicVersion){
return version
}
def actualVersion = resolveWithAllRepositories{
project.configurations.detachedConfiguration(dependency).resolvedConfiguration.lenientConfiguration
.getFirstLevelModuleDependencies(org.gradle.api.specs.Specs.SATISFIES_ALL).find()?.moduleVersion ?: version
}
return actualVersion
}
这个函数应该收集我拥有的所有依赖项。如果我从某个任务中调用它,它会执行以下操作:
task printCurrentDependencies << {
def current = getProjectAndBuildscriptDependencies()
def currentVersions = [:]
current.each { dependency ->
def actualVersion = resolveActualDependencyVersion(dependency)
currentVersions.put(keyOf(dependency), actualVersion)
}
}
因此currentVersions
包含所有依赖项及其实际版本。
但是当我从defaultConfig
android
部分调用它时,它只给了我一个依赖,这就是Gradle本身。
android {
defaultConfig {
buildConfigField "int", "depsCount", getProjectDependencies().size().toString()
}
}
这种行为上的差异使我感到困惑。为什么会这样,以及如何解决它并实现我真正想要的东西?