Home

Awesome

Violation Comments to Bitbucket Server

It comments pull requests in Bitbucket Server (or Stash) with violations found in report files from static code analysis.

It uses Violation Comments to Bitbucket Server Lib and supports the same formats as Violations Lib.

Example of supported reports are available here.

Note: Using Bitbucket Cloud? You may have a look at Violation Comments to Bitbucket Cloud Command Line. This will only work with Bitbucket Server.

You can also do this with a command line tool.

A number of parsers have been implemented. Some parsers can parse output from several reporters.

ReporterParserNotes
ARM-GCCCLANG
AndroidLintANDROIDLINT
Ansible-LaterANSIBLELATERWith json format
AnsibleLintFLAKE8With -p
BanditCLANGWith bandit -r examples/ -f custom -o bandit.out --msg-template "{abspath}:{line}: {severity}: {test_id}: {msg}"
CLangCLANG
CPDCPD
CPPCheckCPPCHECKWith cppcheck test.cpp --output-file=cppcheck.xml --xml
CPPLintCPPLINT
CSSLintCSSLINT
CheckstyleCHECKSTYLE
CloudFormation LinterJUNITcfn-lint . -f junit --output-file report-junit.xml
CodeClimateCODECLIMATE
CodeNarcCODENARC
CoverityCOVERITY
DartMACHINEWith dart analyze --format=machine
Dependency CheckSARIFUsing --format SARIF
DetektCHECKSTYLEWith --output-format xml.
DocFXDOCFX
DoxygenCLANG
ERBCLANGWith erb -P -x -T '-' "${it}" | ruby -c 2>&1 >/dev/null | grep '^-' | sed -E 's/^-([a-zA-Z0-9:]+)/${filename}\1 ERROR:/p' > erbfiles.out.
ESLintCHECKSTYLEWith format: 'checkstyle'.
FindbugsFINDBUGS
Flake8FLAKE8
FxCopFXCOP
GCCCLANG
GHSGHS
GendarmeGENDARME
Generic reporterGENERICWill create one single violation with all the content as message.
GoLintGOLINT
GoVetGOLINTSame format as GoLint.
GolangCI-LintCHECKSTYLEWith --out-format=checkstyle.
GoogleErrorProneGOOGLEERRORPRONE
HadoLintCHECKSTYLEWith -f checkstyle
IARIARWith --no_wrap_diagnostics
InferPMDFacebook Infer. With --pmd-xml.
JACOCOJACOCO
JCReportJCREPORT
JSHintJSLINTWith --reporter=jslint or the CHECKSTYLE parser with --reporter=checkstyle
JUnitJUNITIt only contains the failures.
KTLintCHECKSTYLE
KlocworkKLOCWORK
KotlinGradleKOTLINGRADLEOutput from Kotlin Gradle Plugin.
KotlinMavenKOTLINMAVENOutput from Kotlin Maven Plugin.
LintLINTA common XML format, used by different linters.
MSBuildLogMSBULDLOGWith -fileLogger use .*msbuild\\.log$ as pattern or -fl -flp:logfile=MyProjectOutput.log;verbosity=diagnostic for a custom output filename
MSCppMSCPP
MccabeFLAKE8
MyPyMYPY
NullAwayGOOGLEERRORPRONESame format as Google Error Prone.
PCLintPCLINTPC-Lint using the same output format as the Jenkins warnings plugin, details here
PHPCSCHECKSTYLEWith phpcs api.php --report=checkstyle.
PHPPMDPMDWith phpmd api.php xml ruleset.xml.
PMDPMD
Pep8FLAKE8
PerlCriticPERLCRITIC
PiTestPITEST
ProtoLintPROTOLINT
Puppet-LintCLANGWith -log-format %{fullpath}:%{line}:%{column}: %{kind}: %{message}
PyDocStylePYDOCSTYLE
PyFlakesFLAKE8
PyLintPYLINTWith pylint --output-format=parseable.
ReSharperRESHARPER
RubyCopCLANGWith rubycop -f clang file.rb
SARIFSARIFv2.x. Microsoft Visual C# can generate it with ErrorLog="BuildErrors.sarif,version=2".
SbtScalacSBTSCALAC
ScalastyleCHECKSTYLE
SemgrepSEMGREPWith --json.
SimianSIMIAN
SonarSONARWith mvn sonar:sonar -Dsonar.analysis.mode=preview -Dsonar.report.export.path=sonar-report.json. Removed in 7.7, see SONAR-11670 but can be retrieved with: curl --silent 'http://sonar-server/api/issues/search?componentKeys=unique-key&resolved=false' | jq -f sonar-report-builder.jq > sonar-report.json.
SpotbugsFINDBUGS
StyleCopSTYLECOP
SwiftLintCHECKSTYLEWith --reporter checkstyle.
TSLintCHECKSTYLEWith -t checkstyle
ValgrindVALGRINDWith --xml=yes.
XMLLintXMLLINT
XUnitXUNITIt only contains the failures.
YAMLLintYAMLLINTWith -f parsable
ZPTLintZPTLINT

52 parsers and 79 reporters.

Missing a format? Open an issue here!

The pull request will be commented like this.

Pull request comment

Available in Jenkins here.

Notify Jenkins from Bitbucket Server

Merge

You must perform the merge before build. If you don't perform the merge, the reported violations will refer to other lines then those in the pull request. The merge can be done with a shell script like this.

echo ---
echo --- Merging from $FROM in $FROMREPO to $TO in $TOREPO
echo ---
git clone $TOREPO
cd *
git reset --hard $TO
git status
git remote add from $FROMREPO
git fetch from
git merge $FROM
git --no-pager log --max-count=10 --graph --abbrev-commit

Your build command here!

Job DSL Plugin

This plugin can be used with the Job DSL Plugin. Here is an example.

I trigger it with Pull Request Notifier for Bitbucket Server with URL like http://jenkins:8080/job/Bitbucket_Server_PR_Builder/buildWithParameters?${EVERYTHING_URL}, I report back to Bitbucket Server with HTTP Request Plugin and Conditional BuildStep Plugin.

job('Bitbucket_Server_PR_Builder') {
 concurrentBuild()
 quietPeriod(0)
 parameters {
  stringParam('PULL_REQUEST_TO_HTTP_CLONE_URL', '')
  stringParam('PULL_REQUEST_TO_HASH', '')
  stringParam('PULL_REQUEST_FROM_HTTP_CLONE_URL', '')
  stringParam('PULL_REQUEST_FROM_HASH', '')
  stringParam('PULL_REQUEST_TO_REPO_PROJECT_KEY', '')
  stringParam('PULL_REQUEST_TO_REPO_SLUG', '')
  stringParam('PULL_REQUEST_ID','')
 }
 steps {
  httpRequest {
   url("http://admin:admin@bitbucket:7990/rest/api/1.0/projects/\$PULL_REQUEST_TO_REPO_PROJECT_KEY/repos/\$PULL_REQUEST_TO_REPO_SLUG/pull-requests/\$PULL_REQUEST_ID/comments")
   consoleLogResponseBody(true)
   httpMode("POST")
   acceptType('APPLICATION_JSON')
   contentType('APPLICATION_JSON')
   requestBody('{ "text": "Building... \$BUILD_URL" }')
  }

  shell('''
echo ---
echo --- Merging from $FROM in $FROMREPO to $TO in $TOREPO
echo ---
git clone $PULL_REQUEST_TO_HTTP_CLONE_URL
cd *
git reset --hard $PULL_REQUEST_TO_HASH
git status
git remote add from $PULL_REQUEST_FROM_HTTP_CLONE_URL
git fetch from
git merge $PULL_REQUEST_FROM_HASH
git --no-pager log --max-count=10 --graph --abbrev-commit

./gradlew build
  ''')

  conditionalBuilder {
   runCondition {
    statusCondition {
     worstResult('SUCCESS')
     bestResult('SUCCESS')
    }
    runner {
     runUnstable()
    }
    conditionalbuilders {
     httpRequest {
      url("http://admin:admin@bitbucket:7990/rest/api/1.0/projects/\$PULL_REQUEST_TO_REPO_PROJECT_KEY/repos/\$PULL_REQUEST_TO_REPO_SLUG/pull-requests/\$PULL_REQUEST_ID/comments")
      consoleLogResponseBody(true)
      httpMode("POST")
      acceptType('APPLICATION_JSON')
      contentType('APPLICATION_JSON')
      requestBody('{ "text": "Success... \$BUILD_URL" }')
     }
    }
   }
  }

  conditionalBuilder {
   runCondition {
    statusCondition {
     worstResult('FAILURE')
     bestResult('FAILURE')
    }
    runner {
     runUnstable()
    }
    conditionalbuilders {
     httpRequest {
      url("http://admin:admin@bitbucket:7990/rest/api/1.0/projects/\$PULL_REQUEST_TO_REPO_PROJECT_KEY/repos/\$PULL_REQUEST_TO_REPO_SLUG/pull-requests/\$PULL_REQUEST_ID/comments")
      consoleLogResponseBody(true)
      httpMode("POST")
      acceptType('APPLICATION_JSON')
      contentType('APPLICATION_JSON')
      requestBody('{ "text": "Failure... \$BUILD_URL" }')
     }
    }
   }
  }
 }
 publishers {
  violationsToBitbucketServerRecorder {
   config {
    bitbucketServerUrl("http://bitbucket:7990")
    projectKey("\$PULL_REQUEST_TO_REPO_PROJECT_KEY")
    repoSlug("\$PULL_REQUEST_TO_REPO_SLUG")
    pullRequestId("\$PULL_REQUEST_ID")

    credentialsId('bitbucketservercredentials')

    minSeverity('INFO')
    maxNumberOfViolations(99999)
    createSingleFileComments(true)
    createCommentWithAllSingleFileComments(false)
    commentOnlyChangedContent(true)
    commentOnlyChangedContentContext(5)
    commentOnlyChangedFiles(true)
    keepOldComments(false)
    
    commentTemplate("""
    **Reporter**: {{violation.reporter}}{{#violation.rule}}
    
    **Rule**: {{violation.rule}}{{/violation.rule}}
    **Severity**: {{violation.severity}}
    **File**: {{violation.file}} L{{violation.startLine}}{{#violation.source}}
    
    **Source**: {{violation.source}}{{/violation.source}}
    
    {{violation.message}}
    """)

    violationConfigs {
     violationConfig {
      parser("FINDBUGS")
      reporter("Findbugs")
      pattern(".*/findbugs/.*\\.xml\$")
     }
     violationConfig {
      parser("CHECKSTYLE")
      reporter("Checkstyle")
      pattern(".*/checkstyle/.*\\.xml\$")
     }
    }
   }
  }  
 }
}

