Jens Klingenberg

Gradle: How to group Maven Repos in a list

Posted on July 21, 2018  •  2 minutes  • 231 words
Table of contents

In some of my Gradle based projects, i use libraries which have to be downloaded from many different Maven Repositories. To get a better overview of all used repos i wanted to group them in a list. Unfortunately it was a bit more complicated then i thought it would be. Because i couldn’t find other blog posts with my approach, i wanted to share it with you. So here is my solution:

This is how you add one repository to your buildscript:

repositories {
    maven{url "https://example.org"}
}

When you want to add multiple repositories you have add a new maven{} block per URL, something like this :

maven{url "https://example.org",url "https://example1.org"}

and that:

list.each {
    maven { url it }
}

doesn’t work.

The solution

First create a list in a Gradle(Groovy)

def mavenRepos = ["https://example.org","https://example1.org"]

I created this method, which you have to add in the buildscript{} block:

ext.buildMaven = { p -> repositories { maven { url p } } }

Now you can use the method buildMaven() inside the repositories{} block inside a .each{} method of your repo list you want to add :

buildscript {
  ext.buildMaven = { p -> repositories { maven { url p } } }
  ext.kotlin_version = '1.2.31'
  ext.ktor_version = '0.9.1'
  def mavenRepos = ["https://plugins.gradle.org/m2/",
                    "https://dl.bintray.com/kotlin/ktor"]

  repositories {
    google()
    jcenter()
    mavenCentral()
    mavenRepos.each { buildMaven(it) }
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:3.1.1'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
  }
}
Let's connect: