Skip to content

Instantly share code, notes, and snippets.

@CaiJingLong
Forked from bennyhuo/init.gradle.kts
Last active November 22, 2023 03:48
Show Gist options
  • Save CaiJingLong/0bfd4766fca3d2e412c674a664c0a905 to your computer and use it in GitHub Desktop.
Save CaiJingLong/0bfd4766fca3d2e412c674a664c0a905 to your computer and use it in GitHub Desktop.
Copy files to ~/.gradle, then change to your maven proxy url.
// Thanks to: https://gist.github.com/bennyhuo/af7c43cc4831661193605e124f539942
println("The init script init.gradle.kts is running!")
val gradleHome = System.getProperty("user.home") + "/.gradle"
apply {
val gradleVersion = gradle.gradleVersion
if (gradleVersion < "6.8") {
from(gradleHome + "/old.gradle.kts")
} else {
from(gradleHome + "/new.gradle.kts")
}
}
println("The new scripts")
val localMavenUrl = "http://localhost:8081/repository/maven-public/"
val urlMappings = mapOf(
"https://dl.google.com/dl/android/maven2" to localMavenUrl,
"https://repo.maven.apache.org/maven2" to localMavenUrl,
"https://plugins.gradle.org/m2" to localMavenUrl
)
fun RepositoryHandler.mirroring() {
all {
if (this is MavenArtifactRepository) {
val originalUrl = this.url.toString().removeSuffix("/")
urlMappings[originalUrl]?.let {
logger.lifecycle("Mirroring [$url] to [$it]")
this.setUrl(it)
this.setAllowInsecureProtocol(true)
}
}
}
}
gradle.allprojects {
buildscript {
repositories.mirroring()
}
repositories.mirroring()
}
gradle.beforeSettings {
pluginManagement.repositories.mirroring()
if (gradle.gradleVersion >= "6.8") {
val getDrm = settings.javaClass.getDeclaredMethod("getDependencyResolutionManagement")
val drm = getDrm.invoke(settings)
val getRepos = drm.javaClass.getDeclaredMethod("getRepositories")
val repos = getRepos.invoke(drm) as RepositoryHandler
repos.mirroring()
}
}
println("The old scripts")
val localMavenUrl = "http://localhost:8081/repository/maven-public/"
val urlMappings = mapOf<String, String>(
"https://dl.google.com/dl/android/maven2" to localMavenUrl,
"https://repo.maven.apache.org/maven2" to localMavenUrl,
"https://plugins.gradle.org/m2" to localMavenUrl,
"https://jcenter.bintray.com" to localMavenUrl
)
fun RepositoryHandler.mirroring() {
all {
if (this is MavenArtifactRepository) {
val originalUrl = this.url.toString().removeSuffix("/")
urlMappings[originalUrl]?.let {
logger.lifecycle("Mirroring [$url] to [$it]")
this.setUrl(it)
}
}
}
}
gradle.allprojects {
buildscript {
repositories.mirroring()
}
repositories.mirroring()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment