Skip to content

Instantly share code, notes, and snippets.

@ababushk
Last active October 25, 2019 14:07
Show Gist options
  • Save ababushk/aaf12f8deaef3987f9f2fd3b38f058c5 to your computer and use it in GitHub Desktop.
Save ababushk/aaf12f8deaef3987f9f2fd3b38f058c5 to your computer and use it in GitHub Desktop.
A function to cancel previous builds from the same GitLab merge request
def cancelBuilds(int builds_to_scan=300) {
def jobName = env.JOB_NAME
def currentMR = env.gitlabMergeRequestIid?.toInteger()
def currentRepoUrl = env.gitlabSourceRepoURL
def currentBuildNumber = env.BUILD_NUMBER?.toInteger()
def currentJob = Jenkins.instance.getItemByFullName(jobName)
def i = 0
for (def build : currentJob.builds) {
if (i > builds_to_scan) {
return null
}
def buildNumber = build.number?.toInteger()
if (buildNumber < currentBuildNumber) {
def buildMR = build.getEnvVars()["gitlabMergeRequestIid"]?.toInteger()
def buildRepoUrl = build.getEnvVars()["gitlabSourceRepoURL"]
if (build.isBuilding() && buildMR == currentMR && buildRepoUrl == currentRepoUrl) {
def executor = build.getExecutor()
def cause = new CauseOfInterruption.UserInterruption(
"New pre-commit build was started for current MR ${buildMR} " +
"(see ${this.script.env.BUILD_URL}), current build is aborted"
)
executor.interrupt(Result.ABORTED, cause)
return buildNumber
}
}
i++
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment