如何避免Gradle配置代码中的代码重复? [英] How to avoid code duplication in gradle configuration code?
本文介绍了如何避免Gradle配置代码中的代码重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的顶级gradle.build.kts中:
From my toplevel 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,但是是否有一种规范/惯用的方式来执行" URL. credentials()
块只是一次"吗?
As you can see, there is plenty of code duplication. I see how I could create a helper method to do build the URL, but is there a canonical/idiomatic way to "do" the credentials()
block just "once"?
推荐答案
对于扩展功能:
// At top of file
import org.gradle.api.artifacts.repositories.MavenArtifactRepository
// Anywhere in file
fun MavenArtifactRepository.addCredentialsToRepository() {
credentials {
username = getGradleProperty("id")
password = getGradleProperty("apikey")
}
}
然后您可以执行以下操作:
Then you can do:
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()
}
}
}
这篇关于如何避免Gradle配置代码中的代码重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文