如果检测到不适当的依赖关系,则会失败Gradle构建? [英] Fail a Gradle build if inappropriate dependencies are detected?

查看:97
本文介绍了如果检测到不适当的依赖关系,则会失败Gradle构建?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Gradle,我想确保在大型项目中进行适当的依赖管理,使得模块A不能依赖于模块B(甚至是间接的)。我会如何去做这件事?

Using Gradle, I want to ensure appropriate dependency management in a large project such that module A cannot depend on module B (even indirectly). How would I go about doing this?

推荐答案

您可以分析所有依赖关系,并在发现不合适的情况时抛出异常。下面是一段代码,它对classpath的特定依赖关系进行处理:

You can analyze all dependencies and throw an exception if you find a inappropriate one. Here's a code that does it for a specific dependency on classpath:

apply plugin: 'java'
repositories {
    mavenCentral()
}

// This is just to have some dependencies on the classpath.

dependencies {
    compile 'org.springframework.boot:spring-boot-starter:1.5.1.RELEASE'
    compile "org.webjars:webjars-locator:+"
}

// run this task to analyze all deps

task checkDeps {
    doLast {
        // this closure simply prints a given dependency and throws an exception if slf4j-api is found
        def failIfBad = { dep ->
            println "CHECKING: $dep.module.id.group:$dep.module.id.name"
            if (dep.module.id.name == 'slf4j-api') {
                throw new GradleException("$dep.module.id.group:$dep.module.id.name on classpath!")
            }
        }
        // this is a closure with recursion that calls the above failCheck on all children and their children
        def checkChildren
        checkChildren = { dep ->
            if (dep.children.size() != 0) {
                dep.children.each { child ->
                    failIfBad(child)
                    checkChildren(child)
                }
            }
        }
        // this is how you get all dependencies in the compile scope, iterate on the first level deps and then their children
        configurations.compile.resolvedConfiguration.firstLevelModuleDependencies.each { firstLevelDep ->
            failIfBad(firstLevelDep);
            checkChildren(firstLevelDep);
        }
    }
}

整个代码可能是优化和更复杂的规则将是必要的,但它应该给你你需要开始的。

The whole code could probably be optimized and more sophisticated rules will be necessary, but it should give you what you need to get started.

这篇关于如果检测到不适当的依赖关系,则会失败Gradle构建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