How do I use the report plugin on (PMD, PHPCPD, checkstyle, Jdepend...) in a Jenkins pipeline? - jenkins

I'm using Jenkins 2.x with a Jenkinsfile to run a pipeline.
I have built a job using Jenkinsfile and I want to invoke the Analysis Collector Plugin so I can view the report.
Here is my current Jenkinsfile:
#!groovy
node {
stage 'Build '
echo "My branch is: ${env.BRANCH_NAME}"
sh 'cd gitlist-PHP && ./gradlew clean build dist'
stage 'Report'
step([$class: 'JUnitResultArchiver', testResults: 'gitlist-PHP/build/logs/junit.xml'])
step([$class: 'hudson.plugins.checkstyle.CheckStylePublisher', checkstyle: 'gitlist-PHP/build/logs/phpcs.xml'])
step([$class: 'hudson.plugins.dry.DryPublisher', CopyPasteDetector: 'gitlist-PHP/build/logs/phpcpd.xml'])
stage 'mail'
mail body: 'project build successful',
from: 'siregarpandu#gmail.com',
replyTo: 'xxxx#yyyy.com',
subject: 'project build successful',
to: 'siregarpandu#gmail.com'
}
I want to invoke invoke Checkstyle, Junit and DRY plugin from Jenkins. How do I configure these plugins in the Jenkinsfile? Do these plugins support pipelines?

The following configuration works for me:
step([$class: 'CheckStylePublisher', pattern: 'target/scalastyle-result.xml, target/scala-2.11/scapegoat-report/scapegoat-scalastyle.xml'])
For junit configuration is even easier:
junit 'target/test-reports/*.xml'

step([$class: 'hudson.plugins.checkstyle.CheckStylePublisher', checkstyle: 'gitlist-PHP/build/logs/phpcs.xml'])
Also according to source code repo, the argument 'checkstyle' should be named 'pattern'.
Repo:
https://github.com/jenkinsci/checkstyle-plugin/blob/master/src/main/java/hudson/plugins/checkstyle/CheckStylePublisher.java#L42

This is how I handle this:
PMD
stage('PMD') {
steps {
sh 'vendor/bin/phpmd . xml build/phpmd.xml --reportfile build/logs/pmd.xml --exclude vendor/ || exit 0'
pmd canRunOnFailed: true, pattern: 'build/logs/pmd.xml'
}
}
PHPCPD
stage('Copy paste detection') {
steps {
sh 'vendor/bin/phpcpd --log-pmd build/logs/pmd-cpd.xml --exclude vendor . || exit 0'
dry canRunOnFailed: true, pattern: 'build/logs/pmd-cpd.xml'
}
}
Checkstyle
stage('Checkstyle') {
steps {
sh 'vendor/bin/phpcs --report=checkstyle --report-file=`pwd`/build/logs/checkstyle.xml --standard=PSR2 --extensions=php --ignore=autoload.php --ignore=vendor/ . || exit 0'
checkstyle pattern: 'build/logs/checkstyle.xml'
}
}
JDepend
stage('Software metrics') {
steps {
sh 'vendor/bin/pdepend --jdepend-xml=build/logs/jdepend.xml --jdepend-chart=build/pdepend/dependencies.svg --overview-pyramid=build/pdepend/overview-pyramid.svg --ignore=vendor .'
}
}
The full example you can find here: https://gist.github.com/Yuav/435f29cad03bf0006a85d31f2350f7b4
Reference links
https://jenkins.io/doc/pipeline/steps/

It appears that the plugins need to be modified to support working as Pipeline Steps, so if they have not been updated, they don't work.
Here is a list of compatible plugins that have been updated:
https://github.com/jenkinsci/pipeline-plugin/blob/master/COMPATIBILITY.md
And here is the documentation about how the plugins need to be updated to support Pipelines:
https://github.com/jenkinsci/pipeline-plugin/blob/master/DEVGUIDE.md

Related

Modify env.BRANCH_NAME variable with branch-env.BRANCH_NAME in jenkinsfile for a multibranch pipeline project

