3

Gradle scripts have shortcut functions to define common well known repositories, for example

repositories {
    mavenCentral()
}

I would like to define my own shortcut function something like myPrivateMavenRepo() so that I can write something like

repositories {
    mavenCentral()
    myPrivateMavenRepo()
}

Rather than

repositories {
    mavenCentral()
    maven {
        url "http://repo.mycompany.com/maven2"
    }
}

Questions:

  • How can a custom repo function be developed?
  • Where is this custom function hosted?
  • I have lots of repos that I want to switch to gradle I don't want to hardcode each build.gradle file with the repo Url how do I centralize this in a way that is easy to bootstrap?
JeanValjean
  • 17,172
  • 23
  • 113
  • 157
ams
  • 60,316
  • 68
  • 200
  • 288
  • Probabaly you are looking for https://stackoverflow.com/questions/27777591/how-to-define-and-call-custom-methods-in-build-gradle – Akash Jul 31 '17 at 18:02

2 Answers2

3

The methods in the repositories closure are defined by the RepositoryHandler interface. While mavenCentral(), mavenLocal() and jcenter() add predefined repositories, all other methods require a configuration closure, action or map, which will be applied to a new ArtifactRepository.

A simple approach would be to define such configuration closures, actions or maps and provide them via a plugin extension:

repositories {
    mavenCentral()
    maven myPluginExtension.myRepoClosure
}

Since RepositoryHandler is also a ArtifactRepositoryContainer, you could use its modification methods like add directly to create and register ArtifactRepository objects:

repositories {
    jcenter()
    add myPluginExtension.myRepo
}

If you want to add methods directly to the RepositoryHandler, you can alter its meta class. Please note that this is a Groovy feature, so you can only use this in a Groovy plugin, not a Java plugin.

project.repositories.metaClass.myRepo {
    // implement logic to add repository (e.g. call maven(closure) ...)
}

The method will be available in your build script:

repositories {
    mavenLocal()
    myRepo()
}
Lukas Körfer
  • 13,515
  • 7
  • 46
  • 62
  • Either way fails with: "`Could not find method myRepo() for arguments [] on repository container of type org.gradle.api.internal.artifacts.dsl.DefaultRepositoryHandler.`" message. – Top-Master Apr 23 '22 at 10:27
  • At least if 1. Put in separate file, 2. and imported like "`apply from: './my-repo.gradle'`" 3. finally, used like "`allprojects { repositories { myRepo() } }`" – Top-Master Apr 23 '22 at 10:33
3

I think you could likely do

allprojects {
    repositories.ext.myPrivateMavenRepo = {
        repositories.maven {
           url: 'http://repo.mycompany.com/maven2'
       } 
    } 
} 

Usage

repositories {
    myPrivateMavenRepo() 
} 

You could easily turn that into a plugin

lance-java
  • 25,497
  • 4
  • 59
  • 101