我该如何在Jenkinsfile中定义和使用函数?

4
我想将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"
        }
    }
}
}
```




1个回答

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")
}

1
谢谢,我明白了。之前对于脚本和声明式管道的概念理解不够清晰,你的回答帮助我打开了思路。 - Vatsalya Singh
而且函数在声明式流水线中不起作用,只能在脚本中使用。因此,你可能需要修改你的答案,改为node{ }而不是pipeline。 - Vatsalya Singh
1
不,我刚刚检查过了。它们也可以在声明中使用。只要确保它们在pipeline{}块之外即可。 - smelm
谢谢!我已经从声明式管道转向脚本化管道,发现它更容易。 - Vatsalya Singh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接