Git Product home page Git Product logo

violation-comments-to-gitlab-plugin's Introduction

Violation Comments to GitLab Plugin

This is a Jenkins plugin for Violation Comments to GitLab Lib. This plugin will find report files from static code analysis and comment GitLab pull requests with the content.

An alternative is also to have violations-command-line convert the violations to CodeClimate format and upload that to GitLab. It is explained in readme of violations-command-line.

Available in Jenkins here.

Example of supported reports are available here.

There is a complete running example available here: https://github.com/tomasbjerre/jenkins-configuration-as-code-sandbox

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
Ansible-Later ANSIBLELATER With json format
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 With cppcheck test.cpp --output-file=cppcheck.xml --xml
CPPLint CPPLINT
CSSLint CSSLINT
Checkstyle CHECKSTYLE
CloudFormation Linter JUNIT cfn-lint . -f junit --output-file report-junit.xml
CodeClimate CODECLIMATE
CodeNarc CODENARC
Coverity COVERITY
Dart MACHINE With dart analyze --format=machine
Dependency Check SARIF Using --format SARIF
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
GHS GHS
Gendarme GENDARME
Generic reporter GENERIC Will create one single violation with all the content as message.
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.
JACOCO JACOCO
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.
MSBuildLog MSBULDLOG With -fileLogger use .*msbuild\\.log$ as pattern or -fl -flp:logfile=MyProjectOutput.log;verbosity=diagnostic for a custom output filename
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
SARIF SARIF v2.x. Microsoft Visual C# can generate it with ErrorLog="BuildErrors.sarif,version=2".
SbtScalac SBTSCALAC
Scalastyle CHECKSTYLE
Semgrep SEMGREP With --json.
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
Valgrind VALGRIND With --xml=yes.
XMLLint XMLLINT
XUnit XUNIT It only contains the failures.
YAMLLint YAMLLINT With -f parsable
ZPTLint ZPTLINT

52 parsers and 79 reporters.

Missing a format? Open an issue here!

There is also:

Notify Jenkins from GitLab

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!

Screenshots

Comments can be made on the diff with one comment per violation createSingleFileComments.

Example comment on diff

Or one big comment can be made, createCommentWithAllSingleFileComments.

Example comment

Job DSL Plugin

This plugin can be used with the Job DSL Plugin. Here is an example using Generic Webhook Trigger plugin, HTTP Request Plugin and Conditional BuildStep Plugin.