I have created a multibranch pipeline project and thus created jenkinsfile and put that in dev branch.
In one of the stage, I have to run mvn sonar:sonar -Dsonar.scm.branch=branch-${env.BRANCH_NAME} but it's giving error as bad substitution branch-${env.BRANCH_NAME}.
I need branch-${env.BRANCH_NAME} as a branch-name so that at sonar i can see branch-dev at branches section in sonar dashboard.
if i use mvn sonar:sonar -Dsonar.scm.branch=env.BRANCH_NAME then it provides output but it will act as short-lived branch in sonar. but at sonar we want branch as long-lived branch.
!/usr/bin/env groovy
pipeline {
agent { label 'ol73_slave-jdk8u192-git' }
options {
timestamps()
timeout(time: 2, unit: 'HOURS')
buildDiscarder(logRotator(numToKeepStr: '10'))
disableConcurrentBuilds()
}
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Unit Test and Code Scan') {
steps {
echo "*****JUnit Tests, JaCoCo Code Coverage, & SonarQube Code Qualiy Scan*****"
withMaven(jdk: 'jdk8_u192', maven: 'maven-3.3.9', mavenSettingsConfig: '79ecf9bd-8cbc-4d5e-b7d1-200241e16b52') {
sh '''
cd DARC
mvn clean package sonar:sonar -Dsonar.host.url=***** -Dsonar.login=******* -Dsonar.exclusions=file:**/src/test/** -B -Pcoverage -Dsonar.branch.name=branch-${env.BRANCH_NAME}
'''
}
}
}
}
}
In groovy Strings are encapsulated in single quotes '' and GStrings in double quotes ""
In order to do interpolation you need to be using GStrings. In your example, this should simply be
sh """
cd DARC
mvn clean package sonar:sonar -Dsonar.host.url=***** -Dsonar.login=******* -Dsonar.exclusions=file:**/src/test/** -B -Pcoverage -Dsonar.branch.name=branch-${env.BRANCH_NAME}
"""

jenkins pipeline, unstash from a sub job

I have a separate build pipeline that uses jenkinsfile to build the code.
I trigger it from a deploy pipeline and want to get build results.
The reason for this is that devs can define build steps but deploy is out of there control.
Here's a sample code in jenkins job builder:
- job:
name: Build and Deploy
project-type: pipeline
dsl: |
node {
stage('Build') {
# that job does stash inside a jenkinsfile
build job: "Build"
sh 'cp -rv "../Build/dist/" ./' # this is a workaround
stash includes: 'dist/*.zip', name: 'archive'
}
stage('Deploy') {
unstash 'archive'
sh "..."
}
}
So how can I unstash code stash-ed in a sub-job?
P.S.: there's also a workaround with artefacts:
In a sub-job:
archiveArtifacts artifacts: '*.zip', fingerprint: true
main DSL:
dsl: |
node {
def build_job_number = 0
def JENKINS = "http://127.0.0.1:8080"
stage('Build') {
def build_job = build job: "Build"
build_job_number = build_job.getNumber()
}
stage('Deploy') {
sh "wget -c --http-user=${USER} --http-password=${TOKEN} --auth-no-challenge ${JENKINS}/job/Build/${build_job_number}/artifact/name.zip"
sh "..."
}
}
The issue here is that API token is required.
If you go with archiveArtifacts you can use copyArtifacts to complement it.
As far as I know stash/unstash only work within the same job, so your other option would be to tick the Preserve stashes from completed builds in the pipeline's configuration so you can re-use them.

Cannot access recordIssues in Jenkins Pipeline using Warnings Next Generation

