1. Groovy Syntax¶
1.1. Variable¶
// Variable declaration
String x
def o
// You can also use implicit declaration
x = 1
println x
x = new java.util.Date()
println x
x = -3.1499392
println x
x = false
println x
x = "Hi"
println x
def (a, b, c) = [10, 20, 'foo']
def nums = [1, 3, 5]
def a, b, c
(a, b, c) = nums
// String literals
def username = 'Jenkins'
echo 'Hello Mr. ${username}'
echo "I said, Hello Mr. ${username}"
// Multi line strings
def viewspec = '''
//depot/Tools/build/... //jryan_car/Tools/build/...
//depot/commonlibraries/utils/... //jryan_car/commonlibraries/utils/...
//depot/helloworld/... //jryan_car/helloworld/...
'''
1.2. Conditional¶
def x = false
def y = false
if ( !x ) {
x = true
}
assert x == true
if ( x ) {
x = false
} else {
y = true
}
assert x == y
1.3. Control structure¶
def x = 1.23
def result = ""
switch ( x ) {
case "foo":
result = "found foo"
// lets fall through
case "bar":
result += "bar"
case [4, 5, 6, 'inList']:
result = "list"
break
case 12..30:
result = "range"
break
case Integer:
result = "integer"
break
case Number:
result = "number"
break
case ~/fo*/: // toString() representation of x matches the pattern?
result = "foo regex"
break
case { it < 0 }: // or { x < 0 }
result = "negative"
break
default:
result = "default"
}
1.4. Function¶
// Optional ``return``
def jobName = 'example'
job(jobName) {
}
// Variable function parameter length
def concat1 = { String... args -> args.join('') }
assert concat1('abc','def') == 'abcdef'
def concat2 = { String[] args -> args.join('') }
assert concat2('abc', 'def') == 'abcdef'
def multiConcat = { int n, String... args ->
args.join('')*n
}
assert multiConcat(2, 'abc','def') == 'abcdefabcdef'
1.5. Class¶
// Simple class declaration
class Person {
String name
int age
def fetchAge = { age }
}
def p = new Person(name:'Jessica', age:42)
class Person {
String name
String toString() { name }
}
def sam = new Person(name:'Sam')
// Create a GString with lazy evaluation of "sam"
def gs = "Name: ${-> sam}"
1.6. Loop¶
String message = ''
for (int i = 0; i < 5; i++) {
message += 'Hi '
}
assert message == 'Hi Hi Hi Hi Hi '
1.7. Import¶
package utilities
class MyUtilities {
static void addMyFeature(def job) {
job.with {
description('Arbitrary feature')
}
}
}
import utilities.MyUtilities
def myJob = job('example')
MyUtilities.addMyFeature(myJob)
1.8. Exception¶
try {
'moo'.toLong() // this will generate an exception
assert false // asserting that this point should never be reached
} catch ( e ) {
assert e in NumberFormatException
}
1.9. Rest API HTTP queries¶
def project = 'Netflix/asgard'
def branchApi = new URL("https://api.github.com/repos/${project}/branches")
def branches = new groovy.json.JsonSlurper().parse(branchApi.newReader())
branches.each {
def branchName = it.name
def jobName = "${project}-${branchName}".replaceAll('/','-')
job(jobName) {
scm {
git("https://github.com/${project}.git", branchName)
}
}
}