Tagging A Jenkins Build In Subversion

I have looked at several plugins from which you can tag builds in Jenkins, but I have not quite found the one I wanted. I decided to write a reusable piece of groovy script using the Scriptler plugin.
This script will tag a project if the tag does not exist, or retag a project if the tag exists, deleting the old tag. The plugins needed for this is:

For the script, I defined 3 parameters, JobName, TagTo, and Tag. JobName is the Jenkins job, TagTo is the destination folder not containing the actual tag. It usually ends in tags. Tag is the actual tag itself. An example would be JobName = "http://foo-svn-server/repos/GoldMine/MyProject/trunk", TagTo = "http://foo-svn-server/repos/GoldMine/MyProject/tags" and Tag = "Version 2.1.1.3".

import hudson.model.* 
import org.tmatesoft.svn.core.wc.*
import org.tmatesoft.svn.core.*
 
def job = Hudson.instance.getJob("$JobName") 
def tagFrom = job.scm.locations[0]
  
def svnRev = job.getLastBuild().getEnvironment()["SVN_REVISION"]
  
def psvn = hudson.scm.SubversionSCM.createSvnClientManager(job)

// build svn url containing tag
def svnDest = SVNURL.parseURIDecoded("$TagTo")
svnDest = svnDest.appendPath("$Tag", false)

 
// check if tag already exists
def wcClient = psvn.getWCClient()

try {
    def svnInfo = wcClient.doInfo(svnDest, SVNRevision.HEAD, SVNRevision.HEAD)
    def commitClient = psvn.getCommitClient()
      
    out.println "Tag_Project: path $svnDest alread exists."
    commitClient.doDelete([svnDest] as SVNURL[], "Retagged $tagFrom to $svnDest, deleted old tag."  )
    out.println "Tag_Project: deleted old tag.."  
}
catch(SVNException ex) {
  if (SVNErrorCode.RA_ILLEGAL_URL == ex.getErrorMessage().getErrorCode()) {
	out.println "Tag does not exist, will create tag."
      } else {
        out.println "Tag_Project : unknown error ${etErrorMessage().getErrorCode()}."
        throw ex
      }
}

// tag the project
def doCpy = psvn.getCopyClient()
def svnCpy = new SVNCopySource(SVNRevision.parse(svnRev), SVNRevision.parse(svnRev), SVNURL.parseURIEncoded("$tagFrom"))
doCpy.doCopy([svnCpy] as SVNCopySource[], svnDest, false, true, true, "tagged $Tag", null)
  
out.println "Tag_Project: tagged $svnDest at $svnRev"
Download PDF
This entry was posted in Jenkins and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *