Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract version from package.json with bash inside jenkins pipeline

Script in package.json:

"scripts": {
    "version": "echo $npm_package_version"
  },

One of the stage in Jenkins pipeline:

stage('Build'){
    sh 'npm install'
    def packageVersion = sh 'npm run version'
    echo $packageVersion
    sh 'VERSION=${packageVersion} npm run build'
}

I got version from npm script output, but following line

echo $packageVersion

return null

Is packageVersion value not correctly assigned?

Edited: when using Pipeline Utility Steps with following code

stage('Build'){
    def packageJSON = readJSON file: 'package.json'
    def packageJSONVersion = packageJSON.version
    echo packageJSONVersion
    sh 'VERSION=${packageJSONVersion}_${BUILD_NUMBER}_${BRANCH_NAME} npm run build'
        }

I get

[Pipeline] echo
1.1.0
[Pipeline] sh
[...] Running shell script + VERSION=_16_SOME_BRANCH npm run build

So I am able to extract version, but still cannot pass it when running script

like image 469
gka Avatar asked Aug 04 '18 08:08

gka


2 Answers

For my it this:

sh(script: "grep \"version\" package.json | cut -d '\"' -f4 | tr -d '[[:space:]]'", returnStdout: true)
like image 53
Felipe ardila Avatar answered Oct 25 '22 09:10

Felipe ardila


The sh step by default returns nothing, so packageVersion should be null.

To return the output of the executed command, use it like this:

sh(script: 'npm run version', returnStdout: true')

Actually, I am wondering, why echo $packageVersion doesn't fail with an error, as this variable is not defined, but should be echo packageVersion.

like image 8
StephenKing Avatar answered Oct 25 '22 07:10

StephenKing