我的代码中有这个switch
(上下文:Jenkins管道库):
def installOptions(filePath) {
switch (filePath) {
case ~/.*\.pom/:
"-Dpackaging=pom -DpomFile=$filePath"
break
case ~/.*\.jar/:
'-Dpackaging=jar'
break
case ~/.*-exe-archive.zip/:
filePath = filePath.replace '-exe-archive.zip', '.pom'
"-Dpackaging=zip -DpomFile=$filePath"
break
default:
''
break
}
}
filePath
的值:'temp_downloads/merge/QA-9344/itextcore/java/main.pom'
期望值:
-Dpackaging=pom -DpomFile=temp_downloads/merge/QA-9344/itextcore/java/main.pom
实际值:
null
当我在“常规” Groovy中使用完全相同的switch
时,确实获得了预期的输出:
import org.codehaus.groovy.runtime.InvokerHelper
class InstallJavaBranchArtifacts extends Script {
static void main(String[] args) {
InvokerHelper.runScript(InstallJavaBranchArtifacts, args)
}
def run() {
println installOptions('temp_downloads/merge/QA-9344/itextcore/java/main.pom')
println installOptions('temp_downloads/merge/QA-9344/itextcore/java/barcodes.pom')
println installOptions('temp_downloads/merge/QA-9344/itextcore/java/itext7-barcodes-7.1.12-SNAPSHOT.jar')
}
def installOptions(filePath) {
switch (filePath) {
case ~/.*\.pom/:
"-Dpackaging=pom -DpomFile=$filePath"
break
case ~/.*\.jar/:
'-Dpackaging=jar'
break
case ~/.*-exe-archive.zip/:
filePath = filePath.replace '-exe-archive.zip', '.pom'
"-Dpackaging=zip -DpomFile=$filePath"
break
default:
''
break
}
}
}
然后这是我的输出:
/usr/lib/jvm/java-1.11.0-openjdk-amd64/bin/java ...
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass (file:/usr/share/java/groovy-2.4.17.jar) to method java.lang.Object.finalize()
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
-Dpackaging=pom -DpomFile=temp_downloads/merge/QA-9344/itextcore/java/main.pom
-Dpackaging=pom -DpomFile=temp_downloads/merge/QA-9344/itextcore/java/barcodes.pom
-Dpackaging=jar
Process finished with exit code 0
(除了非法的反射访问蒙宝之外,这是预期的输出。
所以我需要做些什么,以使switch
在Jenkins管道库中的行为与在“常规” Groovy中的行为相同?
Jenkins管道使用Groovy CPS解释器运行您的Groovy代码,该解释器将您的代码分解为多个部分,并以连续传递的方式对其进行评估。在您的示例中,您的switch
语句缺少显式的return
,这就是为什么评估函数体返回null
的原因。
有两个选项可以修复它。
您可以在@NonCPS
函数实现中添加installOptions
批注,这样,您将使用常规Groovy Shell解释器运行此函数的主体。这可能对您有用,因为在此函数的主体中,您没有调用任何Jenkins Pipeline工作流步骤,而仅调用了普通的Groovy代码。
如果要在Groovy CPS模式下保持此代码的执行,请从每种情况中删除break
,并在从转换案例返回的每个字符串之前添加显式return
。
如果您想了解更多有关Groovy CPS的信息,请在此处检查文档-https://github.com/cloudbees/groovy-cps。