简体   繁体   中英

How to extract buildscript from build.gradle

I have following buildscript section in my build.gradle:

buildscript {
    ext {
        nexusUrl = project.hasProperty("myNexusUrl") ? myNexusUrl : "http://10.199.0.99:8081/repository/maven-public/"
    }
    repositories {
        maven { url nexusUrl }
    }
    dependencies {
        classpath group: 'mygroup', name: 'MyGradleLibrary', version: '1.0.1'
    }
}

How can I extract this code to external file, so that it doesn't break the build?

Create a plugin from your library and publish it to that Nexus. Then, add this lines in your settings.gradle :

pluginManagement {
    repositories {
        maven {
            url "…"
        }
        gradlePluginPortal()
    }

    resolutionStrategy {
        eachPlugin {
            if (requested.id.namespace == 'mygroup.gradle-library') {
                useModule('mygroup.gradle-library:1.0.1')
            }
        }
    }
}

Here you state that you want to substitute mygroup.gradle-library plugin with mygroup.gradle-library:1.0.1 dependency.

Then just add a plugin in your build.gradle :

plugins {
    id 'mygroup.gradle-library'
}

Now you have you dependency on the build classpath without buildscript block.


EDIT

In order to apply this to all your projects, put these lines in init script ~/.gradle/init.gradle ( $GRADLE_USER_HOME/init.gradle ):

settingsEvaluated {
    pluginManagement {
        repositories {
            maven {
                url "…"
            }
            gradlePluginPortal()
        }

        resolutionStrategy {
            eachPlugin {
                if (requested.id.namespace == 'mygroup.gradle-library') {
                    useModule('mygroup.gradle-library:1.0.1')
                }
            }
        }
    }
}

After that plugin blocks should work. However, it will work only for you but not for your teammates, unless they do the same.

If you don't like plugins you can still do "global" configuration via init scripts like demonstrated. Read more about the available APIs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM