如何在 jenkinsfile 中定义和使用函数?

Vat*_*ngh 4 jenkins jenkins-groovy jenkins-pipeline

我想将 git diff shell 脚本的输出检索到变量中,然后在其上运行用户定义的函数。我如何声明我想要编写的这些函数以及如何使用它们?

pipeline{
agent any
parameters {
        string(name: 'branchA', defaultValue: 'master', description: 'Comapare which branch?')

        string(name: 'branchB', defaultValue: 'dev', description: 'Compare with which branch?')
}

stages {
    stage('Build') {
        steps{
            checkout([$class: 'GitSCM',
                branches: [[name: '*/master']],
                doGenerateSubmoduleConfigurations: false,
                extensions: [[$class: 'CleanBeforeCheckout']],
                submoduleCfg: [],
                userRemoteConfigs:  [[credentialsId: 'gitCreds', url: "https://github.com/DialgicMew/example.git"]]])
 
                sh "git diff --name-only remotes/origin/${params.branchA} remotes/origin/${params.branchB}"    
         }
    
    stage('Functions on the result') {
        steps{
            echo "Functions to be used here"
        }
    }
}
}
```




Run Code Online (Sandbox Code Playgroud)

sme*_*elm 9

您可以像在任何 Groovy 脚本中一样定义函数,并且可以通过向其传递参数returnStdout来捕获任何 shell 命令的输出。我认为您需要一个脚本环境来调用函数和定义变量。所以它看起来像这样:

pipeline{
    // your pipeline
    scripted {
        def output = sh returnStdout: true, script: "git diff ..."
        def result = workWithOutput(output)
        println result
    }

}

def workWithOutput(text){
    return text.replace("foo", "bar")
}
Run Code Online (Sandbox Code Playgroud)