Skip to content

Instantly share code, notes, and snippets.

@uOOOO
Last active December 28, 2024 16:55
Show Gist options
  • Select an option

  • Save uOOOO/1af7ee45c2935f67f84a6af198272fe9 to your computer and use it in GitHub Desktop.

Select an option

Save uOOOO/1af7ee45c2935f67f84a6af198272fe9 to your computer and use it in GitHub Desktop.
Using local maven repository without modifying gradle scripts in project
initscript {
// Enter a local Maven server URL.
// Hardcode or get from system property.
val localMavenUrl = ""
// This affects the repositories configuration
// in the buildscript block of the top-level build.gradle(.kts).
gradle.rootProject {
buildscript {
repositories {
maven(localMavenUrl)
}
}
}
// This affects the repositories configuration
// in the pluginManagement and dependencyResolutionManagement blocks of settings.gradle.
gradle.beforeSettings {
pluginManagement {
repositories {
maven(localMavenUrl)
}
}
@Suppress("UnstableApiUsage")
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
repositories {
maven(localMavenUrl)
}
}
}
fun isWindows(): Boolean {
return System.getProperty("os.name")
.lowercase()
.contains("win")
}
fun String.valueOf(className: String): Any {
return Class.forName(className)
.getDeclaredMethod("valueOf", String::class.java)
.apply { isAccessible = true }
.invoke(null, this)
}
fun String.toVariable() =
if (isWindows()) this else valueOf("java.lang.ProcessEnvironment\$Variable")
fun String.toValue() =
if (isWindows()) this else valueOf("java.lang.ProcessEnvironment\$Value")
fun setSystemEnv(fieldName: String, key: String, value: String) {
val field = Class.forName("java.lang.ProcessEnvironment")
.getDeclaredField(fieldName)
.apply { isAccessible = true }
@Suppress("UNCHECKED_CAST")
val env = field.get(null) as MutableMap<Any, Any>
env[key.toVariable()] = value.toValue()
}
fun setSystemEnv(key: String, value: String) {
setSystemEnv("theEnvironment", key, value)
if (isWindows()) {
setSystemEnv("theCaseInsensitiveEnvironment", key, value)
}
}
// Override the GRADLE_LIBS_REPO_URL of DefaultGradleApiSourcesResolver
setSystemEnv("GRADLE_LIBS_REPO_OVERRIDE", localMavenUrl)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment