How to parse the jenkins log at the postbuild and display text? - jenkins

In my script I have added "TestResult => Test description => Pass" and "TestResult => Test Description => Fail" as per the need.
As part of the post build , the lines start with TestResult and contains => should be displayed. I added post build groovy script but the result is not showing post build output.
Below is my sample execute shell
below is my post build groovy script
But in the result ,I am not seeing groovy file post build output at all
What am I missing?

This is indeed a bit tricky to find, but if you check out the last example in the Official Documentation of the Groovy Post Build plugin you will find it:
Example 10 (thanks to Frank Merrow).
Trivial, but hard to find the first time: Write a line to the job's Console > Output:
manager.listener.logger.println("I want to see this line in my job's output");
So just change your println statements to manager.listener.logger.println:
def result = ...
manager.listener.logger.println(result.toString());
manager.listener.logger.println("Sample Groovy Line");

Related

How to pass pipeline variables to post build gerrit message?

I have a Pylint running in a Jenkins pipeline. To implement it, I used Gerrit trigger plugin and Next Generation Warnings plugin. Everything is working as expected - Jenkins is joining the review, checks change with pylint and generates report.
Now, I'd like to post pylint score in a custom "Build successful" message. I wanted to pass the pylint score to a environment variable and use it in dedicated window for Gerrit plugin message.
Unfortunately no matter what I try, I cannot pass any "new" variable to the message. Passing parameters embedded in pipeline works (e.g. patchset number).
I created new environment variable in Configure Jenkins menu, tried exporting to shell, writing to it (via $VAR and env. syntax) but nothing works - that is, build message displays raw string like $VAR instead of what variable contains.
What should I do to pass local pylint score (distinct for every pipeline occurence) to the custom build message for Gerrit?
I don't think the custom message can be used for this. This is just supposed to be a static message.
They way I do this is to use the SSH command to perform the review. You can also achieve the same using the REST API.
First I run my linting and white space checking script that will generate a json file with the information I would like to pass to Gerrit. Next I send it to Gerrit using SSH. See below my pipeline script and an example json file.
As a bonus I have added the robot comments. This will now show up in your review as a remark from Jenkins that line 8 of my Jenkins file has a trailing white space. You can easily replace this with your lint result of you like or just ignore it and only put the message. It is easier to use a json file as it will make it easier to create multi line messages
node('master') {
sh """
cat lint_change.json | ssh -p ${env.GERRIT_PORT} ${env.GERRIT_HOST} gerrit review ${env.GERRIT_PATCHSET_REVISION} --json
"""
}
Example json file:
{
"labels": {
"Code-Style": "-1"
},
"message": "Lint Bot Review\nLint Results:\n Errors: 0\n Warnings: 0\n\nWhitespace results:\n Errors: 1",
"robot_comments": {
"Jenkinsfile": [
{
"robot_id": "lint-bot",
"line": "8",
"message": "trailing whitespace."
}
]
}
}
Alternatively, you may want to look at a new gerrit-code-review-plugin that should make this things even easier. However, I have not tried this yet.

Jenkins: attach multiple files in same email using emailext attachmentsPattern

