superdave
superdave

Reputation: 2298

How do I get a custom property defined in 'gradle.properties in kotlin code?

I added a custom property in gradle.properties :

libraryVersion=0.1.0-beta

How do I read this in the code I'm publishing? I would like to use this value in my Kotlin library without hardcoding it.

Upvotes: 8

Views: 14130

Answers (3)

superdave
superdave

Reputation: 2298

I found the answer I was looking for after digging for a while

Here's the solution:

build.gradle.kts:

import java.io.FileOutputStream
import java.util.Properties

version = "1.0.0"

val generatedVersionDir = "$buildDir/generated-version"

sourceSets {
  main {
    kotlin {
      output.dir(generatedVersionDir)
    }
  }
}

tasks.register("generateVersionProperties") {
  doLast {
    val propertiesFile = file("$generatedVersionDir/version.properties")
    propertiesFile.parentFile.mkdirs()
    val properties = Properties()
    properties.setProperty("version", "$version")
    val out = FileOutputStream(propertiesFile)
    properties.store(out, null)
  }
}

tasks.named("processResources") {
  dependsOn("generateVersionProperties")
}

Library.kts:

private val versionProperties = Properties()

val version: String
  get() {
    return versionProperties.getProperty("version") ?: "unknown"
  }

init {
  val versionPropertiesFile = this.javaClass.getResourceAsStream("/version.properties")
  versionProperties.load(versionPropertiesFile)
}

Upvotes: 0

yunir
yunir

Reputation: 91

You may access system properties defined in gradle.properties. They should have systemProp. prefix. Then in gradle build file you should pass it inside the program.

Here is the example of console application that prints property defined in gradle.properties.

File gradle.properties:

systemProp.libraryVersion=0.1.0-beta

File Main.kt:

fun main(args: Array<String>) {
    val libraryVersion = System.getProperty("libraryVersion") ?: ""
    println(libraryVersion)
}

File build.gradle.kts:

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    kotlin("jvm") version "1.5.10"
    application
}

group = "me.yunir"
version = "0.1"

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(kotlin("test"))
}

tasks.test {
    useJUnitPlatform()
}

tasks.withType<KotlinCompile> {
    kotlinOptions.jvmTarget = "11"
}

application {
    mainClass.set("MainKt")
//    applicationDefaultJvmArgs = listOf(                              // 1
//        "-DlibraryVersion=${System.getProperty("libraryVersion")}"
//    )
}

tasks.named<JavaExec>("run") {                                         // 2
    systemProperty("libraryVersion", System.getProperty("libraryVersion"))
}

There are 2 variants passing system property to program:

  • using "application" plugin-specific property applicationDefaultJvmArgs
  • using systemProperty method for specific task

The output of the program:

0.1.0-beta

Additional links:

UPD. 1

Or if you don't want to use prefix systemProp. and use gradle project properties then it will look like this for the 2nd variant:

File gradle.properties:

libraryVersion=0.1.0-beta

File build.gradle.kts:

...
tasks.named<JavaExec>("run") {                                         // 2
    systemProperty("libraryVersion", findProperty("libraryVersion") ?: "")
}
...

Upvotes: 9

Yura
Yura

Reputation: 383

if you want to use a property from gradle you can do it like this

inside app/build.gradle

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

/******************/
def properties = new Properties()
try {
    properties.load(new FileInputStream(rootProject.file("gradle.properties")))
} catch (Exception e) {
    logger.warn("Properties not Found!")
}
/******************/

android {
    compileSdkVersion 31
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.test.myapplication"
        minSdkVersion 21
        targetSdkVersion 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        
        /********/
        buildConfigField("String", "LIBRARY_VERSION", "\"" + properties['libraryVersion'] + "\"")
        /*********/
    }
}

And you can take this value from BuildConfig

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Log.d("TAG", BuildConfig.LIBRARY_VERSION)
    }
}

Upvotes: 2

Related Questions