如何在 Jenkins 管道中实现和调用实用方法?

How to implement and invoke utility methods in Jenkins pipelines?

我想实现可重用 functions/methods 以在我的 Jenkins 管道中使用...

 listAllUnitTests([
      $class: 'MyUtilities',
      arg1: 'foo',
      arg2: 'bar'
      ])

不清楚的是实际如何去做;这是一个插件,扩展,它是什么?

狩猎

所以我从一些熟悉的东西开始,比如 Git checkout...

node {
    checkout([
         $class: 'GitSCM',
         branches: scm.branches,
         extensions: scm.extensions,
         userRemoteConfigs: scm.userRemoteConfigs
    ])
 }

查看 Jenkins 插件 GitSCM 的源代码,checkout 方法似乎相当标准;没有特殊的注释或其他任何东西,尽管我不确定管道参数如何与方法签名对齐,因为显然不匹配。我怀疑我走错路了。

@Override
public void checkout(
   Run<?, ?> build,
   Launcher launcher,
   FilePath workspace,
   TaskListener listener,
   File changelogFile,
   SCMRevisionState baseline)
        throws IOException, InterruptedException {

问题

我会保持简单:我如何实现参数化功能以从 Jenkins 管道调用以实现类似的目的?

node {
  stage('test'){

     myUtilMethod([
          $class: 'MyUtilities',
          arg1: 'foo',
          arg2: 'bar'
          ])
  }
}

您可以使用 https://github.com/jenkinsci/workflow-cps-global-lib-plugin/

实现一个或多个库

我建议明确指定您需要该库(使用上面页面中提到的 @Library 注释),而不是使其隐式可用。这样您就可以在开发和测试您的库时在测试作业中使用它的特定分支。

查看 fabric8 以获取一组非常全面的示例:https://github.com/fabric8io/fabric8-pipeline-library