Groovy compare string - groovy

I have the Groovy code as below
def retVal = sh(returnStdout: true, script: "curl ${URI}; echo \$?")
println("Return value: ${retVal}") -> it printed 0
if (retVal == "0") {
println("Successfull") -> it doesn't go here
}
why the above condition can't be catched?

First of all, you seem to be using the Jenkins API incorrectly.
If all you need is the exit code of the process, use returnStatus: true:
def retVal = sh(returnStatus: true, script: "curl ${URI}")
if (retVal == 0) {
println 'success'
} else {
println "Something wrong, exit code was $retVal")
}
Now, if you really want the stdout instead, perhaps clean up the String first by calling trim() on it or try to match the String against a regex:
if (retValue ~== /\s*0\s*/) {
println "success"
} else {
println "Something wrong, exit code was '$retVal'")
}
I always put quotes around a value I print to make sure new-lines or whitespaces don't make me waste time with bad values.

Related

Groovy pipeline if-else condition

So I try to set variable base of my job {currentBuild.currentResult} status.
script {
if ({currentBuild.currentResult} == "SUCCESS") {
HEADER_COLOR = "green"
} else {
HEADER_COLOR = "Red"
}
}
And although the job pass and the status is SUCCESS the else condition is executed so I put print inside the else section:
else {
echo "${currentBuild.currentResult}"
HEADER_COLOR = "red"
}
And the value inside echo "${currentBuild.currentResult}" is SUCCESS.
Maybe I need to use this if-else in some other way ?
You if-else is ok, but the way you feed it with conditions is wrong.
It should be either:
if (currentBuild.currentResult == "SUCCESS") {
or (strange way)
if ("${currentBuild.currentResult}" == "SUCCESS") {
or (the hard way)
if ({currentBuild.currentResult}() == "SUCCESS") {
or (the harder way)
if ({currentBuild.currentResult}.call() == "SUCCESS") {
WHY?
Your original if would always evaluate to false, because you a comparing an inline-closure instance to "SUCCESS" which is never true.

Groovy code not returning true for folders

groovy code for jenkinspipeline to check for directory or not, is giving false even if it is directoy.
def folderExists(folderName) {
if(fileExists(folderName))
{
def file = new File(folderName)
echo "file/folder exists: "+folderName
echo "Is directry "+ file.isDirectory().toString()
return file.isDirectory()
}
else{
echo "Not found: "+folderName
return false
}
}
Any suggestions??
As far as I remember, Java's File object either won't work in sandboxed mode, or will run only on master node. If you want to check for folder on a slave node, you need to invoke Pipeline methods, or pure shell.
The below code works for me. You had echo instead of println, I'm not au fait with Groovy in Jenkins but in pure Groovy there is no echo that I am aware of. Also, i moved the statement def file = new File(folderName) to before the if decision.
def folderExists(folderName) {
def file = new File(folderName)
if(file.exists())
{
println "file/folder exists: "+folderName
println "Is directry "+ file.isDirectory().toString()
return file.isDirectory()
}
else{
println "Not found: "+folderName
return false
}
}
println folderExists('C:\\temp')

Groovy closure return value independent of code structure

I have some code in build.gradle
test {
doFirst {
def profile = System.getenv("...")
if (profile == "dev") {
println "1: if start"
// ...
println "2: if end"
}
}
}
and last line ("2: if end") executing anyway, even if profile not "dev"
Looks like groovy don't care about code structure: it simple return last line as result of closure
because if I modify code to:
test {
doFirst {
def profile = System.getenv("...")
if (profile == "dev") {
println "1: if start"
// ...
println "2: if end"
}
println "3: after if"
}
}
Then, this way, if profile not "dev", then all ok - after checking statement groovy execute line with "3: after if"
Is this bug or feature? :)
Yes, as commented, this only in the debugger - groovy works fine

How can I optimize switch-cases?

I've got a switch case like this:
def someString = 'hello1234bla'
// ...
switch (someString) {
case {it.contains('1234')}:
doSomething()
break
case {it.contains('2468')}:
doSomethingElse()
break
default:
throw new Exception("ERROR: Number not found")
break
}
This seems to be quite a lot of code for something so seemingly simple. All I want is to have different functions be executed when someString contains a specific substring. Is there no simpler way to do this, apart from maybe an if-else cascade?
This is pretty close to what the comments above suggest, but I'll write out a working example with indentation etc and perhaps it will be a bit more readable:
def someString = "hello1234bla"
def found = [
'1234': { println "do something" },
'2468': { println "do something else" }
].find { pattern, action ->
if (someString.contains(pattern)) { action(); true }
else false
}
if (!found) throw new Exception("ERROR: Number not found")
this executes the first matching action and throws an exception if no matches were found. If you need to execute an action for every match, replace the find call with a findAll call.
Another way of executing code based on a pattern in the string is the groovy String eachMatch method:
def someString = "hello1234blae"
someString.eachMatch(/1234/) { println "do something" }
someString.eachMatch(/2468/) { println "do something else" }
which uses regular expressions and runs the closure (the block in the curlies after the eachMatch call) once for every match. Thus:
someString.eachMatch(/e/) { println "runs twice" }
on the above string would execute twice as there are two 'e' characters in the string.

CliBuilder Arguments Are Empty

Here's a working example of my problem:
def cli = new CliBuilder(usage: 'cli-test -d <argument>')
cli.with {
h(longOpt: 'help', 'usage information')
d(longOpt: 'do-something', required: true, args: 1, 'Do Something' )
}
OptionAccessor options = cli.parse(args)
if(!options) {
return
}
// print usage if -h, --help, or no argument is given
if(options.h || options.arguments().isEmpty()) {
println options.arguments().size()
cli.usage()
return
} else if (options.d) {
println options.d
}
When I execute the script with the following:
groovy cli-test.groovy -d hello
I get this output:
0
usage: cli-test -d <argument>
-d,--do-something <arg> Do Something
-h,--help usage information
The 0 is my println is the arguments length. I can't get any options to work other than h. I'm not sure if I'm doing something wrong.
The reason is that there are no arguments! You've swallowed them all in options.
If you call
groovy cli-test.groovy -d hello foo
then the arguments() list is [foo]
The -d arg is automatically checked for because you made it required, so there's no need to test for it later on.
Not sure why this works this way, but removing:
|| options.arguments().isEmpty()
from the initial if check makes everything work.

Resources