Search code examples
javagradle-kotlin-dsl

Create new File on build.gradle.kts


I have a project that use Jenkinsfile to do some tasks, one of them is generate build version of project with the version on .jar file name.

Using Java 8 and build.gradle i was doing like this

  • Build.gradle

    ext {
        buildVersion = '1.0.0'
    }
    
    task readImageVersion() {
         doLast {
             new File("image.version").text = "Version=${buildVersion}"
         }
    }
    
  • Read this file to get version on Jenkinsfile

    script {
         def props = readProperties file: 'image.version'
         def version = props['Version']
    }
    

Now i'm using Java 17 and build.gradle.kts and i can't find a way to do something like this. Can someone help?

I thy to do something like this, but miserable fails

task("readImageVersion") {
     File.createTempFile(version as String, ".txt")
}

Solution

  • The build.gradle.kts equivalent of the build.gradle snippet in the question would be something like below:

    extra.apply {
        set("buildVersion", "1.0.0")
    }
    
    tasks.register("readImageVersion") {
         doLast {
             file("image.version").appendText("""Version=${project.property("buildVersion")}""")
         }
    }