【问题标题】:How to avoid code duplication in gradle configuration code? [duplicate]如何避免 gradle 配置代码中的代码重复? [复制]
【发布时间】:2021-02-23 08:14:22
【问题描述】:

来自我的顶级 gradle.build.kts:

allprojects {  
    repositories {
        maven {
            url = uri(
                "https://" +
                        getGradleProperty("artifactory-url-prefix") +
                        ".artifactory....whatever/foo/"
            )

            credentials() {
                username = getGradleProperty("id")
                password = getGradleProperty("apikey")
            }
        }

        maven {
            url = uri(
                    "https://" +
                            getGradleProperty("artifactory-url-prefix") +
                            ".artifactory....whatever/bar/"
            )

            credentials() {
                username = getGradleProperty("id")
                password = getGradleProperty("apikey")
            }
        }
    }
}

如您所见,存在大量代码重复。我知道如何创建一个帮助方法来构建 URL,但是是否有一种规范/惯用的方式来“执行”credentials() 块只是“一次”?

【问题讨论】:

  • 构建脚本只是 Groovy 代码。您可以使用通常在 Groovy 中使用的内容来避免重复。
  • 是的,对不起。然后 s/Groovy/Kotlin/g
  • artifactUrls 你在追求什么?例如maven { url = uri(...); artifacturls("..../bar", "..../foo"); credentials { ...}}
  • @Roland 看着docs.gradle.org/current/userguide/… ...这在这里可能没有帮助。当 repo 服务器上有额外的 JAR 时使用该功能,这不是我们需要的。

标签: kotlin gradle build.gradle


【解决方案1】:

这对extension function 很有用:

// At top of file

import org.gradle.api.artifacts.repositories.MavenArtifactRepository

// Anywhere in file

fun MavenArtifactRepository.addCredentialsToRepository() {
    credentials {
        username = getGradleProperty("id")
        password = getGradleProperty("apikey")
    }
}

那么你可以这样做:

allprojects {  
    repositories {
        maven {
            url = uri(
                "https://" +
                        getGradleProperty("artifactory-url-prefix") +
                        ".artifactory....whatever/foo/"
            )

            addCredentialsToRepository()
        }

        maven {
            url = uri(
                    "https://" +
                            getGradleProperty("artifactory-url-prefix") +
                            ".artifactory....whatever/bar/"
            )

            addCredentialsToRepository()
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 2014-03-07
    相关资源
    最近更新 更多