Groovy jenkins 管道 @NonCPSreturn 不是预期结果

0 groovy jenkins jenkins-pipeline

在我的代码中,我有一个解析日志文件并返回结果列表的方法。如果没有 NonCPS,它可以完美工作并返回正确的值。这个方法是从管道阶段调用的,我得到了 java.io.NotSerializedException: java.util.regex.Matcher 这就是我添加 @NonCPS 注释的原因。不再抛出异常,但 log_parser 方法不能正常工作。现在它总是返回整个文件 - 即使删除返回 result_list。调用此方法的结果始终是文件。

    @NonCPS
    def log_parser(String filename){
    def result_list = []
    def match_f, match_s
    def lines = readFile(filename).readLines()

    for( line in lines ) {
        match_f = (line =~ /(?<=Failures: )[^ ]+/ )
        match_s = (line =~ /(?<=Skips: )[^ ]+/ )

        if( match_f ) {
            result_list[1] = (match_f[0]).replace(",", "") }
        if( match_s ) {
            result_list[2] = (match_s[0]).replace(",", "") }
    }
    return result_list
    }
Run Code Online (Sandbox Code Playgroud)

yon*_*ong 5

因为管道将序列化所有变量(包括函数内的局部变量)作为默认行为,但java.util.regex.Matcher不可序列化,这就是您收到错误的原因。

选项 1)一旦使用完不可序列化的变量,立即释放它。

def log_parser(String filename){
    def result_list = []
    def match_f, match_s
    def lines = readFile(filename).readLines()

    for( line in lines ) {
        match_f = (line =~ /(?<=Failures: )[^ ]+/ )
        match_s = (line =~ /(?<=Skips: )[^ ]+/ )

        if( match_f ) {
            result_list[1] = (match_f[0]).replace(",", "")
            match_f = null
        }
        if( match_s ) {
            result_list[2] = (match_s[0]).replace(",", "")
            match_s = null 
        }
    }
    return result_list
}
Run Code Online (Sandbox Code Playgroud)

选项2)将不可序列化的变量移动到带有注释的函数中:@NonCPS@NonCPS函数内部,我们无法调用任何其他管道步骤,因此您应该readFile移出log_pareser()

log_parser(readFile(<log file path>))

@NonCPS
def log_parser(String fileContent){
    def result_list = []
    def match_f, match_s
    def lines = fileContent.readLines()

    for( line in lines ) {
        match_f = (line =~ /(?<=Failures: )[^ ]+/ )
        match_s = (line =~ /(?<=Skips: )[^ ]+/ )

        if( match_f ) {
            result_list[1] = (match_f[0]).replace(",", "") }
        if( match_s ) {
            result_list[2] = (match_s[0]).replace(",", "") }
    }
    return result_list
}
Run Code Online (Sandbox Code Playgroud)