Itai Ganot Itai Ganot - 1 month ago 19
Groovy Question

Groovy: How to save the result of a function run within a variable?

I'm writing a Jenkins pipeline script in Groovy and I'm setting annotation to Mixpanel and for that I have to provide some details such as "RELEASE_DATE", here's the relevant portion of the Jenkinsfile:

MP_API_KEY = "XXXXXXXXXX"
MP_API_SECRET = "XXXXXXXXXXX"
MP_EXPIRE = "1588896000"
MP_APP_PLATFORM = "Android"
MP_BASE_URL = "http://mixpanel.com/api/2.0/annotations/create?"
def get_current_time_date() {
Date date = new Date(); // given date
Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date); // assigns calendar to given date
HOUR24 = calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
timem = calendar.get(Calendar.MINUTE);
times = calendar.get(Calendar.SECOND);
newdate = date.format( 'yyyy-MM-dd' );
println newdate +' '+ HOUR24 + ':' + timem + ':' + times
}
RELEASE_DATE = get_current_time_date()
MP_RELEASE_NOTES = ""
DESCRIPTION = "${MP_APP_PLATFORM} v${MP_VERSION_NAME} ${MP_RELEASE_NOTES}"
REQUEST_URL = "api_key=${MP_API_KEY}&date=${RELEASE_DATE}&description='${DESCRIPTION}'&expire=${MP_EXPIRE}"


I'm trying to fill the RELEASE_DATE variable with the result of the "get_current_time_date" function but to no avail.

So the things I've tried are:

RELEASE_DATE = get_current_time_date
def RELEASE_DATE = get_current_time_date
def RELEASE_DATE = new get_current_time_date
def RELEASE_DATE = { -> get_current_time_date() }


Example result of running the function:

2016-10-18 12:44:35

Answer

try it.

 def get_current_time_date() {
     ...your code..
     def result = newdate +' '+ HOUR24 + ':' + timem + ':' + times
     println result
     result
 }
 RELEASE_DATE = get_current_time_date()