Violation Comments to Bitbucket Server

Build Status

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.

Reporter Parser Notes
ARM-GCC CLANG
AndroidLint ANDROIDLINT
AnsibleLint FLAKE8 With -p
Bandit CLANG With bandit -r examples/ -f custom -o bandit.out --msg-template "{abspath}:{line}: {severity}: {test_id}: {msg}"
CLang CLANG
CPD CPD
CPPCheck CPPCHECK
CPPLint CPPLINT
CSSLint CSSLINT
Checkstyle CHECKSTYLE
CodeClimate CODECLIMATE
CodeNarc CODENARC
Detekt CHECKSTYLE With --output-format xml.
DocFX DOCFX
Doxygen CLANG
ERB CLANG With 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.
ESLint CHECKSTYLE With format: 'checkstyle'.
Findbugs FINDBUGS
Flake8 FLAKE8
FxCop FXCOP
GCC CLANG
Gendarme GENDARME
GoLint GOLINT
GoVet GOLINT Same format as GoLint.
GolangCI-Lint CHECKSTYLE With --out-format=checkstyle.
GoogleErrorProne GOOGLEERRORPRONE
HadoLint CHECKSTYLE With -f checkstyle
IAR IAR With --no_wrap_diagnostics
Infer PMD Facebook Infer. With --pmd-xml.
JCReport JCREPORT
JSHint JSLINT With --reporter=jslint or the CHECKSTYLE parser with --reporter=checkstyle
JUnit JUNIT It only contains the failures.
KTLint CHECKSTYLE
Klocwork KLOCWORK
KotlinGradle KOTLINGRADLE Output from Kotlin Gradle Plugin.
KotlinMaven KOTLINMAVEN Output from Kotlin Maven Plugin.
[Lint]() LINT A common XML format, used by different linters.
MSCpp MSCPP
Mccabe FLAKE8
MyPy MYPY
NullAway GOOGLEERRORPRONE Same format as Google Error Prone.
PCLint PCLINT PC-Lint using the same output format as the Jenkins warnings plugin, details here
PHPCS CHECKSTYLE With phpcs api.php --report=checkstyle.
PHPPMD PMD With phpmd api.php xml ruleset.xml.
PMD PMD
Pep8 FLAKE8
PerlCritic PERLCRITIC
PiTest PITEST
ProtoLint PROTOLINT
Puppet-Lint CLANG With -log-format %{fullpath}:%{line}:%{column}: %{kind}: %{message}
PyDocStyle PYDOCSTYLE
PyFlakes FLAKE8
PyLint PYLINT With pylint --output-format=parseable.
ReSharper RESHARPER
RubyCop CLANG With rubycop -f clang file.rb
SbtScalac SBTSCALAC
Scalastyle CHECKSTYLE
Simian SIMIAN
Sonar SONAR With 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.
Spotbugs FINDBUGS
StyleCop STYLECOP
SwiftLint CHECKSTYLE With --reporter checkstyle.
TSLint CHECKSTYLE With -t checkstyle
XMLLint XMLLINT
XUnit XUNIT It only contains the failures.
YAMLLint YAMLLINT With -f parsable
ZPTLint ZPTLINT

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 [email protected]: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}}
   """,

   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