jenkins - 如何在 jenkinsfile 中定义和使用函数?
问题描述
我想将 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"
}
}
}
}
```
解决方案
您可以像在任何 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")
}
推荐阅读
- python - 从文本文档中读取字符串时,Python 正在替换我的字符串中的字符
- c - 如何捕捉对 exit() 的调用(用于单元测试)
- class - 如何在 Lisp 中创建具有 n 个可能值的类型
- python - Python,同时将类创建附加到列表中
- r - 概率数不正确
- google-sheets - Google 电子表格中工作表的排序是否应该是全局的?
- c++ - 一个向量索引处的多个值
- react-native - 无法在 react-native-map 中安装 google map pod
- python - PIL Python,掩盖图像而不丢失原始图像的某种颜色
- reactjs - 如何使用 id 从 firebase 实时数据库中删除数据?