I am trying to get the commitID/revision in changeSet in Jenkins. And here is my code:
The commitId I got is null but I can get the revision from the summary under the Changes page when the build finished.
def project = hudson.model.Hudson.instance.getItem(project_name)
def buildnum = some_number
build = project.getBuildByNumber(buildnum)
def upstreamBuilds = build.getUpstreamBuilds()
upstreamBuilds.each() { key, value ->
def prj = key;
def num = value;
build = prj.getBuildByNumber(num);
}
def changeSet = build.changeSet
if(changeSet != null) {
def hadChanges = false
changeSet.each() { cs ->
hadChanges = true
println(cs.author)
println(cs.commitId)
println(cs.msgAnnotated)
}
}
How can I get the correct commitId from changeSet of the build?
Related
Does anyone have an updated version of ceilfors answer that works for both AbstractProject and WorkflowJob?
This is the solution I came up with. It was tested on Jenkins 2.355
The test was run from the script console.
For testing purposes, I limited the test to one Freestyle (AbstractProject) and one Pipeline (WorkflowJob) job each. You would need to modify the code below.
I hope others find this useful
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import hudson.plugins.git.*
import jenkins.*
import jenkins.model.*
def modifyGitUrl(url) {
def updatedUrl = url.toString().replace("git#gitlab", "git#github")
// println "updatedUrl = ${updatedUrl}"
return updatedUrl
}
Jenkins.instance.getAllItems(Job.class).each {
project = it.getFullName()
if(project.toString().equals("PL_Quick_Testing") || project.toString().equals("A_Freestyle_Job")) {
try {
if (it instanceof AbstractProject){
def oldScm = it.scm
def newUserRemoteConfigs = oldScm.userRemoteConfigs.collect {
new UserRemoteConfig(modifyGitUrl(it.url), it.name, it.refspec, it.credentialsId)
}
def newScm = new GitSCM(newUserRemoteConfigs, oldScm.branches, oldScm.doGenerateSubmoduleConfigurations,
oldScm.submoduleCfg, oldScm.browser, oldScm.gitTool, oldScm.extensions)
it.scm = newScm
it.save()
println "Done"
} else if (it instanceof WorkflowJob) {
def oldScm = it.getTypicalSCM()
def definition = it.getDefinition()
String scriptPath = it.getDefinition().getScriptPath()
def newUserRemoteConfigs = oldScm.userRemoteConfigs.collect {
new UserRemoteConfig(modifyGitUrl(oldScm.userRemoteConfigs.url[0]), it.name, it.refspec, it.credentialsId)
}
def newScm = new GitSCM(newUserRemoteConfigs, oldScm.branches, oldScm.doGenerateSubmoduleConfigurations,
oldScm.submoduleCfg, oldScm.browser, oldScm.gitTool, oldScm.extensions)
def newDefinition = new org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition(newScm, scriptPath)
it.definition = newDefinition
it.save()
println "Done"
} else {
println("${project} has no SCM")
}
} catch (Exception e) {
// e.printStackTrace()
}
}
}
When build job jenkins generate changelog. But every commit message cut ~72 char with start in new line.
When i get message from currentBuild.changeSets in string set only first line of commit.
Jenkins pipeline:
node {
stage 'clean'
//step([$class: 'WsCleanup'])
stage 'git'
git url: 'https://***#***/***/****.git'
stage 'change'
passedBuilds = []
lastSuccessfulBuild(passedBuilds, currentBuild);
def changeLog = getChangeLog(passedBuilds)
echo "${changeLog}"
}
def lastSuccessfulBuild(passedBuilds, build) {
if ((build != null) && (build.result != 'SUCCESS')) {
passedBuilds.add(build)
}
}
#NonCPS
def getChangeLog(passedBuilds) {
def log = ""
for (int x = 0; x < passedBuilds.size(); x++) {
def currentBuild = passedBuilds[x];
def changeLogSets = currentBuild.changeSets
for (int i = 0; i < changeLogSets.size(); i++) {
def entries = changeLogSets[i].items
for (int j = 0; j < entries.length; j++) {
def entry = entries[j]
def hasSummaryMatch = (entry.msg =~ /(#[0-9]{4})/)
if (hasSummaryMatch) {
def numberTask = hasSummaryMatch[0][0]
numberTask = numberTask.replace('#', '')
def message = entry.msg
echo numberTask
log += "- [${numberTask}](......) ${message}\n"
}
}
}
}
return log;
}
If see changes by build commit have multiline
enter image description here
Summary
changelog (details)
#3157 очень длинный текст, который Jenkins разобьет на 2 строчки. Надо (details)
Commit 49b31854deb27bd13edf6fde33283cb1af8aab89 by fenix_ex
#3157 очень длинный текст, который Jenkins разобьет на 2 строчки. Надо
проверить правильную склейку строк при сборке обновления. А то очень не
красиво получается
how can i get full text commit?
p.s. git log show full message at 1 line.
I have the following two Classes which work just fine locally in groovy, but once I use them with Jenkins Shared Libraries I run into some issues.
./Template.groovy
class Template {
String arch
String type
def body = {}
Template(type, arch, body) {
this.arch = arch
this.type = type
this.body = body
}
}
./TemplateBook.groovy
import Template
class TemplateBook {
def templates = []
TemplateBook() {
def template = new Template("test", "lnx", { args -> sh('echo "Hello World!"'); sh("echo Test"); sh("echo $args")})
templates.push(template)
}
def getTemplate(type, arch) {
def template
for (def i = 0; i < templates.size(); i++) {
if (templates[i].arch == arch && templates[i].type == type) {
template = templates[i].getBody()
i = templates.size()
}
}
return template
}
}
Using the Template.body directly works just fine (locally and on Jenkins), but using the TemplateBook.getTemplate() only executes the first line of the closure (body).
def templateBook = new TemplateBook()
def body = templateBook.getTemplate("test", "lnx")
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = this
body("test")
Output:
Hello World!
def template = new Template("type", "arch", { args -> sh('echo "Hello World!"'); sh("echo Test"); sh("echo $args")})
def body2 = template.body
body2.resolveStrategy = Closure.DELEGATE_FIRST
body2.delegate = this
body2("test")
Output:
Hello World!
Test
test
I want to view the more recent X builds for several Jenkins jobs.
So if I wanted to show the last 5 builds for jobs 1-5 it would looks something like this:
status build time
-------------------------
pass job1#3 13:54
fail job1#2 13:05
fail job1#1 13:01
pass job5#1 12:17
pass job3#1 11:03
How can I accomplish this?
Notice the builds of the jobs are woven together so if one job has run many builds recently it will show up more than other jobs that haven't run as much.
Executing the following script in the Script Console (Manage Jenkins -> Script Console):
import java.text.SimpleDateFormat
def numHoursBack = 24
def dateFormat = new SimpleDateFormat("HH:mm")
def buildNameWidth = 30
def cutOfTime = System.currentTimeMillis() - numHoursBack * 3600 * 1000
SortedMap res = new TreeMap();
for (job in Jenkins.instance.getAllItems(BuildableItem.class)) {
for (build in job.getBuilds()) {
if (build.getTimeInMillis() < cutOfTime) {
break;
}
res.put(build.getTimeInMillis(), build)
}
}
def format = "%-10s%-${buildNameWidth}s%-10s"
println(String.format(format, "status", "build", "Time"))
for (entry in res.descendingMap().entrySet()) {
def build = entry.getValue()
println(String.format(format, build.getResult(), build.getFullDisplayName(), dateFormat.format(build.getTime())))
}
For me this gives:
status build Time
SUCCESS xxx #107393 17:53
SUCCESS xxx #107392 17:48
SUCCESS xxx #107391 17:43
null yyy #3030 17:38
SUCCESS xxx #107390 17:38
FAILURE zzz #3248 17:37
...
You might need to change the numHoursBack constant, it controls the number of hours back to look for builds. As well as the buildNameWidth which determines the column width of the build column (if you have really long job and build names you might need to extend this).
Here is a bit cleanup version of Jon S Groovy script. Also displaying worst build information.
import hudson.model.*;
import java.text.SimpleDateFormat;
//
// Settings
//
def numHoursBack = 24;
def dateFormat = new SimpleDateFormat("HH:mm");
def cutOfTime = System.currentTimeMillis() - numHoursBack * 3600 * 1000;
/**
* Basic build information.
*/
def printBuildInfo(finalizedBuild) {
String level = "INFO";
String result = finalizedBuild.getResult().toString();
switch (result) {
case "UNSTABLE":
level = "WARNING";
break;
case "FAILURE":
level = "ERROR";
break;
}
// basic info and URL
println(String.format(
"[%s] Build %s result is: %s.",
level,
finalizedBuild.getFullDisplayName(),
result
));
// pipe description from downstream
def description = finalizedBuild.getDescription();
if (description != null && !description.isEmpty()) {
println(description.replaceAll("<br>", ""));
}
return finalizedBuild;
}
/**
* Get recent build items.
*/
def getRencentBuilds(cutOfTime) {
SortedMap res = new TreeMap();
for (job in Jenkins.instance.getAllItems(BuildableItem.class)) {
for (build in job.getBuilds()) {
if (build.getTimeInMillis() < cutOfTime) {
break;
}
res.put(build.getTimeInMillis(), build);
}
}
return res;
}
/**
* Print build items.
*
* minResult - minimum to print
*/
def printBuilds(builds, minResult, dateFormat) {
def format = "%-10s %-8s %s";
Result worstResult = Result.SUCCESS;
def worstBuild = null;
// header
println(String.format(format, "status", "Time", "build"));
// list
for (entry in builds.descendingMap().entrySet()) {
def build = entry.getValue();
Result result = build.getResult();
if (result.isWorseThan(worstResult)) {
worstResult = result;
worstBuild = build;
}
if (result.isWorseOrEqualTo(minResult)) {
println(String.format(
format, build.getResult(), dateFormat.format(build.getTime()), build.getFullDisplayName()
));
}
}
return worstBuild;
}
def builds = getRencentBuilds(cutOfTime);
println ("\n\n----------------------\n Failed builds:\n");
def worstBuild = printBuilds(builds, Result.FAILURE, dateFormat);
println ("\n\n----------------------\n Worst build:\n");
if (worstBuild != null) {
printBuildInfo(worstBuild);
}
println ("\n\n----------------------\n All builds:\n");
printBuilds(builds, Result.SUCCESS, dateFormat);
Anyone have a Jenkins Pipeline script that can stuff all the changes since the previous successful build in a variable? I'm using git and a multibranch pipeline job.
Well I managed to cobble something together. I'm pretty sure you can iterate the arrays better but here's what I've got for now:
node('Android') {
passedBuilds = []
lastSuccessfulBuild(passedBuilds, currentBuild);
def changeLog = getChangeLog(passedBuilds)
echo "changeLog ${changeLog}"
}
def lastSuccessfulBuild(passedBuilds, build) {
if ((build != null) && (build.result != 'SUCCESS')) {
passedBuilds.add(build)
lastSuccessfulBuild(passedBuilds, build.getPreviousBuild())
}
}
#NonCPS
def getChangeLog(passedBuilds) {
def log = ""
for (int x = 0; x < passedBuilds.size(); x++) {
def currentBuild = passedBuilds[x];
def changeLogSets = currentBuild.rawBuild.changeSets
for (int i = 0; i < changeLogSets.size(); i++) {
def entries = changeLogSets[i].items
for (int j = 0; j < entries.length; j++) {
def entry = entries[j]
log += "* ${entry.msg} by ${entry.author} \n"
}
}
}
return log;
}
Based on the answer from CaptRespect I came up with the following script for use in the declarative pipeline:
def changes = "Changes:\n"
build = currentBuild
while(build != null && build.result != 'SUCCESS') {
changes += "In ${build.id}:\n"
for (changeLog in build.changeSets) {
for(entry in changeLog.items) {
for(file in entry.affectedFiles) {
changes += "* ${file.path}\n"
}
}
}
build = build.previousBuild
}
echo changes
This is quite useful in stage->when->expression parts to run a stage only when certain files were changed. I haven't gotten to that part yet though, I'd love to create a shared library from this and make it possible to pass it some globbing patterns to check for.
EDIT: Check the docs btw, in case you want to delve a little deeper. You should be able to convert all the object.getSomeProperty() calls into just entry.someProperty.
This is what I've used:
def listFilesForBuild(build) {
def files = []
currentBuild.changeSets.each {
it.items.each {
it.affectedFiles.each {
files << it.path
}
}
}
files
}
def filesSinceLastPass() {
def files = []
def build = currentBuild
while(build.result != 'SUCCESS') {
files += listFilesForBuild(build)
build = build.getPreviousBuild()
}
return files.unique()
}
def files = filesSinceLastPass()
There's the Changes Since Last Success Plugin that could help you with that.
For anyone using Accurev here is an adaptation of andsens answer. andsens answer can't be used because the Accurev plugin doesn't implement getAffectedFiles. Documentation for the AccurevTransaction that extends the ChangeLogSet.Entry class can be found at here.
import hudson.plugins.accurev.*
def changes = "Changes: \n"
build = currentBuild
// Go through the previous builds and get changes until the
// last successful build is found.
while (build != null && build.result != 'SUCCESS') {
changes += "Build ${build.id}:\n"
for (changeLog in build.changeSets) {
for (AccurevTransaction entry in changeLog.items) {
changes += "\n Issue: " + entry.getIssueNum()
changes += "\n Change Type: " + entry.getAction()
changes += "\n Change Message: " + entry.getMsg()
changes += "\n Author: " + entry.getAuthor()
changes += "\n Date: " + entry.getDate()
changes += "\n Files: "
for (path in entry.getAffectedPaths()) {
changes += "\n " + path;
}
changes += "\n"
}
}
build = build.previousBuild
}
echo changes
writeFile file: "changeLog.txt", text: changes
In order to return the changes as a list of strings, instead of just printing them, you may use this function (based on #andsens answer):
def getChangesSinceLastSuccessfulBuild() {
def changes = []
def build = currentBuild
while (build != null && build.result != 'SUCCESS') {
changes += (build.changeSets.collect { changeSet ->
(changeSet.items.collect { item ->
(item.affectedFiles.collect { affectedFile ->
affectedFile.path
}).flatten()
}).flatten()
}).flatten()
build = build.previousBuild
}
return changes.unique()
}