查找配置的所有子配置

时间:2014-10-30 14:02:40

标签: gradle

使用beforeResolve添加依赖关系时,它仅添加到指定的配置,但不会添加到配置为超级配置的配置。

即,在使用java插件时,您拥有默认配置compileruntimetestCompiletestRuntime。配置继承如下:

  • compile< - runtime
  • testCompile< - testRuntime
  • runtime< - testRuntime

如果我使用普通依赖关系块向'com.example:foo:1.0'配置添加依赖关系compile,它将继承到runtimetestCompiletestRuntime配置。如果我使用beforeResolve块添加相同的依赖项,它永远不会继承到任何配置。

我有办法确定扩展给定配置的配置吗?我似乎找到的只是Configuration#extendsFrom(Configuration)方法,它允许在配置中添加超级配置。


解决方案

似乎我在寻找子配置,而不是超级配置。由于该数据不易获得,我根据自己的需要调整了可接受的答案。基本上,对于项目中的每个配置,获取其所有超级配置。如果我们想要的配置是配置的超级配置之一,则该配置是子配置。

/**
 * Get all Configurations that extend the provided configuration, including
 * the one that is specified.
 * 
 * @param config the configuration to get all sub configurations for
 * @param p the project to get the configurations from
 * 
 * @return set of all unique sub configurations of the provided configuration
 */
private static Set<String> getSubConfigs(final Configuration config, final Project p)
{
    final Set<String> subConfs = new HashSet<>()
    subConfs.add(config.name)
    p.configurations.each {
        if (getSuperConfigs(it, p).contains(config.name))
        {
        subConfs.add(it.name)
        }
    }
    return subConfs
}

/**
 * Get all super configurations for a given Configuration.
 * 
 * @param config the configuration to get all super configurations for
 * @param p the project to get the configurations from
 * 
 * @return set of all unique super configurations of the provided configuration
 */
private static Set<String> getSuperConfigs(final Configuration config, final Project p) 
{
    final Set<String> superConfs = new HashSet<>()
    superConfs.add(config.name)
    config.extendsFrom.each {
        superConfs.addAll(getSuperConfigs(p.configurations[it.name], p))
    }
    return superConfs
}

1 个答案:

答案 0 :(得分:-1)

Configuration#getExtendsFrom返回给定配置的超级配置集。您可以打印给定配置的超级配置列表

task printConfig {
    configurations.testRuntime.extendsFrom.each { println it.name }
}

但是,这并没有列出超级配置的超级配置(即递归列表)。但是围绕这个的一些代码将给出完整的列表

ext.configList = new HashMap<String, String>()
def getSuperConfigs(config) {
    config.extendsFrom.each {
        configList.put(it.name, '1')
        getSuperConfigs(configurations[it.name])
    }
}
task printConfig {
    getSuperConfigs(configurations['testRuntime'])
    configList.each {
        println it.key
    }
}