Jenkins Groovy 如何在不结束管道的情况下从 @NonCPS 方法调用方法 [英] Jenkins Groovy how to call methods from @NonCPS method without ending pipeline

查看:35
本文介绍了Jenkins Groovy 如何在不结束管道的情况下从 @NonCPS 方法调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Jenkins 管道中解析一些 JSON 并在循环中调用一些常规方法,但是脚本总是在第一次函数调用后退出.如何做到这一点?

I need to parse some JSON in a Jenkins Pipeline and call some regular methods in a loop, however the script always exits after the first function call. How to do this?

import groovy.json.JsonSlurper
import com.cloudbees.groovy.cps.NonCPS

@NonCPS
def myMethod(String json) {
    def jsonSlurper = new JsonSlurper()
    def jsonObject = jsonSlurper(json)
    jsonObject.each {
        obj ->
            switch(obj.name) {
                case "foo":
                    doAThing(obj)
                    break
                case "bar":
                    doAnotherThing(obj)
                    break
            }
    }
}

在上面的例子中,即使是像这样的 json 对象:

In the above example, even with a json object like:

[{
    "name": "foo"
}, {
    "name": "bar"
}]

...管道总是在第一次迭代后退出.这可能是由于混合了同步和异步功能.有没有办法做到这一点?

...the pipeline always exits after the first iteration. This is presumably due to mixing sync and async functions. Is there any way to do this?

推荐答案

我基本上通过以下方式解决了这个问题:

I've resolved this issue essentially by doing the following:

import groovy.json.JsonSlurper

def myMethod(String json) {
    def jsonSlurper = new JsonSlurper()
    def jsonObject = jsonSlurper(json)
    jsonSlurper = null
    for(int i = 0; i < jsonObject.size(); i++) {
        switch(jsonObject[i].name) {
            case "foo":
                doAThing(jsonObject[i])
                break
            case "bar":
                doAnotherThing(jsonObject[i])
                break
        }
    }
}

使用后立即销毁 JsonSlurper 实例,移除 @NonCPS 注解,切换到 c 样式的 for 循环而不是每个循环.

Immediately destroy the JsonSlurper instance after it's used, remove @NonCPS annotation, switch to a c-style for loop instead of each.

这篇关于Jenkins Groovy 如何在不结束管道的情况下从 @NonCPS 方法调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