I have a simple Jenkinsfile with a recordIssues step. The relevant code looks like this:
step([
$class: 'recordIssues',
aggregatingResults: true,
enabledForFailure: true,
tools: [pyLint()]
])
I have installed the latest version of the Warnings Next Generation plugin (https://plugins.jenkins.io/warnings-ng) but I run into the following issue:
[Pipeline] step
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
java.lang.UnsupportedOperationException: no known implementation of interface jenkins.tasks.SimpleBuildStep is named recordIssues
at org.jenkinsci.plugins.structs.describable.DescribableModel.resolveClass(DescribableModel.java:478)
Is it somehow possible to check that the extension is installed correctly?
This is my working version for a Python project CI configuration in Jenkins to use JUnit, PEP8, Pylint and Coverage reports:
...
stage('Test: Run') {
steps {
// Run my project tests.
sh 'coverage run manage.py tests'
// Dump coverage metrics to XML.
sh 'coverage xml'
// Run Pylint.
sh 'pylint --rcfile=.pylintrc my_project > reports/pylint.report'
// Run Pycodestyle (PEP8 checks).
sh 'pycodestyle my_project > reports/pep8.report'
}
post {
always{
// Generate JUnit, PEP8, Pylint and Coverage reports.
junit 'reports/*junit.xml'
recordIssues(
tool: pep8(pattern: 'reports/pep8.report'),
unstableTotalAll: 200,
failedTotalAll: 220
)
recordIssues(
tool: pyLint(pattern: 'reports/pylint.report'),
unstableTotalAll: 20,
failedTotalAll: 30
)
cobertura coberturaReportFile: 'reports/coverage.xml'
}
}
}
...
It works with Cobertura plugin, JUnit plugin and Warnings Next Generation. Python packages I used are the traditional coverage and pylint and for PEP8 I used pycodestyle.
Hope this helps somebody else, as finding good examples of this Jenkinsfile stuff is not easy.
Just for the record:
Jenkins v2.204.2
Jenkins Warnings Next Generation Plugin v8.0.0
stage('Static Analysis') {
steps {
recordIssues(
tool: pyLint(pattern: '**/pylint.out'),
unstableTotalAll: 100,
)
}
This works for me (Jenkins ver. 2.164.1):
stage('Static Analysis') {
recordIssues(
tool: pyLint(pattern: '**/pylint.out'),
unstableTotalAll: '100',
)
recordIssues(
tool: pep8(pattern: '**/pep8.out'),
unstableTotalAll: '100',
)
}

No such DSL method 'publishHTML' found among steps

I have a jenkins DSL step that runs my python nosetests and creates a unittest coverage report.
Here is my jenkins stage.
stage ('Unit Tests') {
steps {
sh """
#. venv/bin/activate
export PATH=${VIRTUAL_ENV}/bin:${PATH}
make unittest || true
"""
}
post {
always {
junit keepLongStdio: true, testResults: 'report/nosetests.xml'
publishHTML target: [
reportDir: 'report/coverage',
reportFiles: 'index.html',
reportName: 'Coverage Report - Unit Test'
]
}
}
}
I get this error -
java.lang.NoSuchMethodError: No such DSL method 'publishHTML' found among steps.
How can I fix this error? I got this piece of code from a different repository.
The publishHTML method is provided by the HTLMPublisher Jenkins plugin. After installing the plugin on the primary Jenkins server, the publishHTML method will be available in the Jenkins Pipeline for both scripted and declarative syntax.

Get warnings from PMD with Jenkins Pipeline

How get number of warnings from PMD with Jenkins Pipeline?.
I have tried but can not find a way to fix this
Here is my Code Analysis block stage:
stage('CAT') {
step([$class: 'hudson.plugins.checkstyle.CheckStylePublisher', checkstyle: '**/target/checkstyle-result.xml'])
step([$class: 'hudson.plugins.pmd.PmdPublisher', checkstyle: '**/target/pmd.xml'])
}
This is how I handle PMD in Jenkinfile (PHP project):
stage('PMD') {
steps {
sh 'vendor/bin/phpmd . xml build/phpmd.xml --reportfile build/logs/pmd.xml --exclude vendor/ || exit 0'
pmd canRunOnFailed: true, pattern: 'build/logs/pmd.xml'
}
}
Reference links
https://jenkins.io/doc/pipeline/steps/
https://jenkins.io/doc/pipeline/steps/pmd/

Resources