Wednesday, September 25, 2019

Automatic NPM version increment upon Jenkins build



You have a node javascript package, that is automatically built using a Jenkins job.
The Jenkins job is automatically triggered upon push of updates to GIT.

That's very nice, but you want to automatically increment the version in the library package.json, without you manually handling this upon every push.



This can be done using Jenkins pipeline job. The job should do the following:
  1. Build the package - to ensure that it has no compilation and tests errors
  2. Update the version in package.json, and push the update back to GIT
  3. Rebuild the package, this time with the updated version
  4. Publish the package

But wait, what do you think would happen once the job updates the GIT in step #2?
We will get an infinite loop, since the push would reactivate the build job.
To avoid this, we need to identify if the last push was made by the Jenkins, and if so, do not update the version. So the updated steps are:

  1. Build the package - to ensure that it has no compilation and tests errors
  2. Check the last push, and if it was made by Jenkins, abort.
  3. Update the version in package.json, and push the update back to GIT
  4. Rebuild the package, this time with the updated version
  5. Publish the package

Checking the Last GIT Push

This pipeline groovy script checks the last commit.
The commit and publish step will run only if the last commit does not include the comment: 'update_version_by_jenkins'.
def gitUrl = 'git@bitbucket.org:myrepo/mygit.git'
def lastCommit = ''
sshagent (credentials: ['1938eb47-e7e8-4fed-b88c-87561e128345']) {
  sh('git config --global user.name "Jenkins"')
  sh('git config --global user.email "jenkins@company.com"')
  sh('git checkout master')
  sh('git pull origin master')
  sh('git checkout HEAD --force')
  lastCommit = sh([script: 'git log -1', returnStdout: true])
}

if (lastCommit.contains('update_version_by_jenkins')){
  echo "self triggered build, no need to update version"
} else {
  CommitAndPublish()
}

Update the Version

Update of the version is handled by npm.
In this case we update the third part of the version.
For example: version 1.2.29 will be updated to 1.2.30.

sh '/usr/bin/npm version patch'

Push the Updated package.json

Now we need to push the changes back to GIT.
sh "git add package.json"
sh "git commit -m update_version_by_jenkins"

sshagent (credentials: ['1938eb47-e7e8-4fed-b88c-87561e128345']) {
  sh('git push origin master')
}

Notice

The same logic can be used in a limited mode, for example: increment the version only upon merge to the master branch.

No comments:

Post a Comment