之前写过一篇Gradle 全局配置,不需要每次都修改项目文件
实际公司的项目又有些不同,公司有一个内部的maven仓库, 需要使用个人的账号密码登录,默认的项目里留空的,jenkins build时可以通过配置参数传入,但是本地一般构建不可能像jenkins那么复杂。
每次项目拉下来或者切换分支就要改一下用户名密码的配置非常麻烦。经过测试,把之前的init.gradle又更新了一下,可以支持需要用户名密码的企业仓库。 同时还不影响自己新建的demo项目或者测试github项目
def name = "username"
def pwd = "password" // 通常是encode后的值
def repoConfig = {
all {
ArtifactRepository repo ->
if (repo instanceof MavenArtifactRepository) {
def url = repo.url.toString()
println url
// 删除不需要(实际上内网也限制访问)的仓库,自己新建项目或者测试github项目可能还会使用这些仓库
if (url.contains('repo1.maven.org/maven2') || url.contains('jcenter.bintray.com')
|| url.contains('google.com') || url.contains('plugins.gradle')
|| url.contains('jitpack.io') || url.contains('maven.fabric.io')
) {
println "external repo (${repo.name} : ${repo.url}) removed"
remove repo
}
// 对于内网仓库地址,配置用户名密码(因为项目里默认留空了)
if (url.contains('www.yourinternalrepo.com')) {
if (repo instanceof AuthenticationSupported) {
def cred = repo.getCredentials()
if (cred.username == "null" || cred.username == "") {
println "username is null or empty, updated"
cred.username = name
cred.password = pwd
}
}
}
}
}
// 如果是默认新建的项目或者github的项目,肯定没有内网的配置,还需要自己加一个
maven {
credentials {
username name
password pwd
}
url "yourinternalrepourl"
authentication {
basic(BasicAuthentication)
}
metadataSources {
mavenPom()
artifact()
}
}
}
// 现在新建的项目会在 settings.gradle就配置仓库,这个会比build.gradle先运行,添加下面的code 覆盖settings配置
// for overriding the configuration in settings.gradle
settingsEvaluated { settings ->
settings.pluginManagement {
// Print repositories collection
println "Repositories names: " + repositories.getNames()
// Clear repositories collection
repositories.clear()
// Add my Artifactory mirror
repositories repoConfig
// Print repositories collection
println "Repositories names: " + repositories.getNames()
}
println "gradle version $gradle.gradleVersion"
if ((gradle.gradleVersion <=> "6.8")>=0){
// dependencyResolutionManagement enabled since gradle 6.8
settings.dependencyResolutionManagement {
println "Repositories names: " + repositories.getNames()
repositories.clear()
repositories repoConfig
println "Repositories names: " + repositories.getNames()
}
}
}
allprojects {
buildscript {
repositories repoConfig
}
repositories repoConfig
}