wvxvw
wvxvw

Reputation: 9478

How to define and call a function in Jenkinsfile?

I've seen a bunch of questions related to this subject, but none of them offers anything that would be an acceptable solution (please, no loading external Groovy scripts, no calling to sh step etc.)

The operation I need to perform is a oneliner, but pipeline limitations made it impossible to write anything useful in that unter-language...

So, here's minimal example:

@NonCPS
def encodeProperties(Map properties) {
    properties.collect { k, v -> "$k=$v" }.join('|')
}

node('dockerized') {
    stage('Whatever') {
        properties = [foo: 123, bar: "foo"]
        echo encodeProperties(properties)
    }
}

Depending on whether I add or remove @NonCPS annotation, or type declaration of the argument, the error changes, but it never gives any reason for what happened. It's basically random noise, that contradicts the reality of the situation (at times it would claim that some irrelevant object doesn't have a method encodeProperties, other times it would say that it cannot find a method encodeProperties with a signature that nobody was trying to call it with (like two arguments instead of one) and so on.

From reading the documentation, which is of disastrous quality, I sort of understood that maybe functions in general aren't serializable, and that is why you need to explain this explicitly to the Groovy interpreter... I'm sorry, this makes no sense, but this is roughly what documentation says.

Obviously, trying to use collect inside stage creates a load of new errors... Which are, at least understandable in that the author confesses that their version of Groovy doesn't implement most of the Groovy standard...

Upvotes: 4

Views: 6542

Answers (1)

Vitalii Vitrenko
Vitalii Vitrenko

Reputation: 10415

It's just a typo. You defined encodeProperties but called encodeProprties.

Upvotes: 2

Related Questions