jenkins 共享库声明带有可选参数和闭包的自定义步骤

问题描述 投票:0回答:1

我正在使用全局共享库(vars/mystep.groovy)创建自定义步骤。该步骤需要 3 个可选的命名参数和一个必需的闭包。这对于詹金斯步骤来说是相当标准的,许多内置步骤都有这种模式。

mystep arg3: "foo", arg1: [ 1, 2, 3] {
    // somecode here
}

mystep {
    // somecode here
}

我的问题是 call() 函数的声明。要么它与实际调用的签名不匹配,从而导致

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method
错误,这意味着 call() 函数定义的任何签名都与调用者不匹配。或者我得到参数的空值。

我尝试了几种方法,但都不太有效。最明显的是:

  • def call(arg1=null, arg2=null, arg3=null, Closure somecode)
  • def call(Map args, Closure somecode)
  • def call(Map args = [:], Closure somecode = null)
  • def call(args)

在某些情况下,我可以让它使用参数,但如果不使用参数而仅使用闭包,则会失败。或者反过来。但到目前为止我还没有找到适用于所有情况的神奇公式。

我应该如何定义调用方法以使其与步骤用法相匹配?

jenkins-groovy
1个回答
0
投票

经过多次迭代,我找到了一个可行的公式。它并不完美。需要两次修改:

#1:调用步骤时必须使用()。不知道为什么,这只是 groovy 的语法糖。

mystep () {
   // somecode
}

mystep (arg3:"foo", arg1: [1,2,3]) {
    // somecode
}

如果没有 (),就会弹出各种错误。

#2 重载 mystep.goovy 文件中的 call() 函数。

def call(Closure somecode) {
    mystep(arg1: null, arg2: null, arg3: null, somecode)
}

def call(Map args, Closure somecode=null) {
    def arg1 = args.get('arg1', null)
    ...

这不会进行任何类型检查或处理未知或无效的参数,因此如果有更好的解决方案,我愿意接受。

© www.soinside.com 2019 - 2024. All rights reserved.