Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define Gradle project properties with Kotlin DSL

I'd like to check if two project properties are set and if not, set them to empty values in order to avoid a build failure. These properties are supposed come from ~/.gradle/gradle.properties (if configured).

The goal is to have credentials to a Maven repository in S3 defined in that local file. Every user has to put his own data there, but I want the build to just output a warning and continue if these are not set. Chances are high it will still be successful even without contacting S3.

I have got it running with Groovy DSL, but I am now switching to Kotlin and I just can't get the syntax right.

This is how ~/.gradle/gradle.properties looks like:

s3AccessKeyId=ABCDEFGHIJKLMNOPQRST
s3SecretKey=abcdefghijklmnopqrstuvwxyz1234567890abcd

And here are the relevant sections of the build.gradle.kts

if (!project.hasProperty("s3AccessKeyId") || !project.hasProperty("s3SecretKey")) {
    logger.lifecycle("WARNING: s3AccessKeyId and s3SecretKey not set!")
    project.extra["s3AccessKeyId"] = ""
    project.extra["s3SecretKey"] = ""
}

repositories {
    mavenLocal()
    maven {
        url = uri("s3://maven-repo.mycompany.com.s3.eu-central-1.amazonaws.com/")
        credentials(AwsCredentials::class) {
            accessKey = project.extra["s3AccessKeyId"].toString()
            secretKey = project.extra["s3SecretKey"].toString()
        }
    }
}

No matter how I write the s3AccessKeyId="" lines, I am always getting the error:

Cannot get property 's3AccessKeyId' on extra properties extension as it does not exist

If all artifacts are found in the local Maven repository, I expect the build to work, even without gradle.properties. Only if some artifact is missing, the build should abort with some "credentials wrong" error.

As I said, it already worked with Groovy.

like image 931
chrset Avatar asked Nov 12 '19 14:11

chrset


People also ask

What is Kotlin Gradle DSL?

Kotlin DSL brings the simplicity of the Kotlin language syntax and rich API set right into the script files on top of that code completion makes it perfect to work with Gradle script files. We will use this to manage our dependencies and project settings configurations more elegantly.

Which DSL does Gradle use?

IDE support. The Kotlin DSL is fully supported by IntelliJ IDEA and Android Studio.


1 Answers

For that you need to use the properties attibute which is different from the extra like:

project.properties["s3SecretKey"].toString()

And then you need to have in your gradle.properties:

s3AccessKeyId=ABCDEFGHIJKLMNOPQRST

If the value is not there it might return null so you can do:

(project.properties["s3SecretKey"] ?: "default value").toString()

And it should work

like image 86
Sylhare Avatar answered Sep 25 '22 20:09

Sylhare