Last active
October 25, 2019 14:07
-
-
Save ababushk/aaf12f8deaef3987f9f2fd3b38f058c5 to your computer and use it in GitHub Desktop.
A function to cancel previous builds from the same GitLab merge request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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