We would like to analyze the build history in a Jenkins job. We don't want to approve any dangerous signatures, so the logic should be implemented as a step in a Jenkins Shared Library. We use folders and multibranch jobs, so the mechanism has to analyze items recursively.
How to implement it?
To collect all builds the following code could be used.
import hudson.model.Job
import hudson.model.Run
import jenkins.model.Jenkins
List<Map<String, Object>> call() {
def builds = []
for (def job in findAllJobs()) {
for (def build in job.builds) {
builds << [
name: build.parent.name,
fullName: build.parent.fullName,
result: build.result?.toString(),
number: build.number as String,
date: build.time,
timestamp: build.timeInMillis,
url: "${build.parent.absoluteUrl}${build.number}/"
]
}
}
return builds
}
List<Job> findAllJobs() {
def jobs = []
jobs.addAll(jenkins.getItems(Job))
def folderClass = loadClass('com.cloudbees.hudson.plugins.folder.AbstractFolder')
for (def folder in jenkins.getItems(folderClass)) {
jobs.addAll(findNestedJobs(folder, folderClass))
}
return jobs
}
List<Job> findNestedJobs(def folder, Class<?> folderClass) {
def jobs = []
for (def item in folder.items) {
if (folderClass.isAssignableFrom(item.class)) {
jobs.addAll(findNestedJobs(item, folderClass))
} else if (item instanceof Job) {
jobs << item
}
}
return jobs
}
Class<?> loadClass(String className) {
return Class.forName(className, true, jenkins.pluginManager.uberClassLoader)
}
Jenkins getJenkins() {
return Jenkins.get()
}
It returns for every build:
<folder>/<job>/<branch name|PR number>
)branch name|PR number
)SUCCESS
, FAILURE
etc.)java.util.Date
)long
)If for example only builds executed within 24 hours must be executed, two approach could be used:
The second option is better because it doesn't force the logic to iterate through old builds.