Jenkins共享库实现Groovy Trait触发CPS编译报错问题
环境配置
配置Jenkins共享库时采用如下目录结构:
vars/ utils.groovy src/ com.my.corp.utils/ tools/ Utilities.groovy helpers/ Workflow.groovy
Workflow.groovy代码
package com.my.corp.utils.helpers // import org.jenkinsci.plugins.workflow.cps.CpsScript trait Workflow { def workflow }
Utilities.groovy代码
package com.my.corp.utils.tools import com.my.corp.utils.helpers.Workflow // import org.jenkinsci.plugins.workflow.cps.CpsScript class Utilities implements Serializable, Workflow { def x = 5 def y = 10 def echo(Map args) { this.workflow.sh """echo 'args: ${args}'""" this.workflow.sh """echo 'args.inspect(): ${args.inspect()}'""" this.workflow.sh """echo 'this.steps: ${this.workflow}'""" this.workflow.echo message: args.inspect() this.workflow.sh """echo "${this.workflow.class.getName()}; args: ${args}\"""" } }
utils.groovy代码
import com.my.corp.utils.tools.Utilities def call(Map params) { this.echo "${this}" params.put('workflow', this) new Utilities(params).echo(params) }
问题现象
在主流水线中调用utils x: 1, y: 2时,抛出如下报错:
org.jenkinsci.plugins.workflow.cps.CpsCompilationErrorsException: startup failed
完整错误栈提示Unsupported array expression for CPS transformation in this context,即当前上下文存在CPS转换不支持的数组表达式,共触发2个编译错误。
对比验证
测试发现:若将Workflow从trait改为abstract class,同时将Utilities类定义改为extends Workflow implements Serializable,代码可正常运行;且上述使用trait的代码在纯Groovy在线执行环境中运行无任何异常。
根因说明
该问题是Jenkins WorkflowCPS模块(即workflow-cps-plugin)的已知功能限制,官方Jira issue JENKINS-46145: Groovy Traits are not supported 明确记录了该问题,同时该限制也会影响接口方法的默认实现,在对应Java与Jenkins版本中可稳定复现。
内容的提问来源于stack exchange,提问作者Peter Zaitcev
相关产品推荐
相关产品推荐

