Last active
June 12, 2025 13:19
-
-
Save dongfg/30997b060068e962b40521d3921bc427 to your computer and use it in GitHub Desktop.
Gradle国内全局加速, 把这个文件放到~/.gradle目录下既可, tks https://gist.github.com/wuseal/76506684c63c5399150d9fd671cbc89b
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@file:Suppress("UnstableApiUsage") | |
object MavenMirror { | |
const val CENTRAL = "https://mirrors.huaweicloud.com/repository/maven/" | |
const val GOOGLE = "https://maven.aliyun.com/repository/google/" | |
const val GRADLE_PLUGIN = "https://maven.aliyun.com/repository/gradle-plugin/" | |
} | |
val mirrorMapping = listOf( | |
"https://repo1.maven.org/maven2" to MavenMirror.CENTRAL, | |
"https://repo.maven.apache.org/maven2/" to MavenMirror.CENTRAL, | |
"https://dl.google.com/dl/android/maven2/" to MavenMirror.GOOGLE, | |
"https://plugins.gradle.org/m2" to MavenMirror.GRADLE_PLUGIN | |
) | |
val isVerbose = System.getenv("MIRROR_DEBUG") == "true" | |
fun RepositoryHandler.applyMirrors() { | |
all { | |
if (this is MavenArtifactRepository) { | |
val name = this.name | |
val url = this.url.toString() | |
val matched = mirrorMapping.find { (prefix, _) -> url.startsWith(prefix) }?.second | |
matched?.let(::setUrl) | |
if (isVerbose) { | |
println("[Mirror] $name $url, ${matched ?: "NO MIRROR"}") | |
} | |
} | |
} | |
} | |
fun RepositoryHandler.useMirrors() { | |
clear() | |
maven { url = uri(MavenMirror.CENTRAL) } | |
maven { url = uri(MavenMirror.GOOGLE) } | |
maven { url = uri(MavenMirror.GRADLE_PLUGIN) } | |
mavenCentral() | |
google() | |
gradlePluginPortal() | |
} | |
// 清空项目中 pluginManagement/dependencyResolutionManagement 使用镜像 | |
settingsEvaluated { | |
if (isVerbose) { | |
println("[Mirror] settingsEvaluated => use mirror repository") | |
} | |
pluginManagement.repositories.useMirrors() | |
dependencyResolutionManagement.repositories.useMirrors() | |
} | |
// 替换项目中 repository 为镜像 | |
allprojects { | |
repositories.applyMirrors() | |
buildscript.repositories.applyMirrors() | |
} |
optimized. tested on gradle 8.14.2
- MIRROR_DEBUG=true to print debug log
测试时发现阿里云偶尔会出现下载失败的问题, 切换到华为云, 同时删除 jcenter (gradle 已废弃)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Gradle Wrapper 加速