重构gradle中的Maven块 [英] Refactor maven block in gradle
问题描述
我正在处理一个android项目,并且有许多使用相同凭据的自定义存储库:
I'm working on an android project, and have a number of custom repositories using the same credentials:
repositories {
maven {
url "<url1>"
credentials {
username = "<username>"
password = "<password>"
}
}
maven {
url "<url2>"
credentials {
username = "<username>"
password = "<password>"
}
}
}
是否可以定义方法(块?),这样我可以一次定义用户名和密码,而不必每次都重复?我希望能够做到:
Is there a way to define a method (block?) so that I can define the username and password once and not have to repeat it every time? I'd like to be able to do:
repositories {
customMaven { url "<url1>"}
customMaven { url "<url2>"}
}
很抱歉,如果我在这里使用的术语不正确-gradle语法对我来说还是个谜.
Apologies if I'm using terms incorrectly here - gradle syntax is somewhat of a mystery to me.
推荐答案
@ToYonos提供的第一个答案会很好,但是如果您正在寻找基于配置块的解决方案,则可以使用 RepositoryHandler 中的方法MavenArtifactRepository maven(Action<? super MavenArtifactRepository> action)
a>类(
First answer provided by @ToYonos will work fine, but if you are looking for a solution based on a configuration block, you can use the method MavenArtifactRepository maven(Action<? super MavenArtifactRepository> action)
from RepositoryHandler class (see here), as follows:
// a Closure that builds an Action for configuring a MavenArtifactRepository instance
def customMavenRepo = { url ->
return new Action<MavenArtifactRepository>() {
void execute(MavenArtifactRepository repo) {
repo.setUrl(url)
repo.credentials(new Action<PasswordCredentials>() {
void execute(PasswordCredentials credentials) {
credentials.setUsername("<username>")
credentials.setPassword("<password>")
}
});
}
};
}
// usage
repositories {
jcenter()
maven customMavenRepo("http://company.com/repo1")
maven customMavenRepo("http://company.com/repo2")
maven customMavenRepo("http://company.com/repo3")
}
编辑,来自以下注释:解决方案将关闭,如下所示.我认为这里需要使用curry
方法(请参见强制关闭),但也许还有其他方法可以简化...
EDIT from comments below: solution will Closure would look as follow. I think the use of curry
method (see Currying closure) is needed here, but maybe there are other ways to simplify...
// one closure with URL as parameter
ext.myCustomMavenClosure = { pUrl ->
url pUrl
credentials {
username = "<username>"
password = "<password>"
}
}
// helper function to return a "curried" closure
Closure myCustomMaven (url){
return myCustomMavenClosure.curry(url)
}
repositories {
// use closure directly
maven myCustomMavenClosure.curry ("http://mycompany.com/repo1")
// or use helper method
maven myCustomMaven("http://mycompany.com/repo2")
}
这篇关于重构gradle中的Maven块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!