DEV Community

Cover image for Gradle: How to group Maven Repos in a list
Jens Klingenberg
Jens Klingenberg

Posted on

1 2

Gradle: How to group Maven Repos in a list

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"}
}
view raw gistfile1.txt hosted with ❤ by GitHub

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"}
view raw gistfile1.txt hosted with ❤ by GitHub

and that:

list.each {
maven { url it }
}
view raw gistfile1.txt hosted with ❤ by GitHub

doesn't work.

The solution

First create a list in a Gradle(Groovy)

def mavenRepos = ["https://example.org","https://example1.org"]
view raw gistfile1.txt hosted with ❤ by GitHub

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

ext.buildMaven = { p -> repositories { maven { url p } } }
view raw gistfile1.txt hosted with ❤ by GitHub

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"
}
}
view raw gistfile1.txt hosted with ❤ by GitHub

I hope that this tip was useful for you.

Sentry blog image

The countdown to March 31 is on.

Make the switch from app center suck less with Sentry.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more