groovy - Groovy 脚本中的全局方法

标签 groovy jenkins-pipeline jenkins-groovy

根据another answer如果您在没有 def 的情况下定义一个变量,它将变为“全局”,因此您可以从脚本中的任何位置访问它。如何使用方法来做到这一点(因为没有 def AFAIK 就没有定义)?

郑重声明:我正在定义 Jenkins 管道,并希望在各个阶段之外访问一些“全局”方法

最佳答案

您可以在 Jenkinsfile 中定义任何方法外 pipeline {} ,例如

@NonCPS
def pomVersion() {
    def matcher = readFile('pom.xml') =~ '<version>(.+)</version>'
    return matcher ? matcher[1][1] : null
}

pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
                sh "sed -i.bak -e 's|\${appVersion}|'${pomVersion()}'|g' dep_pom.xml"            
                sh 'mvn clean -U install -DdeploymentContext=test -f dep_pom.xml'
            }
            post {
                success {
                    junit '**/target/**/*.xml'
                }
            }
        }
    }
}

这里是一些示例脚本,它定义了 pomVersion()pom.xml 读取版本的方法文件。它可以在管道的任何阶段和任何步骤中访问。

关于你的陈述:

if you define a variable without def it becomes "global" and thus you can access it from anywhere in the script

其实不是这样的。 Groovy 脚本编译为扩展 groovy.lang.Script 的类类(class)。它使用 bindings存储脚本中使用的所有变量的结构(将其视为 Map<String,Object> )。这种机制允许例如如果它们使用相同的 GroovyShell 运行,则在两个单独的脚本之间共享相同的绑定(bind)实例。

关于groovy - Groovy 脚本中的全局方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48319642/

相关文章:

java - 创建一个通用方法来查找对象列表中某个属性的最大值

java - 如何从 Jenkins Pipeline Groovy 脚本更新配置属性文件?

jenkins-pipeline - 使用 readFile 从文件中读取数据并将其转换为 groovy 中的列表的最佳方法是什么?

groovy - 向 Groovy DSL 添加可选子句

java - 升级到 Spring Boot 2.4 破坏 Spock Spring 模拟

groovy - 如何在groovy中对多值列表进行排序?

Jenkins Pipeline 发布 html 报告

Jenkins Pipeline Jenkinsfile 加载外部 groovy 类

jenkins - 在 JenkinsPipelineUnit 中模拟 findFiles

jenkins - 如何在 Jenkins 管道中并行运行 for 循环的每次迭代?