How to add a maven repository by url using kotlins

2020-06-06 08:17发布

问题:

Whats the equivalent of the following code snippet from a build.gradle in a build.gradle.kts version?

repositories {
  mavenCentral()
  maven {
    url '<MAVEN REPO URL>'
  }
}

回答1:

As an addition to the other answers, in #kotlin-dsl/256 shortcut methods were added to the various repository methods to do something like the following:

repositories {
  mavenCentral()
  maven(url = "<MAVEN REPO URL>")
}

According to the issue, this was added in the Kotlin DSL version 0.11.1. The 0.11.x versions were included in the Gradle 4.2 release.

To see the Gradle version you are running with your build when using the Gradle wrapper run ./gradlew --version.



回答2:

At 2018-01-13 the correct syntax is the following (instead of url, the function setUrl):

repositories {
    mavenCentral()
    maven {
        setUrl("<MAVEN REPO URL>")
    }
}


回答3:

The official doco allows you to switch the examples between the Groovy and Kotlin DSLs. Currently the answer listed there to your question is:

repositories {
    mavenCentral()
    maven {
        url = uri("<MAVEN REPO URL>")
    }
}

I needed to add Gitlab with authentication, which has a more complicated syntax. For others that stumble upon this, here is the official Gitlab example translated to the kts/Kotlin syntax.

val gitLabPrivateToken: String by project

maven {
    url = uri("https://<gitlab-url>/api/v4/groups/<group>/-/packages/maven")
    name = "GitLab"
    credentials(HttpHeaderCredentials::class) {
        name = "Private-Token"
        value = gitLabPrivateToken
    }
    authentication {
        create<HttpHeaderAuthentication>("header")
    }
}

The example URL here is true to Gitlab doco. But for me, it only worked with a URL like this: https://gitlab.com/api/v4/projects/12345/packages/maven