Skip to content

Instantly share code, notes, and snippets.

@wburgers
Created May 29, 2018 12:01
Show Gist options
  • Save wburgers/c42c24d8c843088f1b1fdd027762701d to your computer and use it in GitHub Desktop.
Save wburgers/c42c24d8c843088f1b1fdd027762701d to your computer and use it in GitHub Desktop.
import hudson.model.*
import jenkins.model.Jenkins
def JobName = "Your PR-pipeline job name here"
def buildingJobs = Jenkins.instance.getAllItems(Job.class).findAll {
it.getName() == JobName && it.isBuilding()
}
def latestBuildForPR = []
buildingJobs.each { job->
allRuns = job._getRuns()
allRuns.each { item ->
if (!item.isBuilding()) return
def buildDescriptionPRnumber = item.getDescription().replaceAll("\\<.*?>","").split(' ')[1]
if (!latestBuildForPR.contains(buildDescriptionPRnumber)) latestBuildForPR << buildDescriptionPRnumber
else item.doStop()
}
}
@wburgers
Copy link
Author

Version 2

import hudson.model.*
import jenkins.model.Jenkins

def jobs = Jenkins.instance.getAllItems(org.jenkinsci.plugins.workflow.job.WorkflowJob).findAll {
    it.fullName.matches("(.*)<Your JobName Here>(.*)")
}

def latestBuildForPR = [];
jobs.each { job ->
    def buildPRnumber = job.getName()
    println "checking ${buildPRnumber}"
    for (build in job.builds) {
        if (!build.isBuilding()) continue
        if (!latestBuildForPR.contains(buildPRnumber)) {
            latestBuildForPR << buildPRnumber
        } else {
            println "Killing older build (${build.getNumber()}) for ${buildPRnumber}"
            build.doStop()
        }
    }
}
return null

@luukdobber
Copy link

luukdobber commented Sep 13, 2021

Version 3:

import hudson.model.*
import jenkins.model.Jenkins

def jobs = Jenkins.instance.getAllItems(org.jenkinsci.plugins.workflow.job.WorkflowJob).findAll {
    it.fullName.matches("(.*)<Your JobName Here>(.*)")
}

jobs.each { job ->
    def buildPRnumber = job.getName()
    println "Checking job ${job.fullName}"
  
    def latestBuildForPR = [];
    for (build in job.builds) {
        if (!build.isBuilding()) continue
        if (!latestBuildForPR.contains(buildPRnumber)) {
            println "  Build ${build.getNumber()} is the latest build for ${buildPRnumber}"
            latestBuildForPR << buildPRnumber
        } else {
            println "  Killing older build (${build.getNumber()}) for ${buildPRnumber}"
            build.doStop()
        }
    }
    println ""
}
return null

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment