-
Notifications
You must be signed in to change notification settings - Fork 411
/
CleanBuildHistory.groovy
48 lines (47 loc) · 1.6 KB
/
CleanBuildHistory.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import com.cloudbees.hudson.plugins.folder.AbstractFolder
import hudson.model.AbstractItem
import groovy.transform.Field
def jobName = "LatestJob1/AnotherOne/anotherFolder" // jobName can be set to a Job or a Folder. If a folder, it will clean all jobs in that folder
//jobName should be full job name from root if mutliple levels down(for example "Folder1/Folder2/Job")
def resetBuildNumber = false // If this is true, the build number will be set back to 1
@Field def cleanedJobsTotal = 0
removeBuilds(Jenkins.instance.getItemByFullName(jobName), resetBuildNumber)
def removeBuilds(job, resetBuildNumber) {
def buildTotal = 5
def count
if (job instanceof AbstractFolder) {
cleanedJobsLimit = 2 //Maximum number of jobs to clean in one run, useful for large systems or slow disks
for (subJob in job.getItems()) {
if(cleanedJobsTotal >= cleanedJobsLimit){
println "The cleaned jobs limit of " + cleanedJobsTotal + " has been reached. Exiting..."
return
}
else{
removeBuilds(subJob, resetBuildNumber)
}
}
} else if (job instanceof Job) {
count = 0
buildsDeleted = false
job.getBuilds().each {
if(count < buildTotal){
count++
}
else{
it.delete()
buildsDeleted = true
}
}
if(buildsDeleted){
println "Job " + job.name + " cleaned successfully.\n"
cleanedJobsTotal++
}
if (resetBuildNumber) {
job.nextBuildNumber = 1
job.save()
}
} else {
//Do nothing, next job
//throw new RuntimeException("Unsupported job type ${job.getClass().getName()}!")
}
}