Search code examples
javagradlegradle-kotlin-dsl

using a common variable in settings.gradle.kts and build.gradle.kts


I'm using Gradle in my JAVA project, and I'm using the same URL in both settings.gradle.kts and build.gradle.kts files.

The URL is duplicated in both files and I want to declare it once and use it in both of the files in the way gradle designed to do that (no hacks).

I've tried the following:

  1. Using the project extras but could find a way to use it in both files but only in the build file.
  2. Declare the variable in the top of the settings.gradle.kts file and then try to access it from the build file - with no success.

I know I can use the gradle.properties file but it's local for each developer and I don't want everyone to add it to their file.

I'm trying to find the way that would be transparent to the team.

this is how it looks now:

settings.gradle.kts

pluginManagement {
    val nexusUsername: String by settings
    val nexusPassword: String by settings

    repositories {
        maven {
            credentials {
                username = nexusUsername
                password = nexusPassword
            }

            val nexusBaseUrl = System.getenv("NEXUS_BASE_URL") ?: "my-default-url"
            url = uri("$nexusBaseUrl/nexus/content/repositories/gradle-plugins/")
        }
    }
}

build.gradle.kts

import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.tasks.testing.logging.TestExceptionFormat

plugins {
    java
    checkstyle
    id("com.github.johnrengelman.shadow") version "7.1.2"
}


subprojects {

    val nexusUsername: String by project
    val nexusPassword: String by project

    repositories {
        maven {
            name = "NexusPublic"
            credentials {
                username = nexusUsername
                password = nexusPassword
            }
            val nexusBaseUrl = System.getenv("NEXUS_BASE_URL") ?: "my-default-url"
            url = uri("$nexusBaseUrl/nexus/content/groups/public/")
        }
    }

and I want nexusBaseUrl to be declared once and used in both files.


Solution

  • Gradle.properties shouldn't be local for each developer, it shouldn't be part of gitignore.

    I recommend getting nexusUsername and nexusPassword from the environment variables instead, and having nexusBaseUrl on gradle.properties, the same way you have the username and password right now.

    To get from environment variable, use System.getenv("NEXUS_USERNAME") as shown here.