Search code examples
kotlingroovybuild.gradlegradle-kotlin-dsl

Converting some code snippet from groovy to kotlin KTS in my build.gradle.kts file


I have the following code in my build.gradle.kts. I have now migrated to kotlin KTS. And need help on translating this code from groovy to kotlin script.

fun getVersionFromGit(fallback: String): String {
    return try {
        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
            "git describe --tags --abbrev=0 --match "v*.*.*"".execute().text.substring(1).trim()
        } else {
            ["sh , "-c"", "git describe --tags --abbrev=0 --match "v*.*.*""].execute().text.substring(1).trim()
        }
    } catch (e: Throwable) {
        println("Skipping git version")
        fallback
    }
}

I am getting errors

Unexpected tokens (use ';' to separate expressions on the same line) Unsupported [literal prefixes and suffixes] Unresolved reference: v Expecting an element

Many thanks in advance

UPDATE:

fun getVersionFromGit(fallback: String): String {
    return try {
        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
            "git describe --tags --abbrev=0 --match \"v*.*.*\"".execute().text.substring(1).trim()
        } else {
            listOf("sh , \"-c\"", "git describe --tags --abbrev=0 --match \"v*.*.*\"").execute().text.substring(1).trim()
        }
    } catch (e: Throwable) {
        println("Skipping git version")
        fallback
    }
}

The latest error is Unresolved reference: execute


Solution

  • This should do the trick:

    import java.io.ByteArrayOutputStream
    
    fun getVersionFromGit(fallback: String) =
        try {
            ByteArrayOutputStream().use { out ->
                exec {
                    commandLine = listOf("git", "describe", "--tags", "--abbrev=0", "--match", "v*.*.*")
                    standardOutput = out
                }.assertNormalExitValue()
                out.toString().substring(1).trim()
            }
        } catch (e: Throwable) {
            println("Skipping git version")
            fallback
        }
    
    task("demo") {
        println(getVersionFromGit("oops"))
    }
    

    Tested on MacOS and Windows.