首页 > 解决方案 > 如何从 Jenkins 文件中读取 package.json 中的命令

问题描述

我有一个 package.json

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

我需要检查 JenkinsFile(Groovy) 的 package.json 中是否存在 pact:tests。如果它存在运行协议测试,则跳过它。

尝试了几种方法

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

但是上面的代码返回 pactExists = null

尝试 2:

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

但这直接运行我认为的命令

尝试 3:

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

但是我收到一个错误,因为在协议之后使用 ':':

有没有办法将输出保存在某个变量中?

标签: groovyjenkins-pipelinejenkins-groovy

解决方案


如果要捕获sh步骤的结果,则需要将returnStdout选项设置为true,例如

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

或者,如果您想使用readJSONstep,那么您需要使用引号定义一个键,例如

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

推荐阅读