Cmag
Cmag

Reputation: 15750

groovy to preserve quotes

Folks, Am looping over environment variables from Jenkins and am trying to build a list to then pass to ytt to then generate a Kubernetes yml.

How does one build a list which preserves the quotes? i.e. [foo.js, --delay, "40"]

def argList = []
argList.add(env.SCRIPT_NAME)
def args = env.SCRIPT_ARGS.split()
args.each { item ->
  def arg = ""
  if (item.isNumber()) {
    arg = item.toString()
  } else {
    arg = item
  }
  argList.add(arg)
}
sh "echo scriptAndArgs: ${argList} >> values.yml"

Currently, the output in the yml file is scriptAndArgs: [foo.js, --delay, 40]

Thanks

Upvotes: 0

Views: 415

Answers (2)

cfrick
cfrick

Reputation: 37008

Given you want to write YAML, which is a superset of JSON, your best bet is to just write a JSON array:

groovy.json.JsonOutput.toJson(["a", "b", 40]*.toString())
// ===> ["a","b","40"]

This approach also ensures proper quoting.

Another way, that works by accident and is build-in is inspect, which tries to write the data strucutre closer to what a human would input (this is no serialization by any means, but only for debugging and i'd not use it here)

["a", "b", 40]*.toString().inspect()
// ===> ['a', 'b', '40']

Upvotes: 2

Cmag
Cmag

Reputation: 15750

                def argString = "[" + env.SCRIPT_NAME

                def args = env.SCRIPT_ARGS.split()
                args.each { item ->
                    if (item.isNumber()) {
                        argString = argString + ',' + '"' + item + '"'
                    } else {
                        argString = argString + ',' + item
                    }
                }
                argString = argString + "]"
                sh "echo scriptAndArgs: '${argString}' >> values.yml"

Result being scriptAndArgs: [.../foo.js,--delay,"40"]

This also gets around Jenkins permissions the restrict doing things like list.inspect()

Upvotes: 0

Related Questions