job('GitLab_MR_Builder') {
 concurrentBuild()
 quietPeriod(0)
 parameters {
  stringParam('MERGE_REQUEST_TO_URL', '')
  stringParam('MERGE_REQUEST_FROM_URL', '')
  stringParam('MERGE_REQUEST_TO_BRANCH', '')
  stringParam('MERGE_REQUEST_FROM_BRANCH', '')
 }
 scm {
  git {
   remote {
    name('origin')
    url('$MERGE_REQUEST_TO_URL')
   }
   remote {
    name('upstream')
    url('$MERGE_REQUEST_FROM_URL')
   }
   branch('$MERGE_REQUEST_FROM_BRANCH')
   extensions {
    mergeOptions {
     remote('upstream')
     branch('$MERGE_REQUEST_TO_BRANCH')
    }
   }
  }
 }
 triggers {
  genericTrigger {
   genericVariables {
    genericVariable {
     key("MERGE_REQUEST_TO_URL")
     value("\$.object_attributes.target.git_http_url")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("MERGE_REQUEST_FROM_URL")
     value("\$.object_attributes.source.git_http_url")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("MERGE_REQUEST_TO_BRANCH")
     value("\$.object_attributes.target_branch")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("MERGE_REQUEST_FROM_BRANCH")
     value("\$.object_attributes.source_branch")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("PROJECT_ID")
     value("\$.object_attributes.target_project_id")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("MERGE_REQUST_ID")
     value("\$.object_attributes.id")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("MR_OBJECT_KIND")
     value("\$.object_kind")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("MR_OLD_REV")
     value("\$.object_attributes.oldrev")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("MR_ACTION")
     value("\$.object_attributes.action")
     expressionType("JSONPath")
     regexpFilter("")
    }
   }
   regexpFilterText("\$MR_OBJECT_KIND \$MR_ACTION \$MR_OLD_REV")
   regexpFilterExpression("^merge_request\\s(update\\s.{40}\$|open.*)")
  }
 }
 steps {
  httpRequest {
   url("http://gitlab:880/api/v3/projects/\$PROJECT_ID/merge_requests/\$MERGE_REQUST_ID/notes?private_token=AvAkp6HtUvzpesPypXSk")
   consoleLogResponseBody(true)
   httpMode("POST")
   requestBody('body=Building... %20\$BUILD_URL')
   }
 
  shell('./gradlew build')
 
  conditionalBuilder {
   runCondition {
    statusCondition {
     worstResult('SUCCESS')
     bestResult('SUCCESS')
    }
    runner {
     runUnstable()
    }
    conditionalbuilders {
     httpRequest {
      url('http://gitlab:880/api/v3/projects/\$PROJECT_ID/merge_requests/\$MERGE_REQUST_ID/notes?private_token=AvAkp6HtUvzpesPypXSk')
      consoleLogResponseBody(true)
      httpMode('POST')
      requestBody('body=SUCCESS%20\$BUILD_URL')
     }
    }
   }
  }
 
  conditionalBuilder {
   runCondition {
    statusCondition {
     worstResult('FAILURE')
     bestResult('FAILURE')
    }
    runner {
     runUnstable()
    }
    conditionalbuilders {
     httpRequest {
      url('http://gitlab:880/api/v3/projects/\$PROJECT_ID/merge_requests/\$MERGE_REQUST_ID/notes?private_token=AvAkp6HtUvzpesPypXSk')
      consoleLogResponseBody(true)
      httpMode('POST')
      requestBody('body=FAIL%20\$BUILD_URL')
     }
    }
   }
  }
 }
 publishers {
  violationsToGitLabRecorder {
   config {
    gitLabUrl("http://gitlab:880/")
    projectId("\$PROJECT_ID")
    mergeRequestIid("\$MERGE_REQUST_IID")
    
    // Only specify proxy if you need it
    proxyUri('')
    proxyCredentialsId('') // A username/password credential
 
    commentOnlyChangedContent(true)
    commentOnlyChangedContentContext(0)
    commentOnlyChangedFiles(true)
    createSingleFileComments(true)
    createCommentWithAllSingleFileComments(true)
    minSeverity('INFO')
    maxNumberOfViolations(99999)
    
    //You may want this when troubleshooting things
    enableLogging(true)
    
 
    apiTokenCredentialsId("gitlabtoken") // A secret text credential
    apiTokenPrivate(true)
    authMethodHeader(true)
    ignoreCertificateErrors(true)
    
    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

Here is an example pipeline that will merge, run unit tests, run static code analysis and finally report back to GitLab. It requires the GitLab Plugin.

pipelineJob("merge-request-pipeline") {
 concurrentBuild()
 quietPeriod(0)
 authenticationToken("thetoken")
 triggers {
  genericTrigger {
   genericVariables {
    genericVariable {
     key("MERGE_REQUEST_TO_URL")
     value("\$.object_attributes.target.git_http_url")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("MERGE_REQUEST_FROM_URL")
     value("\$.object_attributes.source.git_http_url")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("MERGE_REQUEST_TO_BRANCH")
     value("\$.object_attributes.target_branch")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("MERGE_REQUEST_FROM_BRANCH")
     value("\$.object_attributes.source_branch")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("PROJECT_ID")
     value("\$.object_attributes.target_project_id")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("PROJECT_PATH")
     value("\$.object_attributes.target.path_with_namespace")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("MERGE_REQUST_IID")
     value("\$.object_attributes.iid")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("MR_OBJECT_KIND")
     value("\$.object_kind")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("MR_OLD_REV")
     value("\$.object_attributes.oldrev")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("MR_ACTION")
     value("\$.object_attributes.action")
     expressionType("JSONPath")
     regexpFilter("")
    }
    genericVariable {
     key("MR_TITLE")
     value("\$.object_attributes.title")
     expressionType("JSONPath")
     regexpFilter("")
    }
   }
   regexpFilterText("\$MR_OBJECT_KIND \$MR_ACTION \$MR_OLD_REV")
   regexpFilterExpression("^merge_request\\s(update\\s.{40}\$|open.*)")
  }
 }
 
 definition {
  cps {
   script(readFileFromWorkspace('merge_request_pipeline.pipeline'))
   sandbox()
  }
 }
}

And the merge_request_pipeline.pipeline contains

def commentMr(projectId, mergeRequestIid, comment) {
 def body = comment
 .replaceAll(" ","%20")
 .replaceAll("/","%2F")
 def project = projectId
 .replaceAll("/","%2F")
 sh "curl http://gitlab:80/api/v4/projects/$project/merge_requests/$mergeRequestIid/notes -H 'PRIVATE-TOKEN: 6xRcmSzPzzEXeS2qqr7R' -X POST -d \"body="+body+"\""
}
  
node {
 deleteDir()
 currentBuild.description = "$MR_TITLE from $MERGE_REQUEST_FROM_BRANCH to $MERGE_REQUEST_TO_BRANCH"
  
 commentMr(env.PROJECT_PATH,env.MERGE_REQUST_IID,"Verifierar $MERGE_REQUEST_FROM_BRANCH... ${env.BUILD_URL}")
  
 stage('Merge') {
  sh "git init"
  sh "git fetch --no-tags $MERGE_REQUEST_TO_URL +refs/heads/*:refs/remotes/origin/* --depth=200"
  sh "git checkout origin/${env.MERGE_REQUEST_TO_BRANCH}"
  sh "git config user.email '[email protected]'"
  sh "git config user.name 'jenkins'"
  sh "git merge origin/${env.MERGE_REQUEST_FROM_BRANCH}"
  sh "git log --graph --abbrev-commit --max-count=10"
 }
  
 stage('Compile') {
  sh "./gradlew assemble"
 }
  
 stage('Unit test') {
  sh "./gradlew test"
  commentMr(env.PROJECT_PATH,env.MERGE_REQUST_IID,"Test ok in $MERGE_REQUEST_FROM_BRANCH =) ${env.BUILD_URL}")
 }
  
 stage('Regression test') {
  sh "echo regtest"
  commentMr(env.PROJECT_PATH,env.MERGE_REQUST_IID,"Regression test ok in $MERGE_REQUEST_FROM_BRANCH =) ${env.BUILD_URL}")
 }
  
 stage('Static code analysis') {
 sh "./gradlew check"
 step([
 $class: 'ViolationsToGitLabRecorder',
 config: [
  gitLabUrl: 'http://gitlab:80/',
  projectId: env.PROJECT_PATH,
  mergeRequestIid: env.MERGE_REQUST_IID,
  commentOnlyChangedContent: true,
  commentOnlyChangedContentContext: 0,
  commentOnlyChangedFiles: true,
  createSingleFileComments: true,
  createCommentWithAllSingleFileComments: true,
  minSeverity: 'INFO',
  maxNumberOfViolations: 99999,
 
  // You may want this when troubleshooting things
  enableLogging: true,
 
  // Only specify proxy if you need it
  proxyUri: '',
  proxyCredentialsId: '', // A username/password credential
 
  apiTokenCredentialsId: 'id', // A secret text credential
  apiTokenPrivate: true,
  authMethodHeader: true,
  ignoreCertificateErrors: true,
  keepOldComments: false,
  shouldSetWip: true,
 
  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: [
   [ pattern: '.*/checkstyle/.*\\.xml$', parser: 'CHECKSTYLE', reporter: 'Checkstyle' ],
   [ pattern: '.*/findbugs/.*\\.xml$', parser: 'FINDBUGS', reporter: 'Findbugs' ],
   [ pattern: '.*/pmd/.*\\.xml$', parser: 'PMD', reporter: 'PMD' ],
  ]
 ]
 ])
 }
}

Encoding

The commentTemplate parameter can be used to fix encoding problems, or just adjust what is being commented. See README in violation-comments-lib.

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

violation-comments-to-gitlab-plugin's People

Contributors

daniel-beck-bot avatar falkena avatar jetersen avatar strangelookingnerd avatar timja avatar tomasbjerre avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

violation-comments-to-gitlab-plugin's Issues

Missing supported version of Jenkins

We have an quite old version of Jenkins that we had problems upgrading since we also need to update plugins. It would therefore be a nice fact to be able to read in the README.md what versions of Jenkins that are able to handle the plugin. For my needs it is sufficient to know about the latest version but if you want to put some extra sugar on top you make a list where the requirements are changed over time.

Our version of Jenkins is 2.138.

Support GitLab plugin GitLab API token credential type

When the GitLab plugin is installed, a credential category for personal API tokens is available.

This plugin could then make use of this more specific one instead of the generic "secret text" category.

At the moment it does not support GitLab API token credentials at all.

Let report log level to be configured per violationConfig

Currently the minSeverity can be only set globally. It would be nice to configure it per violationConfig, since some kind of reports can be more important than others. For example i am interested in all Checkstyle violations, but only interested in error Android LINT violations.
We cannot configure the plugin this way currently.

The syntax could be:

violationConfigs: [
  [ pattern: '.*/checkstyle/.*\\.xml$', parser: 'CHECKSTYLE', reporter: 'Checkstyle', minSeverity: 'ERROR'],
  [ pattern: '.*/reports/lint-results.*\\.xml$', parser: 'ANDROIDLINT', reporter: 'AndroidLint', minSeverity: 'WARN']
]

NPE (ServiceLocaterUtilities) when commenting MR

Jenkins: 2.2.0
Gitlab: 12.7.5
Plugin: 2.3.9

Pipeline:
`
step([

$class: 'ViolationsToGitLabRecorder',

config: [

		apiTokenCredentialsId                         : 'GitlabCI',

		apiTokenPrivate                               : true,

		authMethodHeader                              : true,

		commentOnlyChangedContent                     : false,

		commentOnlyChangedFiles                       : true,

		commentTemplate                               : '**Severity**: {{violation.severity}}<br>**Source**: <i>{{violation.file}}:{{violation.endLine}}</i><br>{{violation.message}}',

		createSingleFileComments                      : true,

		gitLabUrl                                     : 'http://git/',

		ignoreCertificateErrors                       : true,

		keepOldComments                               : true,

		mergeRequestIid                               : env.gitlabMergeRequestIid,

		minSeverity                                   : 'INFO',

		maxNumberOfViolations                         : 9999,

		createCommentWithAllSingleFileComments        : true,

		shouldSetWip                                  : false,

		projectId                                     : env.gitlabMergeRequestTargetProjectId,

		enableLogging                                 : true,

		violationConfigs                              : [

				[parser: 'SONAR', pattern: '.*/sonar/report.*json', reporter: 'Sonar'],

				[parser: 'JUNIT', pattern: '.*/surefire-reports/.*xml', reporter: 'JUnit']

		]

]])

`

StackTrace:
`java.lang.RuntimeException: Could not get project 1249
at se.bjurr.violations.comments.gitlab.lib.GitLabCommentsProvider.(GitLabCommentsProvider.java:72)
at se.bjurr.violations.comments.gitlab.lib.ViolationCommentsToGitLabApi.toPullRequest(ViolationCommentsToGitLabApi.java:175)
at org.jenkinsci.plugins.jvctgl.perform.JvctglPerformer.doPerform(JvctglPerformer.java:160)
at org.jenkinsci.plugins.jvctgl.perform.JvctglPerformer$2.invoke(JvctglPerformer.java:268)
at org.jenkinsci.plugins.jvctgl.perform.JvctglPerformer$2.invoke(JvctglPerformer.java:256)
at hudson.FilePath$FileCallableWrapper.call(FilePath.java:3069)
at hudson.remoting.UserRequest.perform(UserRequest.java:211)
at hudson.remoting.UserRequest.perform(UserRequest.java:54)
at hudson.remoting.Request$2.run(Request.java:369)
at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:72)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)

Caused by: org.gitlab4j.api.GitLabApiException
at org.gitlab4j.api.AbstractApi.handle(AbstractApi.java:604)
at org.gitlab4j.api.AbstractApi.get(AbstractApi.java:182)
at org.gitlab4j.api.ProjectApi.getProject(ProjectApi.java:665)
at se.bjurr.violations.comments.gitlab.lib.GitLabCommentsProvider.(GitLabCommentsProvider.java:70)
... 13 more

Caused by: java.lang.NullPointerException
at org.glassfish.hk2.utilities.ServiceLocatorUtilities.addClasses(ServiceLocatorUtilities.java:411)
at org.glassfish.hk2.utilities.ServiceLocatorUtilities.enablePerThreadScope(ServiceLocatorUtilities.java:83)
at org.glassfish.jersey.inject.hk2.AbstractHk2InjectionManager.createLocator(AbstractHk2InjectionManager.java:92)
at org.glassfish.jersey.inject.hk2.AbstractHk2InjectionManager.(AbstractHk2InjectionManager.java:62)
at org.glassfish.jersey.inject.hk2.ImmediateHk2InjectionManager.(ImmediateHk2InjectionManager.java:38)
at org.glassfish.jersey.inject.hk2.Hk2InjectionManagerFactory$Hk2InjectionManagerStrategy$1.createInjectionManager(Hk2InjectionManagerFactory.java:55)
at org.glassfish.jersey.inject.hk2.Hk2InjectionManagerFactory.create(Hk2InjectionManagerFactory.java:73)
at org.glassfish.jersey.internal.inject.InjectionManagerFactory.create(InjectionManagerFactory.java:32)
at org.glassfish.jersey.internal.inject.Injections.createInjectionManager(Injections.java:44)
at org.glassfish.jersey.client.ClientConfig$State.initRuntime(ClientConfig.java:408)
at org.glassfish.jersey.internal.util.collection.Values$LazyValueImpl.get(Values.java:317)
at org.glassfish.jersey.client.ClientConfig.getRuntime(ClientConfig.java:802)
at org.glassfish.jersey.client.ClientRequest.getConfiguration(ClientRequest.java:261)
at org.glassfish.jersey.client.JerseyInvocation.validateHttpMethodAndEntity(JerseyInvocation.java:119)
at org.glassfish.jersey.client.JerseyInvocation.(JerseyInvocation.java:88)
at org.glassfish.jersey.client.JerseyInvocation.(JerseyInvocation.java:84)
at org.glassfish.jersey.client.JerseyInvocation.(JerseyInvocation.java:75)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:395)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:295)
at org.gitlab4j.api.GitLabApiClient.get(GitLabApiClient.java:384)
at org.gitlab4j.api.GitLabApiClient.get(GitLabApiClient.java:372)
at org.gitlab4j.api.AbstractApi.get(AbstractApi.java:180)
... 15 more`

Could not get GitLab project

My Env:

GitLab 10.0.4
Jenkins 2.73.2

I setup violation comments gitlab plugin as below:
gitlab

It threw an exception when running its Post-build Action:

19:00:09 Will comment PR https://gitlab.company.com/ 253 2917
19:00:09 java.lang.RuntimeException: Could not get project 253
19:00:09 at se.bjurr.violations.comments.gitlab.lib.GitLabCommentsProvider.<init>(GitLabCommentsProvider.java:51)
19:00:09 at se.bjurr.violations.comments.gitlab.lib.ViolationCommentsToGitLabApi.toPullRequest(ViolationCommentsToGitLabApi.java:125)
19:00:09 at org.jenkinsci.plugins.jvctgl.perform.JvctglPerformer.doPerform(JvctglPerformer.java:137)
19:00:09 at org.jenkinsci.plugins.jvctgl.perform.JvctglPerformer$1.invoke(JvctglPerformer.java:220)
19:00:09 at org.jenkinsci.plugins.jvctgl.perform.JvctglPerformer$1.invoke(JvctglPerformer.java:208)
19:00:09 at hudson.FilePath.act(FilePath.java:998)
19:00:09 at hudson.FilePath.act(FilePath.java:976)
19:00:09 at org.jenkinsci.plugins.jvctgl.perform.JvctglPerformer.jvctsPerform(JvctglPerformer.java:207)
19:00:09 at org.jenkinsci.plugins.jvctgl.ViolationsToGitLabRecorder.perform(ViolationsToGitLabRecorder.java:66)
19:00:09 at hudson.tasks.BuildStepCompatibilityLayer.perform(BuildStepCompatibilityLayer.java:81)
19:00:09 at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
19:00:09 at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:736)
19:00:09 at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:682)
19:00:09 at hudson.model.Build$BuildExecution.post2(Build.java:186)
19:00:09 at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:627)
19:00:09 at hudson.model.Run.execute(Run.java:1762)
19:00:09 at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
19:00:09 at hudson.model.ResourceController.execute(ResourceController.java:97)
19:00:09 at hudson.model.Executor.run(Executor.java:421)

In fact GitLab project 253 exists.

How to configure

Describe your use-case which is not covered by existing documentation.

There are a couple of configuration items that I'm struggling with.

  • gitLabUrl - I'm assuming that this would be 'https://gitlab.com/'? Any reason not to hardcode it?
  • apiTokenCredentialsId - I've tried every way I can to create a credential I can think of and the plugin still says it can't find it. Specifically, it throws an exception
 java.lang.RuntimeException: API Token not set!
 	at org.jenkinsci.plugins.jvctgl.perform.JvctglPerformer.jvctsPerform(JvctglPerformer.java:230)
  • projectId - The documented value of env.PROJECT_PATH doesn't exist. I've guessed at env.GITLAB_PROJECT_ID?
  • mergeRequestIid - The documented value of env.MERGE_REQUST_IID doesn't exist. I'm assuming env.CHANGE_ID?

The env variables that might be useful are

 BRANCH_NAME=MR-7
 BUILD_DISPLAY_NAME=#14
 BUILD_ID=14
 BUILD_NUMBER=14
 BUILD_TAG=jenkins-Platform-vivint%2Fhorizontals%2Fplatform%2Faccountsystem-MR-7-14
 BUILD_URL=https://***.***.***/job/Platform/job/vivint%252Fhorizontals%252Fplatform%252Faccountsystem/job/MR-7/14/
 CHANGE_AUTHOR=ben.mathews
 CHANGE_AUTHOR_DISPLAY_NAME=Benjamin Mathews
 CHANGE_BRANCH=mergeRequestCommenting
 CHANGE_ID=7
 CHANGE_TARGET=master
 CHANGE_TITLE=Merge request commenting
 CHANGE_URL=https://gitlab.com/**/-/merge_requests/7
 CI=true
 EXECUTOR_NUMBER=10
 GITLAB_OBJECT_KIND=none
 HUDSON_HOME=/var/lib/jenkins
 HUDSON_URL=https://***.***.***/
 JENKINS_HOME=/var/lib/jenkins
 JENKINS_URL=https://***.***.***/
 JOB_BASE_NAME=MR-7
 JOB_DISPLAY_URL=https://***.***.***/job/Platform/job/vivint%252Fhorizontals%252Fplatform%252Faccountsystem/job/MR-7/display/redirect
 JOB_NAME=Platform/vivint%2Fhorizontals%2Fplatform%2Faccountsystem/MR-7
 JOB_URL=https://***.***.***/job/Platform/job/vivint%252Fhorizontals%252Fplatform%252Faccountsystem/job/MR-7/
 WORKSPACE=/var/lib/jenkins/workspace/workspace/tals_platform_accountsystem_MR-7
 WORKSPACE_TMP=/var/lib/jenkins/workspace/workspace/tals_platform_accountsystem_MR-7@tmp

Reference any relevant documentation, other materials or issues/pull requests that can be used for inspiration.

No response

Can't add API key

Hi,

I'm trying to set up this plugin but I can't add any credentials. The dropdown stays empty.

image

Even after clicking the 'add' button and adding all kids of keys nothing shows up in the list.

The weird thing is that the general git plugin does recognise the credentials and works fine:

image

Support commentOnlyChangedContentContext

Expected: if the commentOnlyChangedContent parameter is set to true, only the violations for changed lines should be reported.

Actual: it seems if the violation is inside the diff, it is still reported, despite if the line was actually changed or not.

Example:

screenshot 2019-03-04 at 15 35 44

You can see that a violation was reported for line 5 (the line with ellipsis), but that line actually was not changed by the commits.

Jenkins pipeline-syntax entry does not generate correctly

It may be a good idea to look at old issues, both closed and open.

Some recurring problems are:

  • The user did not perform the merge before doing the analysis.
  • No violations were reported because:
    • The user tested the plugin on a PR that did not introduce any new violations.
    • The user had both createSingleFileComments and createCommentWithAllSingleFileComments set to false

When reporting a bug, please try to provide as much information as possible.

  • Plugin version used.
    2.45
  • Jenkins version used.
    2.176.4
  • Your configuration.
    • Pipeline script or screenshot.
      Capture
  • Expected result and actual result.
    I expected that the pipeline generator would be able to display a snippet that I could paste into my jenkinsfile, with the details set up. Instead, I received what seems to be an object stringification.
  • Any information from the logs:
    • Jenkins log: http://jenkins-server/log/
      No relevant logs
    • Build log.
      No Build was able to be performed since it couldn't generate the definition.

Coverage report

Would be nice with a quick coverage summary:

Coverage report

89.47% line coverage
69.14% branch coverage

See more here.

Commenting/WIPing the merge request doesn't work

After changing the configuration several times (authHeader true/false, private true/false, ...) It seems that I found a configuration for the plugin which allows jenkins to connect to gitlab. At least I don't get error messages which say otherwise.
However the comments that should appear in the merge request, and setting the merge request to WIP doesn't happen. Do I do something wrong, or are there currently problems existing with the commenting stuff? Unfortunately I couldn't test with other options such as the maven connection because it seems to be broken, too cf. tomasbjerre/violation-comments-to-gitlab-maven-plugin#1

This is the output i get:


--- Violation Comments to GitLab ---

gitLabUrl: #########
projectId: 211
mergeRequestIid: 289
apiToken: false
apiTokenCredentialsId: true
ignoreCertificateErrors: true
apiTokenPrivate: true
authMethodHeader: true
createCommentWithAllSingleFileComments: false
commentOnlyChangedContent: false
minSeverity: INFO
keepOldComments: false
shouldSetWip: true
FINDBUGS with pattern ./target/findbugsXml.xml$
Running Violation Comments To GitLab
Merge request: 289
Workspace: #################
Found 2 violations from ViolationConfig [pattern=.
/target/findbugsXml.xml$, parser=FINDBUGS, reporter=Findbugs].
Will comment PR https://########## 211 289

This is the configuration I use:

ViolationsToGitLab([apiToken: '',
                                apiTokenCredentialsId: 'id',
                                apiTokenPrivate: true,
                                authMethodHeader: true,
                                gitLabUrl: '',
                                ignoreCertificateErrors: true,
                                keepOldComments: false,
                                mergeRequestIid: env.gitlabMergeRequestIid,
                                projectId: "211",
                                shouldSetWip: true,
                                commentOnlyChangedContent: false,
                                violationConfigs: [[parser: 'FINDBUGS', pattern: '.*/target/findbugsXml\\.xml$', reporter: 'Findbugs']]])

Clarify that credentials have to be "secret text" credentials

The configuration does not make clear that a secret text credential has to be used. Adding a descriptive text or expandable help text would be helpful.

This is especially confusing when the GitLab plugin is installed as well, which adds a credential category for personal API tokens. Given that this plugins setting is labeled as "personal API token" as well, it implies that that credential category should be used, but then fails to identify it. (Adding the credentials from the Add button and it then simply not appearing as a selectable option is quite confusing.)

JUnit/Surefire reports

Would be nice to be able to post the total number of tests, and name failures:

Unit test report

🔻 514/517 tests succeeded

  • SomeClass.test_1
  • SomeClass.test_2
  • SomeClass.test_3

See more here.

Getting null pointer exception on comment

Plugin version 2.31
Jenkins version 2.138.3
Gitlab 10.7.3 ce

Pipeline command

        step([
          $class: 'ViolationsToGitLabRecorder',
          config: [
            gitLabUrl: 'https://mygitlabserver/',
            projectId: 'projectgroup/project-name',
            mergeRequestIid: env.gitlabMergeRequestIid,
            //createCommentWithAllSingleFileComments: true,
            createSingleFileComments: true,
            //commentOnlyChangedContent: true,
            commentOnlyChangedFiles: true,
            minSeverity: 'INFO',
            maxNumberOfViolations: 99999,
            enableLogging: true,
            apiTokenCredentialsId: 'jenkins-violations-secret',
            apiTokenPrivate: true,
            authMethodHeader: true,
            ignoreCertificateErrors: 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: [
              [ pattern: '.*checkstyle\\.xml$', parser: 'CHECKSTYLE', reporter: 'Checkstyle' ]
            ]
          ]
        ])

Stack trace during the build

java.lang.NullPointerException
	at se.bjurr.violations.comments.gitlab.lib.GitLabCommentsProvider.createSingleFileComment(GitLabCommentsProvider.java:161)
	at se.bjurr.violations.comments.lib.CommentsCreator.createSingleFileComments(CommentsCreator.java:147)
	at se.bjurr.violations.comments.lib.CommentsCreator.createComments(CommentsCreator.java:71)
	at se.bjurr.violations.comments.lib.CommentsCreator.createComments(CommentsCreator.java:38)
	at se.bjurr.violations.comments.gitlab.lib.ViolationCommentsToGitLabApi.toPullRequest(ViolationCommentsToGitLabApi.java:175)
	at org.jenkinsci.plugins.jvctgl.perform.JvctglPerformer.doPerform(JvctglPerformer.java:160)
	at org.jenkinsci.plugins.jvctgl.perform.JvctglPerformer$2.invoke(JvctglPerformer.java:268)
	at org.jenkinsci.plugins.jvctgl.perform.JvctglPerformer$2.invoke(JvctglPerformer.java:256)
	at hudson.FilePath$FileCallableWrapper.call(FilePath.java:3052)
	at hudson.remoting.UserRequest.perform(UserRequest.java:212)
	at hudson.remoting.UserRequest.perform(UserRequest.java:54)
	at hudson.remoting.Request$2.run(Request.java:369)
	at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:72)
	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)