We are trying to use Jenkins pipeline and using the following function:
emailext attachmentsPattern: "${env.LOG_FILE}" , "${env.PASSED_SOURCES_LOG}", "${env.FAILED_SOURCES_LOG}",
body: "Hi,\nThe nightly integration tests run is completed. Please find the log attached to this email.",
subject: "NIGHTLY INTEGRATION TESTS RUN - ${BUILD_NUMBER}",
to: "${env.EMAIL}"
Unfortunatelly I could not find a way to put these multiple files in same email. It outputs error.
Would someone know how to declare it properly?
Cheers,
The attachmentsPattern takes an Ant file pattern so perhaps something like:
**/*.log
would work. Or you could collect the files by reading them and writing them to a single file and then attach that.

file parameter in declarative pipeline

I am developing declarative pipeline and want to use file parameter to read its content, but its not working as expected
parameters{
file(fileLocation:'list.txt', description:'contains list of projects to be build')
}
I am getting following error
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 12: Invalid parameter "fileLocation", did you mean "description"? # line 12, column 14.
file(fileLocation:'release-list.txt', description:'contains list of projects to be build')
Following is another option mentioned for basic step plugin
readFile: Read file from workspace
Reads a file from a relative path (with root in current directory, usually workspace) and returns its content as a plain string.
file
Relative ( /-separated) path to file within a workspace to read.
Type: String
encoding (optional)
Type: String
its working in script step like
def myfile = readFile('list.txt')
echo "${myfile}"
But how to use it directly in declarative script as we used other basic steps like dir??
The correct arguments for the file parameter are name and description. So it should be:
file(name:'list.txt', description:'contains list of projects to be build')
However there's an open jenkins issue dating back from 2015 about the file parameter not working for pipelines, so I don't think even this will solve your issue. https://issues.jenkins-ci.org/browse/JENKINS-27413
Following syntax is working
parameters{
file name:'list.txt', description:'contains list of projects to be build'
}
But fileLocation parameter is not acceptable still.
Below syntax is available in Jenkins2 Up & Running book but its not working
parameters{
file(fileLocation:'list.txt', description:'contains list of projects to be build')
}
Till outstanding issues gets fixed, I believe we may have to stick to freestyle mode & handle things either in downstream pipeline job or within same job leveraging needy plugin feature.
Here is my attempt which looks to work file irrespective (yes supports Binaries as well) types : https://i.stack.imgur.com/vH7mQ.png
${list.txt} will point to right file in your case..
Take a look at the plug-in https://plugins.jenkins.io/file-parameters/.
This plug-in adds support for file parameters in your Jenkinsfile: https://plugins.jenkins.io/file-parameters/#plugin-content-usage-in-declarative-pipeline
parameters {
base64File 'small'
stashedFile 'large'
}
https://github.com/jenkinsci/file-parameters-plugin

Email-Ext objects in groovy script as file

My question is kind of a follow up of this:
How to place Email-Ext groovy script on the jenkins file system
Here is my situation:
I have a groovy script which constructs the email which will be send.
This works fine as long as I have the script directly written (the code) in:
Pre-send Script
If I take this script, place it in the Jenkins filesystem(...jenkins\email-templates) as: email-presend.groovy and I try to call it with:
<presendScript>${SCRIPT, script="email-presend"}</presendScript>
I get the error message, that I can't access the message object:
Script1.groovy: 1: expecting EOF, found 'or' # line 1, column 17.
Error in script or template: groovy.lang.MissingPropertyException: No such property: msg for class: Script1
Code on the line:
msg.addHeader("X-Priority", "1 (Highest)");
msg.addHeader("Importance", "High");
Am I missing something obvious, since I can't find any code snippet which did this?
I want to use the javax.mail.Message msg which is available if the code is directly in jenkins.
Unfortunately it seems like it's not possible according to this post:
Email-ext comment
Too bad :(

Getting Statistics to show up in TC

I've setup teamcity with my sln file and got the unit tests to show up with the CppUnit plugin that teamcity has. And I get test results in the TeamCity UI.
Now I'm trying to get trending reports to show up for my unit tests and code coverage.
As of code coverage, we're using vsinstr.exe and vsperfmon.exe which produces an XML file.
I'm not quite sure as of what steps I should be taking to make the trending reports and code coverage(not as important) to show up.
I've already seen this post, but the answer seems to require editing the build script, which I don't think would work for my case since I'm building through MSBuild and the .sln file, and the tests are being ran through that build.
So basically I'm trying to get the Statistics tab to show up, and I'm not sure where to begin.
Just add simple Powershell step into your build configuration. Something like this:
function TeamCity-SetBuildStatistic([string]$key, [string]$value) {
Write-Output "##teamcity[buildStatisticValue key='$key' value='$value']"
}
$outputFile = 'MetricsResults.xml'
$xml = [xml] (Get-Content $outputFile)
$metrics = $xml.CodeMetricsReport.Targets.Target[0].Modules.Module.Metrics
$metrics.Metric
| foreach { TeamCity-SetBuildStatistic "$($_.Name)" $_.Value.Replace(',', '') }
It uses XML output from FxCop Metrics. You have to update the script for your actual schema.

Resources