Pipeline Plugin

This plugin can be used with the Pipeline Plugin:

node {
 deleteDir()
 
 stage('Merge') {
  sh '''
  git clone git@github.com:tomasbjerre/violations-test.git .
  git checkout master
  git merge origin/feature/addingcrap
  '''
 }

 stage('Build') {
  sh '''
  ./build.sh || ls
  '''
 }

 stage('Static code analysis') {
  ViolationsToBitbucketServer([
   bitbucketServerUrl: 'http://localhost:7990/',
   commentOnlyChangedContent: true,
   commentOnlyChangedContentContext: 5,
   commentOnlyChangedFiles: true,
   createCommentWithAllSingleFileComments: false,
   createSingleFileComments: true,
   maxNumberOfViolations: 99999,
   keepOldComments: true,
   projectKey: 'PROJ', // Use environment variable here
   pullRequestId: '1', // Use environment variable here
   repoSlug: 'violations-test', // Use environment variable here
   
   credentialsId: 'theid',
   
   commentTemplate: """
   **Reporter**: {{violation.reporter}}{{#violation.rule}}
   
   **Rule**: {{violation.rule}}{{/violation.rule}}
   **Severity**: {{violation.severity}}
   **File**: {{violation.file}} L{{violation.startLine}}{{#violation.source}}
   
   **Source**: {{violation.source}}{{/violation.source}}
   
   {{violation.message}}
   """,
   
   ignorePaths: [
       [path: 'node_modules'],
       [path: '.yarn']
   ],

   violationConfigs: [
    // Many more formats available, check https://github.com/tomasbjerre/violations-lib
    [parser: 'FINDBUGS', pattern: '.*/findbugs/.*\\.xml\$', reporter: 'Findbugs'],
    [parser: 'CHECKSTYLE', pattern: '.*/checkstyle/.*\\.xml\$', reporter: 'Checkstyle']
   ]
  ])
 }
}

Developer instructions

Instructions for developers.

Plugin development

More details on Jenkins plugin development is available here.

There is a /build.sh that will perform a full build and test the plugin.

If you have release-permissions this is how you do a release:

mvn release:prepare release:perform