You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkins Groovy Pipeline获取的镜像标签列表无法正确排序的解决方案问询

问题根因

当前你拉取到的标签默认是字符串类型,使用默认排序规则会按照字典序比较,因此会出现121/排在79/之前的问题,只需在返回列表前增加自定义排序逻辑即可解决,以下是两种可行方案:

方案1:纯数字标签场景专用排序

适配你给出的数字/格式标签,直接提取数值排序即可,性能最优:
在你现有脚本的return image_id之前添加如下代码:

// 提取标签内数字转成整数,按数值升序排序
image_id = image_id.sort { it.replaceAll(/\D/, '').toInteger() }

方案2:通用场景自然排序

如果你的标签后续可能出现字母、多段版本号(如v2.3.1、beta-10)等格式,使用自然排序逻辑兼容所有场景:

// 自定义自然排序逻辑,兼容混合字符+数字的标签格式
image_id = image_id.sort { strA, strB ->
    def splitReg = /(?<=\D)(?=\d)|(?<=\d)(?=\D)/
    def partsA = strA.split(splitReg).toList()
    def partsB = strB.split(splitReg).toList()
    def len = Math.max(partsA.size(), partsB.size())
    
    for (int i = 0; i < len; i++) {
        def partA = i < partsA.size() ? partsA[i] : ''
        def partB = i < partsB.size() ? partsB[i] : ''
        
        if (partA.matches(/\d+/) && partB.matches(/\d+/)) {
            def numCmp = partA.toInteger() <=> partB.toInteger()
            if (numCmp != 0) return numCmp
        } else {
            def strCmp = partA <=> partB
            if (strCmp != 0) return strCmp
        }
    }
    return 0
}

补充说明

如果需要降序排列,在排序代码后追加.reverse()即可。

内容的提问来源于stack exchange,提问作者triciratops

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 00:06:03