Problem reading report

Hi im currently facing this problem, maybe i havent undestand the plugin correnctly

Im currently generating a report using PMD with this call, which generates a xml file with 5 violations...

$PMD_HOME/bin/run.sh pmd -d srcToDeploy -R "$PMD_HOME/rules.xml" -f xml -r csv-delta.xml -failOnViolation false

After this im calling your plugin with the next command

ViolationsToGitLab([apiToken: 'MYAPITOKEN', apiTokenCredentialsId: 'jenkins-violations', apiTokenPrivate: true, authMethodHeader: false, gitLabUrl: 'https://gitlab.com',
	ignoreCertificateErrors: true, mergeRequestId: env.gitlabMergeRequestIid, projectId: env.gitlabMergeRequestTargetProjectId,
	violationConfigs: [[parser: 'PMD', pattern: 'csv-delta.xml', reporter: '']]])

This generates this result

[Code Quality Tests] ---
[Code Quality Tests] --- Violation Comments to GitLab ---
[Code Quality Tests] ---
[Code Quality Tests] gitLabUrl: https://gitlab.com
[Code Quality Tests] projectId: 5606826
[Code Quality Tests] mergeRequestId: 34
[Code Quality Tests] apiToken: true
[Code Quality Tests] apiTokenCredentialsId: true
[Code Quality Tests] ignoreCertificateErrors: true
[Code Quality Tests] apiTokenPrivate: true
[Code Quality Tests] authMethodHeader: false
[Code Quality Tests] createCommentWithAllSingleFileComments: false
[Code Quality Tests] commentOnlyChangedContent: false
[Code Quality Tests] minSeverity: INFO
[Code Quality Tests] keepOldComments: true
[Code Quality Tests] shouldSetWip: false
[Code Quality Tests] PMD with pattern csv-delta.xml
[Code Quality Tests] Running Violation Comments To GitLab
[Code Quality Tests] Merge request: 34
[Code Quality Tests] Workspace: /var/lib/jenkins/workspace/liquidstudio-jenkins-demo
[Code Quality Tests] Found 0 violations from ViolationConfig [pattern=csv-delta.xml, parser=PMD, reporter=].
[Code Quality Tests] Will comment PR https://gitlab.com 5606826 34

The number of violations is 0 when in the xml i generate with the pmd i have 5...

Im doing anything wrong??

Thank you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.