【问题标题】:Groovy vs Jenkins - regex replaceFirst/replaceAll function with closure works differently in Jenkins shared libraryGroovy vs Jenkins - 带有闭包的正则表达式 replaceFirst/replaceAll 函数在 Jenkins 共享库中的工作方式不同
【发布时间】:2020-05-12 16:35:08
【问题描述】:

我尝试创建一个 Jenkins 共享库。为此,我创建了可单元测试的 Groovy 类,例如版本控制。我有一个正则表达式模式,我想用 groovy 闭包中的匹配参数替换版本字符串。在 Junit 测试中,一切正常,但从 Jenkins 开始,如果我使用多参数闭包,我只会在所有参数中得到空值。

我的版本控制功能:

static String getNewVersion(String oldVersion, VersioningType type) {
        Pattern pattern = ~/^(\d+)\.(\d+)\.(\d+)(-.*)?$/
        switch (type) {
            case VersioningType.INC_PATCH:
              //Closure incPatchNotworkingFromJenkins = { _, major, minor, patch, postfix -> "${major}.${minor}.{(patch as int) + 1}{postfix :? ""}"}  
                Closure incPatch = { matchgroups -> "${matchgroups[1]}.${matchgroups[2]}.${(matchgroups[3] as int) + 1 }${matchgroups[4] ?: ""}" }
                return oldVersion.replaceAll(pattern, incPatch)
    }
}

这行得通,但是评论中的闭包 Jenkins 仅在所有参数中都获得了 null-s,只有 _ 参数获得了值。如果我 println 参数,我得到 [0.1.1, null, null, null, null], null, null, null, null。

有人可以帮我吗?为什么 Jenkins 不理解多参数闭包?

提前致谢!

【问题讨论】:

    标签: regex jenkins groovy closures shared-libraries


    【解决方案1】:

    让你的函数@NonCPS

    @NonCPS
    static String getNewVersion(String oldVersion, VersioningType type) {
            Pattern pattern = ~/^(\d+)\.(\d+)\.(\d+)(-.*)?$/
            switch (type) {
                case VersioningType.INC_PATCH:
                    Closure incPatchNotworkingFromJenkins = { _, major, minor, patch, postfix -> "${major}.${minor}.{(patch as int) + 1}{postfix :? ""}"}  
                    // Closure incPatch = { matchgroups -> "${matchgroups[1]}.${matchgroups[2]}.${(matchgroups[3] as int) + 1 }${matchgroups[4] ?: ""}" }
                    return oldVersion.replaceAll(pattern, incPatch)
        }
    }
    

    【讨论】:

    • 用这种方法我得到了 groovy.lang.MissingMethodException: No signature of method: Versioner$_getNewVersion_closure1.0.1.{(patch as int) + 1}{postfix :? () 适用于参数类型:(java.lang.String) 值:[}] Versioner 是包含此方法的 groovy 类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 2014-10-15
    • 2013-08-19
    • 1970-01-01
    • 2015-04-01
    • 2022-07-07
    相关资源
    最近更新 更多