mans0ry
mans0ry

Reputation: 13

Jenkins console script different results

I am trying to get last successful build on multibranch pipeline job, and only what I came to is this

def str = Jenkins.instance.getAllItems() .findAll{ it instanceof Job }.collect{ it.getLastSuccessfulBuild() }.findAll{ it } .sort{ it.timestamp }.grep(~/iOS.*/).last().toString()
println str.substring(str.lastIndexOf('/') + 1).replace('%2F', '_').replace(' #', '_')

but unfortunately, this only works in script console of Jenkins, and throwing different results in pipeline, any guesses what could be wrong?

Jenkins version 2.176.1

I expect the output of:

feature_INC-777_77

But getting:

java.util.GregorianCalendar[time=1566913952011,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Moscow",offset=10800000,dstSavings=0,useDaylight=false,transitions=79,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2019,MONTH=7,WEEK_OF_YEAR=35,WEEK_OF_MONTH=5,DAY_OF_MONTH=27,DAY_OF_YEAR=239,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=52,SECOND=32,MILLISECOND=11,ZONE_OFFSET=10800000,DST_OFFSET=0]

For pipeline like:

import jenkins.model.*
import hudson.model.*
import jenkins.*
import hudson.*

def str = Jenkins.instance.getAllItems().findAll{ it instanceof Job }.collect{ it.getLastSuccessfulBuild() }.findAll{ it }.sort{it.timestamp}

println str

Can someone help with this, please?

Upvotes: 1

Views: 683

Answers (1)

lGSMl
lGSMl

Reputation: 171

ah this beautiful groovy + Jenkins combo...

put your statement into a method and add annotation on top @NonCPS

While I will be in trouble to get a clear full explanation, in short - jenkins push all the code in your scripted pipeline via super-complicated (as for me) set of CPS transforms - https://github.com/cloudbees/groovy-cps/ , which may or may not convert groovy API properly. Rule of thumb - when using closures - use @NonCPS annotation, otherwise you will have a ton of weird errors that are hard to debug.

more info:

https://wiki.jenkins.io/display/JENKINS/Pipeline+CPS+method+mismatches

https://github.com/jenkinsci/workflow-cps-plugin

What is the effect of @NonCPS in a Jenkins pipeline script

Upvotes: 1

Related Questions