Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refactor common Jenkins JobDSL code?

I have the following JobDSL spec:

job {   steps {     gradle('generateLock saveLock', '-PdependencyLock.includeTransitives=true', true) { node ->       node / wrapperScript('${NEBULA_HOME}/gradlew')     }     gradle('check', '', true) { node ->       node / wrapperScript('${NEBULA_HOME}/gradlew')     }   } } 

I'd like to refactor the common code, say, into a function:

def gradlew(String tasks, String options) {   gradle(tasks, options, true) { node ->     node / wrapperScript('${NEBULA_HOME}/gradlew')   } } 

But the gradle function isn't visible from within the gradlew function. What's the right way to do this?

like image 522
Noel Yap Avatar asked Jan 13 '15 21:01

Noel Yap


1 Answers

The curly brackets form a Groovy closure. Each closure has a delegate object to which method calls are directed. And the delegate can be accessed via the delegate property. You can pass that delegate to the helper function to get access to it's methods.

def gradlew(def context, String tasks, String options = '') {   context.gradle(tasks, options, true) { node ->     node / wrapperScript('${NEBULA_HOME}/gradlew')   } } job {   steps {     gradlew(delegate, 'generateLock saveLock', '-PdependencyLock.includeTransitives=true')     gradlew(delegate, 'check')   } } 
like image 200
daspilker Avatar answered Sep 22 '22 19:09

daspilker