如何在 Jenkins Job DSL 插件上下文中使用共享/通用 Groovy 方法

Joh*_*Zaj 5 groovy jenkins

使用 GroovyConsole 我有文件 main.groovy :

new Helpers().test("test method called")
Run Code Online (Sandbox Code Playgroud)

并在同一目录中有包含内容的文件 Helpers.groovy

def test(String str) {
    println "test method called with: " + str
}
Run Code Online (Sandbox Code Playgroud)

运行结果中的结果:

groovy> new Helpers().test("test method called") 

test method called with: test method called
Run Code Online (Sandbox Code Playgroud)

然而,在 Jenkins 使用 DSL 的上下文中,我在文件生成器.groovy 中有类似的代码:

new Helpers().test("test method called")
Run Code Online (Sandbox Code Playgroud)

然后在同一目录的 Helpers.groovy 中我有:

def test(String str) {
    println("test method called on: " + str)
}
Run Code Online (Sandbox Code Playgroud)

但是,当我运行时,我在日志中没有得到任何输出(来自 println)。如果我将 def 放在同一个 main.groovy 文件中,则它可以正常工作。

可能缺少一些基本的东西。它正在詹金斯中编译/绿色,所以不确定如何适应这一点,因此运行时将执行我想要的操作。

use*_*900 1

从其他文件调用方法时需要导入类

在与 DSL 相同级别创建一个名为utilities的目录,并在utilities目录中创建一个名为MyUtilities.groovy的文件,其中包含以下内容:

package utilities

class MyUtilities {
    static void addMyFeature(def job) {
        job.with {
            description('Arbitrary feature')
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后从 DSL 中添加如下内容:

import utilities.MyUtilities
Run Code Online (Sandbox Code Playgroud)