![](/img/trans.png)
[英]Gradle Kotlin : How to convert part of build.gradle script from groovy to build.gradle.kts syntaxe?
[英]Converting some code snippet from groovy to kotlin KTS in my build.gradle.kts file
我的 build.gradle.kts 中有以下代碼。 我現在已經遷移到 kotlin KTS。 並且需要幫助將此代碼從 groovy 轉換為 kotlin 腳本。
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
}
}
我收到錯誤
Unexpected tokens (use ';' to separate expressions on the same line)
Unsupported [literal prefixes and suffixes]
Unresolved reference: v
Expecting an element
提前謝謝了
更新:
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
}
}
最新的錯誤是Unresolved reference: execute
看起來您沒有正確轉義字符串中的引號。
"git describe --tags --abbrev=0 --match "v*.*.*""
應該
"git describe --tags --abbrev=0 --match \"v*.*.*\""
試試這個,但是它可能不會像當前使用 groovy 那樣拆分,因為您必須創建函數 runCommand 來拆分字符串:
fun getVersionFromGit(fallback: String): String {
return try {
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
"git describe --tags --abbrev=0 --match \"v*.*.*\"".runCommand().trim()
} else {
listOf("sh , \"-c\"", "git describe --tags --abbrev=0 --match \"v*.*.*\"").runCommand().trim()
}
} catch (e: Throwable) {
println("Skipping git version")
fallback
}
}
fun String.runCommand(workingDir: File): String? {
...
}
這應該可以解決問題:
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"))
}
在 MacOS 和 Windows 上測試。
通過使用import org.codehaus.groovy.runtime.ProcessGroovyMethods
fun getVersionFromGit(fallback: String): String {
return try {
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
ProcessGroovyMethods.getText(ProcessGroovyMethods
.execute("git describe --tags --abbrev=0 --match \"v*.*.*\"")).substring(1).trim()
} else {
ProcessGroovyMethods.getText(ProcessGroovyMethods
.execute(listOf("sh , \"-c\"", "git describe --tags --abbrev=0 --match \"v*.*.*\""))).substring(1).trim()
}
} catch (e: Throwable) {
println("Skipping git version")
fallback
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.