Getting Jenkins to tag using extracted version number

Getting Jenkins to tag using extracted version number

15 November 2014

I feel like I'm going against the grain here as I found this simple thing difficult to implement. I wanted Jenkins-CI to:

  • Publish a Nodejs package to npm
  • Tag using the Package.json version number.

Publishing to a local NPM was easy enough. I added a custom builder Execute Windows Command.

cmd /c npm set registry http://npm
cmd /c npm publish

Tagging using the version number from Package.json was not obvious. I wanted to link the Package.json version number with the tag name.

For example, the following Package.json would result in tag 0.0.1-beta being created.

{
  "name":"ColsProject",
  "version":"0.0.1-beta"

I achieved this by creating a grunt task called ci:setup which would produce a transient properties file for jenkins called build.properties.

The following custom grunt task creates the build.properties.

grunt.registerTask('ci:setup',function()  {
    fs.writeFile('build.properties','PKG_VERSION=' + pkg.version, this.async());
});

The created build.properties looks like

PKG_VERSION=0.0.1-beta

I then configured my job Inject Variables builder to use build.properties.

The is the //builders section of config.xml for the job.

See //builders/EnvInjectBuilder element.

<builders>
  <!-- Uses a local NPM registry, installs dependences and runs grunt tasks -->
  <hudson.tasks.BatchFile>
    <command>cmd /c npm set registry http://local-npm
cmd /c npm install -d
cmd /c grunt ci:setup build test</command>
  </hudson.tasks.BatchFile>
  <EnvInjectBuilder plugin="envinject@1.89">
    <info>
      <propertiesFilePath>$WORKSPACE/build.properties</propertiesFilePath>
    </info>
  </EnvInjectBuilder>
  <hudson.tasks.BatchFile>
    <command>cmd /c npm set registry http://local-npm
cmd /c npm publish</command>
  </hudson.tasks.BatchFile>
</builders>
<publishers>
  <hudson.plugins.git.GitPublisher plugin="git@2.2.1">
    <configVersion>2</configVersion>
    <pushMerge>false</pushMerge>
    <pushOnlyIfSuccess>true</pushOnlyIfSuccess>
    <tagsToPush>
      <hudson.plugins.git.GitPublisher_-TagToPush>
        <targetRepoName>origin</targetRepoName>
        <tagName>$PKG_VERSION</tagName>
        <tagMessage>Published by Jenkins-CI.</tagMessage>
        <createTag>true</createTag>
        <updateTag>false</updateTag>
      </hudson.plugins.git.GitPublisher_-TagToPush>
    </tagsToPush>
  </hudson.plugins.git.GitPublisher> 
</publishers>
CI Jenkins-CI