我想为Gradle中的现有配置实现扁平化的依赖树。
对于如下所示的新配置可以执行类似的操作:
def static resolveAllDependencies(ResolvedDependency dep, Map<String, ResolvedDependency> deps) {
def key = "${dep.moduleGroup}:${dep.moduleName}".toString()
if (deps.containsKey(key)) {
return
}
deps[key] = dep
if (dep.children.size() > 0) {
dep.children.each { child ->
resolveAllDependencies(child, deps)
}
}
}
dependencies {
compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.9'
}
configurations {
flatRuntime {
defaultDependencies { dependencies ->
def allDeps = [:]
configurations.runtime.resolvedConfiguration.firstLevelModuleDependencies.each { ResolvedDependency d ->
resolveAllDependencies(d, allDeps)
}
allDeps.values().each { ResolvedDependency d ->
dependencies.add(new DefaultExternalModuleDependency(d.getModuleGroup(), d.getModuleName(), d.getModuleVersion()))
}
}
}
}
有了上面的build.gradle
,我们得到了一个新的配置flatRuntime
,该配置具有所有runtime
的依赖项,在第一层上已被扁平化。
runtime - Runtime dependencies for source set 'main' (deprecated, use 'runtimeOnly' instead).
\--- org.apache.httpcomponents:httpclient:4.5.9
+--- org.apache.httpcomponents:httpcore:4.4.11
+--- commons-logging:commons-logging:1.2
\--- commons-codec:commons-codec:1.11
flatRuntime
+--- org.apache.httpcomponents:httpclient:4.5.9
| +--- org.apache.httpcomponents:httpcore:4.4.11
| +--- commons-logging:commons-logging:1.2
| \--- commons-codec:commons-codec:1.11
+--- org.apache.httpcomponents:httpcore:4.4.11
+--- commons-logging:commons-logging:1.2
\--- commons-codec:commons-codec:1.11
在这里,我想为runtime
获得相同的拼合。如果我将flatRuntime
天真地重写为runtime
,肯定会得到StackOverflowError
。解决方案是递归完成的。当然,即使我使用withDependencies
代替defaultDependencies
,结果也一样。
要实现这一点,我想我需要自行解决依赖关系,而无需调用Gradle的标准解析机制。但是...有可能吗?