在Jenkins管道中列出就地排序

时间:2017-09-21 03:35:03

标签: sorting jenkins groovy jenkins-pipeline

我正在尝试对Jenkins管道中的对象列表进行排序。我在本地或Jenkins内部运行代码得到的结果不同:

pipeline {
    agent any
    stages {
        stage('default'){
            steps {
                script {
                   @NonCPS
                   def nonCpsTest = {
                        def list = [
                            ['CreationDate': '200'],
                            ['CreationDate': '300'],
                            ['CreationDate': '100'],
                       ]

                       def rval = list.sort { it['CreationDate'] }

                       echo "Rval=$rval"
                       echo "List=$list"  
                   }
                   nonCpsTest()
                }
            }
        }
    }
}

当我使用groovy shell(groovysh)在本地执行此脚本时,结果是

groovy:000> list = [[ 'CreationDate':200 ], [ 'CreationDate':300 ], [ 'CreationDate':100 ]]
===> [[CreationDate:200], [CreationDate:300], [CreationDate:100]]
groovy:000>  rval = list.sort { it['CreationDate'] }
===> [[CreationDate:100], [CreationDate:200], [CreationDate:300]]
groovy:000> list
===> [[CreationDate:100], [CreationDate:200], [CreationDate:300]]
groovy:000> list == rval
===> true

在Jenkins服务器上我正在关注

[Pipeline] {
[Pipeline] stage
[Pipeline] { (default)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
Rval=300
[Pipeline] echo
List=[[CreationDate:200], [CreationDate:300], [CreationDate:100]]
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline

Jenkins工作流使列表无论如何都是不可变的,或者覆盖sort方法,如果是这样,如何在Jenkins管道代码中进行列表排序?

1 个答案:

答案 0 :(得分:4)

您将nonCpsTest声明为变量并且它引用了闭包的问题,​​因此@NonCPS在这种情况下不起作用

以下变体可以正常工作:

@NonCPS
def nonCpsTest() {
    def list = [
        ['CreationDate': '200'],
        ['CreationDate': '300'],
        ['CreationDate': '100'],
    ]
    def rval = list.sort{ it['CreationDate'] }
    echo "Rval=$rval"
    echo "List=$list"  
}

node{
   nonCpsTest()
}