Get Subversion Revision For Workspace in Jenkins

You can use svnkit, a Java interface for Subversion supplied with the Subversion Plugin for Jenkins for getting Subversion information about jobs and various locations in a Subversion repository. I found that this approach was difficult to use when using a Groovy script in Scriptler to generate the default Subversion revision for a dynamic parameter. Let’s face it, my Java experience is not what my C# and VB .NET experience is, so svnkit can be a little intimidating. The following piece of code failed for getting a dynamic parameter:

This fails for a dynamic parameter…

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)

   . . .

The above snippet fails at the last line when used in a Scriptler script for a dynamic parameter. But what if I want to get the checked out revision for an arbitrary Jenkins workspace and do it at the beginning of a job before the SCM checkout? This is what I need to get the default value for a dynamic parameter. While I have had some luck with svnkit in the previous post Tagging A Jenkins Build In Subversion, this only seems to work when used as a job step while the job is running and has prepared the execution environment.

Here is a snippet that you can copy and paste into Scripter and this works for a dynamic parameter. We basically call svn from the command line and slurp up STDOUT. Just define the JobName parameter as a string and that will be the name of the job.

import hudson.model.*
def job = Hudson.instance.getJob(JobName)
def workSpace = job.getLastBuild().getEnvironment()["WORKSPACE"]
def pSvn = ("svn info \"$workSpace\"").execute()
def sout = new StringBuffer()
pSvn.consumeProcessOutput(sout, null)        
def currentTags = sout.toString().trim()
def mt = currentTags =~ /Revision\:\s+(\d+)/

return mt[0][1]  

If you want to get the revision directly from the repository as opposed to the workspace, check here.

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 *