有没有办法从gradle依赖关系中提取项目URL和最新可用版本?

时间:2019-09-19 22:30:22

标签: json gradle android-gradle-plugin build.gradle

我正在尝试从build.gradle中提取有关gradle依赖关系的信息,并将其打包到JSON字符串中以供其他地方使用。

我正在尝试做的一个小例子:

来自app/build.gradle

android {
    ...
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.0.0'
}

我想获取(以JSON格式)这样的内容:

...
{
    "name": "androidx.appcompat:appcompat",
    "source": "google",
    "installed": {
        "version": "1.0.0"
    },
    "latest": {
        "version": "1.1.0"
    }
    "projectUrl": "https://dl.google.com/dl/android/maven2/index.html",
    "license": "Apache 2.0 <http://www.apache.org/licenses/LICENSE-2.0>"
}
...

到目前为止,我已经设法获得了一半的信息,

configurations {
    myConfig.extendsFrom implementation
}

task printSolvedDepsTreeInJson {
    doLast {
        def jsonOutput = "["
        configurations.myConfig.resolvedConfiguration.firstLevelModuleDependencies.each { dep ->
            def addToJson
            addToJson = { resolvedDep ->
                jsonOutput += "\n{\n"
                jsonOutput += "\t\"name\": \"${resolvedDep.module.id.group}:${resolvedDep.module.id.name}\",\n"
                if (resolvedDep.module.id.group.contains("android") || resolvedDep.module.id.group.contains("google")) {
                    jsonOutput += "\t\"source\": \"google\",\n"
                } else {
                    jsonOutput += "\t\"source\": \"jcenter\",\n"
                }
                jsonOutput += "\t\"installed\": {\n\t\t\"version\": \"${resolvedDep.module.id.version}\"\n\t},\n"
                jsonOutput += "},"
            }
            addToJson(dep)
        }
        if (jsonOutput[-1] == ',') {
            jsonOutput = jsonOutput[0..-2]
        }
        jsonOutput += "\n]"
        println jsonOutput
    }
}

但是我找不到有关如何找到gradle依赖关系的最新版本的任何文档(并且我知道此信息在某处,因为Android Studio会向您提供有关新版本的lint消息)。我还想添加一个到依赖项的URL(例如,如果是开源的github链接),由于我发现了这个gradle plugin that can generate a JSON report which lists the website the project is from,因此我认为这应该也是可能的。

有什么办法吗?

1 个答案:

答案 0 :(得分:0)

为什么不依靠您提到的确切插件(Ben Manes' Gradle Versions Plugin)为您工作?您可以依靠dependencyUpdates任务,然后解析输出以在自己的报告中使用。

否则,您可以看看该插件的实现方式。我相信它重复了配置,但是有一个依赖关系解析规则,该规则用动态声明latest.release代替了该版本(请参阅该here的文档),然后让Gradle对其进行解析。