Groovy different results on using equals() and == on a GStringImpl

Nice question, the surprising thing about the code above is that println “${‘test’}”.equals(‘test’) returns false. The other line of code returns the expected result, so let’s forget about that. Summary “${‘test’}”.equals(‘test’) The object that equals is called on is of type GStringImpl whereas ‘test’ is of type String, so they are not considered equal. But … Read more

Converting a string to int in Groovy

Use the toInteger() method to convert a String to an Integer, e.g. int value = “99”.toInteger() An alternative, which avoids using a deprecated method (see below) is int value = “66” as Integer If you need to check whether the String can be converted before performing the conversion, use String number = “66” if (number.isInteger()) … Read more

Load script from groovy script

If you don’t mind the code in file2 being in a with block, you can do: new GroovyShell().parse( new File( ‘file1.groovy’ ) ).with { method() } Another possible method would be to change file1.groovy to: class File1 { def method() { println “test” } } And then in file2.groovy you can use mixin to add … Read more

Get values from properties file using Groovy

It looks to me you complicate things too much. Here’s a simple example that should do the job: For given test.properties file: a=1 b=2 This code runs fine: Properties properties = new Properties() File propertiesFile = new File(‘test.properties’) propertiesFile.withInputStream { properties.load(it) } def runtimeString = ‘a’ assert properties.”$runtimeString” == ‘1’ assert properties.b == ‘2’

Can you break from a Groovy “each” closure?

Nope, you can’t abort an “each” without throwing an exception. You likely want a classic loop if you want the break to abort under a particular condition. Alternatively, you could use a “find” closure instead of an each and return true when you would have done a break. This example will abort before processing the … Read more

Creating a Jenkins environment variable using Groovy

Jenkins 1.x The following groovy snippet should pass the version (as you’ve already supplied), and store it in the job’s variables as ‘miniVersion’. import hudson.model.* def env = System.getenv() def version = env[‘currentversion’] def m = version =~/\d{1,2}/ def minVerVal = m[0]+”.”+m[1] def pa = new ParametersAction([ new StringParameterValue(“miniVersion”, minVerVal) ]) // add variable to … Read more

Including a groovy script in another groovy

evaluate(new File(“../tools/Tools.groovy”)) Put that at the top of your script. That will bring in the contents of a groovy file (just replace the file name between the double quotes with your groovy script). I do this with a class surprisingly called “Tools.groovy”.