我正在尝试将使用 Jenkins Job DSL 插件的代码分解为可重用的部分,并且我怀疑我的问题是 Groovy 通用的,而不是 Jenkins 特定的。例如,我想重用此 block 的部分内容:
freeStyleJob() {
//generic stuff
name "something"
description "something else"
//custom stuff
scm {
svn {
//etc....
}
}
}
通过将名称和描述放入实用方法中(显然我想做的不仅仅是在现实生活中这样做)。但是,我找不到正确的语法来为当前作用域创建闭包。我认为它应该是这样的:
def jobCommonItems() {
return {
//generic stuff
name "something"
description "something else"
}
}
freeStyleJob() {
jobCommonItems().call()
//custom stuff
scm {
svn {
//etc....
}
}
}
(也许在某处有一个closure.delegate = this)
但是,这不适用于闭包。它适用于方法,如下所示:https://dzone.com/articles/groovy-closures-owner-delegate
为了说明这一点,这里有一个测试,显示了可能语法的三种组合:
String myString = "Top Level: string"
def myMethod() {
println "Top Level: Method"
}
def myClosure = { println "Top Level: Class"}
class MyClass1 {
String myString = "Class1: String"
def myMethod() {
println "Class1: Method"
}
def myClosure = { println "Class1: Closure"}
}
class MyClass2 {
String myString = "Class2: String"
def myMethod() {
println "Class2: Method"
}
def myClosure = { println "Class2: Closure"}
}
class MyClass {
def closure = {
println "In-Class generated closure begins, delegate is ${delegate}"
myMethod()
myClosure()
println myString
}
}
def closure = new MyClass().closure
closure.delegate = new MyClass1()
closure()
closure = new MyClass().closure
closure.delegate = new MyClass2()
closure()
// This fails - it can find the top level method, but not closure or string
closure.delegate = this
closure()
def methodMissing(String methodName, args) {
println "Method not found in class ${this} by name ${methodName}"
}
我收到一个错误,指出闭包不在主类中(即测试 test.groovy):未在类 test@60611244 中按名称 myClosure 找到方法
我尝试将委托(delegate)更改为“this”,我尝试更改查找策略等。我可能错过了一些基本的东西。
最佳答案
诸如freeStyleJob
之类的作业工厂方法返回一个对象,该对象可用于使用with
方法应用更多配置。该方法需要一个闭包参数,该参数与传递给 freeStyleJob
方法的闭包具有相同的属性。
def basicConfiguration() {
return {
description('foo')
scm {
// whatever
}
}
}
def myJob = freeStyleJob('example') {
publishers {
// more config
}
}
myJob.with basicConfiguration()
脚本本身是 DslFactory
的一个实例,它是包含以下内容的接口(interface): freeStyleJob
方法。您可以将该对象传递给类或方法以使用 freeStyleJob
。
def myJobFactory(def dslFactory, def jobName) {
dslFactory.freeStyleJob(jobName) {
description('foo')
}
}
def myJob = myJobFactory(this, 'example')
然后您可以使用 myJob
对象通过 with
应用进一步配置。
关于Groovy:如何从另一个闭包调用顶级范围内的闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32464548/