我正在努力创造一个基本的工作岗位,以减少我们工作之间的重复。我做了以下工作,但这不起作用:
def baseJob(Map m, Closure c = {}) {
type = m.type ?: 'dev'
pipelineJob("prefix-${m.name}") {
parameters {
stringParam('ONE', 'one', 'Description one')
}
c()
}
}
baseJob(type: 'release', name: 'test') {
parameters { // <-- Fails here
stringParam('TWO', 'two', 'Description two')
}
}我得到以下错误:
错误:(脚本,第12行)没有方法的签名: script.parameters()适用于参数类型:(script$_run_closure1$_closure4)值: script$_run_closure1$_closure4@18b249b3
预期的工作如下:
def baseJob(Map m, Closure c = {}) {
type = m.type ?: 'dev'
pipelineJob("prefix-${m.name}") {
parameters {
stringParam('ONE', 'one', 'Description one')
}
parameters { // <-- This is fine
stringParam('TWO', 'two', 'Description two')
}
c()
}
}
baseJob(type: 'release', name: 'test')所以问题不在于我多次调用parameters。问题似乎是,我在闭包中调用parameters。
我相信有一种方法可以执行闭包,以便正确地调用parameters。但是,我怀疑我还需要更多地了解Groovy和Jenkins Job,然后才能弄清楚。所以我希望有人知道怎么做。
如果您有一个替代的解决方案来完成一个可扩展的基本工作,这也是一个有效的答案。
发布于 2019-07-03 16:48:41
您只需要将调用的闭包的委托设置为您所在的闭包的委托:
def baseJob(Map m, Closure c = {}) {
type = m.type ?: 'dev'
pipelineJob("prefix-${m.name}") {
parameters {
stringParam('ONE', 'one', 'Description one')
}
c.delegate = delegate // <-- Just add this line
c()
}
}
baseJob(type: 'release', name: 'test') {
parameters {
stringParam('TWO', 'two', 'Description two')
}
}delegate包含当前正在执行的闭包的委托。
发布于 2019-07-03 15:05:57
回答:方法
parameters不是在脚本中实现的。它实际上是在管道闭包委托类中实现的。
这段代码可能会帮助你了解那里发生了什么..。
class Test {
void printMe()
{
println "I am in test"
}
}
void test(Closure cl)
{
Test t = new Test()
cl.delegate = t
cl()
}
def callMe = { printMe()}
test {
printMe() // This will run
callMe() // This will fail
}你的例子中的 : pipeline (String arg, Closure pipeLineClosure)
pipeLineClousure是在类X中实现的,其中可以找到parameters方法。如下图所示,
class X
{
...
parameters (Closure cl)
},所以可能的实现是:
class Custom{
String val1
String val2
String val3
}
def baseJob(Map m, List<Custom> l) {
type = m.type ?: 'dev'
pipelineJob("prefix-${m.name}") {
l.each{v->
parameters {
stringParam(v.val1, v.val2, v.val3)
}
}
}
}
List l = []
l.add new Custom(val1: 'ONE', val2: 'one', val3: 'description')
// can be add more values
baseJob(type: 'release', name: 'test', l)希望它能帮助
https://stackoverflow.com/questions/56872330
复制相似问题