salt-pepper
salt-pepper

Reputation: 125

How to read a command from package.json from a Jenkins file

I have a package.json

"scripts": {
"pact:tests": <script>
}

I need to check if pact:tests exists in the package.json from JenkinsFile(Groovy). If it exsits run pact test else skip it.

Tried a couple of ways

def pactExists = sh "grep \"pact:tests\" package.json | wc -l"
if(pactExists > 0)
   run pact
else
  skip

But the above code return pactExists = null

Try 2 :

def pactExists2 = sh "${grep pact:tests package.json}"

But this directly runs the command I think

Try 3 :

def packageJSON = readJSON file: 'package.json'
def pactExists = packageJSON.scripts.pact:tests

But I get an error for using ':' after pact:

Is there a way to save the output in some var?

Upvotes: 0

Views: 1001

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42234

If you want to capture the result of the sh step, you need to set returnStdout option to true, e.g.

def pactExists = sh(script: "grep \"pact:tests\" package.json | wc -l", returnStdout: true)

Alternatively, if you want to use readJSON step, then you would need to define a key using quotes, e.g.

def pactExists = packageJSON.scripts.'pact:tests'

Upvotes: 1

Related Questions