Jenkins : Batch-Update Mercurial branch that is checked out

Updates for multiple jobs which branch will be checked out from Hg


When you have several jobs for one project (Continuous, Nightly, Test, Release, Dev, ...) you often have to change branches, especially when you have one branch per version.
It's quite annoying to change that by hand in each configuration.
For this script you just need to change the parts for the old branch name, new branch name and a regex pattern to match your jobs.

def oldBranch = "NAME_OF_OLD_BRANCH" // update this
def newBranch = "NAME_OF_NEW_BRANCH" // update this
def jobNamePattern = "YourRegExPattern" // update this
def freeStyleJobs = hudson.model.Hudson.instance.getItems(hudson.model.FreeStyleProject.class)
for (job in freeStyleJobs)
{
  def oldScm = job.getScm()
  if (oldScm.getType().indexOf("Mercurial") > -1 && job.name.matches(jobNamePattern))
  {
    if (oldScm.getBranch().equals(oldBranch))
    {
      print "Job '${job.name}' has branch '${oldBranch}' and will be updated to '${newBranch}'"
      // uncomment the next two lines to actually perform the operation. Else it simulates a dry-run
      //def newHgSCM = new  hudson.plugins.mercurial.MercurialSCM(oldScm.getInstallation(),  oldScm.getSource(), newBranch, oldScm.getModules(), oldScm.getSubdir(),  oldScm.getBrowser(), oldScm.isClean())
      //job.setScm(newHgSCM)      println "[OK]"  
    } else if (oldScm.getBranch().equals(newBranch))
    {
      println "Job '${job.name}' already is on branch '${newBranch}'"  
    } else
    {
      println "Job '${job.name}' is on branch '${oldScm.getBranch()}' and will not be updated" 
    }
  }
}