Jenkins/Groovy:如何从共享库类构造函数调用 readJSON?

问题描述

如何在包含空 JSON 对象的 Jenkins 共享库中定义类?

// src/org/build/Report.groovy

package org.build

public class Report implements Serializable {
  def steps
  def json

  Report(steps) {
    this.steps = steps

    this.json = emptyJson()
  }

  @Noncps
  def emptyJson() {
    return this.steps.readJSON( text: '{}' )
  }
}

...从这个管道实例化:

@Library('my-library')
import org.build.Report
pipeline {
  agent any
  stages {
    stage("foo") {
      steps {
        script {
          rep = new org.build.Report(this)
        }
      }
    }
  }
}

...并失败并显示错误expected to call org.build.Report.<init> but wound up catching readJSON; see: https://jenkins.io/redirect/pipeline-cps-method-mismatches/


我只是在今天早些时候才想到我已经找到了解决这一“类”问题的方法
早些时候,我在从共享库类调用共享库函数时遇到了同样的错误。我根据错误消息指出的链接中的指南修复了该问题,即使用 @Noncps 注释共享库函数
IE。在下面的代码中,类 FirstClass 能够调用函数 firstNonNull(),因为该函数是用 @Noncps 注释的;如果没有注释,此代码生成与上述问题相同的错误

// src/org/example/FirstClass.groovy

package org.example

public class FirstClass implements Serializable {
  def steps
  def var

  FirstClass(steps) {
    this.steps = steps
    this.var = steps.utils.firstNonNull( [null,null,"assigned_from_ctor"] )
  }
}
// vars/utils.groovy

@Noncps
def firstNonNull( arr ) {
  for ( def i in arr ) { if ( i ) { return i } }

  return null
}
@Library('my-library')
import org.example.FirstClass
pipeline {
  agent any
  stages {
    stage("foo") {
      steps {
        script {
          first_class = new org.example.FirstClass(this)
        }
      }
    }
  }
}

为什么这种方法不适用于调用 ReportreadJSON 类?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)