Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
I had the same problem for the Java plugin. I solved it by executing an analysis with SCM support disabled:sonar.scm.disabled = trueNote thatI didn't have to disable it permanently,only forone analysis. After that it worked fine again.
|
This is an analysis that I have been running for a while.
The SCM is Git.I upgradedSonarQubeto 5.2 (fromhttp://downloads.sourceforge.net/project/sonar-pkg/debas I am using Ubuntu LTS 14.04.3)sonar.lognow gives:2015.11.17 10:43:00 ERROR web[o.s.s.c.t.CeWorkerRunnableImpl] Executed task | project=energy:energy | id=AVEVClvzTc_W2Q8I5ipV | time=647msThrough the web interface I tracked down:http://localhost:9000/api/ce/logs?taskId=AVEVClvzTc_W2Q8I5ipVwhich gave:java.lang.IllegalArgumentException: There's no changeset on line 170
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:125) ~[guava-17.0.jar:na]
at org.sonar.server.computation.scm.ScmInfoImpl.getChangesetForLine(ScmInfoImpl.java:64) ~[sonar-server-5.2.jar:na]
at org.sonar.server.computation.scm.ReportScmInfo.getChangesetForLine(ReportScmInfo.java:71) ~[sonar-server-5.2.jar:na]
at org.sonar.server.computation.step.NewCoverageMeasuresStep$NewCoverageCounter.initialize(NewCoverageMeasuresStep.java:391) ~[sonar-server-5.2.jar:na](It would be an improvement if the error message told you the file name in which it thinks line 170 is wrong.)Is there anything to be done other than wait for version 5.3 ?
|
After SonarQube 5.2 upgrade java analysis fails with java.lang.IllegalArgumentException: There's no changeset on line
|
I had java installed even then i was also getting the same error in my mac system and i just installed "Java SE Development Kit 8u60"(jdk-8u60-macosx-x64.dmg) for "Mac OS X x64" and then the issue got fixed.http://www.oracle.com/technetwork/java/javase/downloads/java-archive-javase8-2177648.htmlso i think just installing "Java SE Development Kit 8u60" for right system from above link may fix this issue for others who ever faces this problem.
|
I'm trying to install SonarQube on a Maxc (actually sonar source, tutorial is athttp://chapter31.com/2013/05/02/installing-sonar-source-on-mac-osx/). The result of the "sonar start" command is the following output in sonar.log:--> Wrapper Started as Daemon
Launching a JVM...
JVM exited while loading the application.
Error occurred during initialization of VM
Incompatible minimum and maximum heap sizes specified
JVM Restarts disabled. Shutting down.
<-- Wrapper StoppedI've tried to set the Java properties correctly in sonar.properties:sonar.web.javaOpts=-Xms512m -Xmx768m -XX:MaxPermSize=256m -XX:+HeapDumpOnOutOfMemoryError -Djava.net.preferIPv4Stack=trueThe system is a Macbook Pro running OSX 10.11.1. Typing "java -version" into the command line outputs java version "1.6.0_65".
|
Incompatible heap sizes error in Sonarqube
|
The issue you are encoutering comes from a binary incompatiblity due to latest version of JaCoCo binary report. This issue has been fixed in version 3.4 of the sonar-java-plugin :https://jira.sonarsource.com/browse/SONARJAVA-1091Please update your plugin version, it should solve the issue.
|
The problem discussed inJaCoCo SonarQube incompatible version 1007is happening again withsonarqube-maven-plugin 2.7.1in combination withjacoco-maven-plugin 0.7.5.201505241946Executingsonar:sonarresults injava.io.IOException: Incompatible version 1007.According tohttps://jira.sonarsource.com/browse/SONARJAVA-1091this should be fixed already.The java plugin in my SQ-Server installation is version 3.3.Can anyone confirm this?
|
Incompatible version 1007 with sonarqube-maven-plugin 2.7.1 and jacoco-maven-plugin 0.7.5
|
By default SonarQube's LDAP plugin works like you think it does. You can configureLDAP group mappingso that when the user enrolls, he/she is automatically added to the appropriate group.In other words, create the group for the project in SonarQube, and then create the same group in LDAP and add users to it. Then when users login for the first time they will be in the appropriate group, and on each subsequent login any group changes will be reflected in SonarQube.This, in my opinion, is infact better than adding users manually.
|
I guess this question basically boils down to some misunderstanding that I have about how the SonarQube LDAP plugin works in general. We have integrated the LDAP plugin and our users are authenticating against our corporate LDAP server. When we we want to create a new group and add users to that group for a new project, we have assumed that the users themselves must authenticate into SonarQube first so they get added as a user to SonarQube. After that, then we are able to put them into the appropriate groups that they belong to. This is a pain for our administrators since the people that need to be added are logging in at differing times or forgetting to log in at all. What we would like is something that Nexus provides where we can do a lookup of that user's account id, then add them and place them into the appropriate group(s). In that way, the user is not bothered by having to login first and then the administrator has to give the privileges and then the user logs out and logs back in. Is this a misunderstanding on my part? I ask because when I go to the users page and click on 'Create New User' it not only asks for the user's id but also the user's password which I obviously don't know so this is telling me that this will be a local account.
|
How to automatically discover and add users via LDAP in SonarQube?
|
The problem issolved.
The proxy settings on the build agent had changed. This resulted in http requests to the TFS server or any local addresses to fail.It was particularly challanging to figure out, because the Agent build log that tells you all the details of a build is the file that could not be transferred to the drop location.So I usedProcMonfrom Sysinternals with File monitor enabled during a build. A comparison between a successful build in the past and a current failed build showed me which file was missing (the agent log file). A search in ProcMon for this file revealed where that file was located on the build agent. The Agent Log file contained theDownloading coverage file from {0} to {1}line Dinesh was looking for in his attempt to help me. That http address pasted into a browser showed an "Access denied" message.From there it was a logical step to analyse the Proxy settings. What finally solved it was to check "Bypass proxy server for local addresses" in the Local Area Network (LAN) Settings"
|
I have code coverage enabled on TFS 2013. I work with MSBuild.SonarQube.Runner 1.0.1. When I run the End phase of the Analysis. I get the following error messages:11:36:00.269 Failed to convert the downloaded code coverage tool to XML. No code coverage information will be uploaded to SonarQube.<br/>
Check that the downloaded code coverage file (C:\Builds\39\[product name]\System_Main_Release_Code_Analysis\.sonarqube\out\VSCodeCoverageReport.coverage) is valid by opening it in Visual Studio. If it is not, check that the internet security settings on the build machine allow files to be downloaded from the Team Foundation Server machine.
Post-processing failed. Exit code: 1
An error occurred while copying diagnostic activity logs to the drop location. Details: ForbiddenOn the build server there is no VSCodeCoverageReport.coverage file - at least not at the indicated location and with that name. However, when I click on (Coverage Results) in the TFS Build summary, a coverage file is downloaded that opens up in Visual Studio in the Code Coverage Results Window.What could be the issue?
|
Failed to convert the downloaded code coverage tool to XML
|
I ran into this issue today. Turns out that I had miss configured SonarQube.Analysis.xml. Essentially, it expects<Property Name="sonar.host.url">http://{server}:9000/sonar</Property>including/sonar(which comes from sonar.web.context setting of sonar.properties on the server).I had missed out /sonar in SonarQube.Analysis.xml and had exact same symptom as yours.
|
Unable to execute sonar run for ms build when i change the sonar host from localhost to my machine ip.tried changing the host in sonar.properties file and also in sonarqube_analysis.xml.c:\HID\project-test\PACS\sonar_opencover\Project>MSBuild.SonarQube.Runner.exe end
Default properties file was found at C:\HID\project-test\dotnet\MSBuild.SonarQube.Runner-1.0.1\SonarQube.Analysis.xml
Loading analysis properties from C:\HID\project-test\dotnet\MSBuild.SonarQube.Runner-1.0.1\SonarQube.Analysis.xml
Post-processing started.
Execution failed. The specified executable does not exist: c:\HID\project-test\PACS\sonar_opencover\Project\.sonarqube\bin\MSBuild.SonarQube.Internal.PostProcess.exe
Post-processing failed. Exit code: 1Scripts i executed@call "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\VsDevCmd.bat"
MSBuild.SonarQube.Runner.exe begin /k:"jenkins_test5" /n:"jenkins_test5" /v:"1.0" /d:sonar.cs.opencover.reportsPaths="%CD%\opencover.xml"
msbuild.exe
"C:\HID\project-test\PACS\sonar_opencover\opencover.4.6.210\OpenCover.Console.exe" -output:"%CD%\opencover.xml" -register:user -target:"vstest.console.exe" -targetargs:"UnitTestProject1\bin\Debug\UnitTestProject1.dll"
MSBuild.SonarQube.Runner.exe end
|
Doesnt find MSBuild.SonarQube.Internal.PostProcess.exe
|
This is a native feature since SQ 5.1, see "Getting Issues Report in Preview Mode"
|
When running the sonar runner in TeamCity on previous versions of SonarQube it was possible to create an HTML issues report for the analysis. This could then be loaded into a tab on the build to show analysis results. However, since 5.1 the Issues Report plugin has been replaced with built in functionality and has been deprecated.
The report is still created if run in preview mode, but it is not created when run in analysis mode, so that the tab on the build is no longer available.
Can this functionality be made available?
|
Issue Report not availble for version 5.1.2
|
You can only useUser Text Displaywidget (available inWidget Lab Plugin). It is associated with dashboard (not project) so all projects using this dashboard will see the same message.
|
I have included Welcome widget in my Sonar dashboard. Now I want to include my project specific documents and links in this widget.I am not able to modify the default contents of this widget.
How can I update/delete contents of this welcome widget?
|
Modify contents of Welcome widget in Sonar
|
Yes, you should put this line in your sonar-project.properties file.sonar.cpd.js.minimumLines=5Seehttps://docs.sonarqube.org/display/SONAR/Analysis+Parameters#AnalysisParameters-Duplications:A piece of code is considered as duplicated as soon as there are at
least 100 successive and duplicated tokens (can be overridden with
property sonar.cpd.${language}.minimumTokens) spread on at least 10
lines of code (can be overridden with property
sonar.cpd.${language}.minimumLines)
|
At the moment the duplication metric for JavaScript Code in SonarQube code is defined as followed:“There should be at least 100 successive and duplicated tokens.
Those tokens should be spread at least on 10 lines of code.”Is there a way to change the nummer of tokens and the number of lines? Since I want to have 5 lines.
|
Sonarqube: Is it possible to adapt duplication metric for javascript code?
|
You should uninstall this plugin. It is compatible, but it does not work correctly. The problem is thatSonarQube 5.1introduced core auto assignment (seeautomatic issue assignmentandSONAR-5906). The core functionality & plugin execution order is as follows:Plugin during the execution assigns issues & collects information to whom he should send e-mails. Next core functionality reassign issues.Core functionality reassigns issuesPlugin sends emails with incorrect dataSeetopic on SonarQube mailing list
|
This is about sonarqube 5.1 versionI have issue assign plugin and also subscribed to the emails in my profile page. I've done some erroneous SVN commits deliberately to check the email notification settings but it doesn't seem to work correctly. I receive emails sometimes but other times it doesn't work like that.I know this is not a constructive enough question but I'm really stucked here after trying all the scenarios and going through the documentation.
Any insight would be highly appreciated.
|
Email Notification unpredicted behaviour in sonarqube
|
There is no built-in way of ignoring files in Roslyn at the moment, so you can't do it. Each analyzer needs to decide if the analyzed file needs to be checked or not. Specifically for SonarLint, I've created an issue on GitHub:https://github.com/SonarSource/sonarlint-vs/issues/85. You can track its progress.
|
BackgroundI am running Visual Studio 2015 Enterprise (RTM) and have enabled theSonarLintextension for code analysis of my multi-project ASP.NET 4.5 MVC solution.ProblemSonarLint analysis seems to be ignoring the project setting for Code Analysis "Suppress results from generated code (managed only)"That is, I'm getting a lot of Sonar errors reported back for a couple of*.designer.csfiles generated from some.aspxpages. (Most of the project is MVC, for what it's worth.) I don't care about these errors, and don't think I have a decent path for fixing them...More DetailsI have SonarQube integrated with our TFS 2013 environment, and it is correctly ignoring these issues on the TFS server analysis. This problem is just showing up in Visual Studio, using the Roslyn analysis.Any ideas how I can set up the equivalent of an .ignore file or otherwise fix this?
|
Remove Auto-generated Code from SonarLint Analysis
|
The link to the documentation you provide points tohttp://nemo.sonarqube.org/which is running SonarQube 5.1, not the version you are using.Fortunately, there is no change regarding permissions checks on the WS/api/projects/destroybetween 4.5 and 5.1 and what you request is not implemented: Administer System permission is required, project administer permission is not enough.In 5.2, this WS is replaced by WS/api/project/deletewhich requires 'Administer System' permission or 'Administer' permission on the project.
|
I'm using SonarQube 4.5.4. TheSonarQube's API documentationsays that thePOST api/projects/destroymethod requiresAdminister Systempermission.However, users having the Administer Project role can delete their projects via the web interface selecting theDeletionoption in theProject Configurationmenu.Why can't "project administrators" use the API to delete the projects they administer? Or is there a way? I've tried and I got this error:$ curl -u user:password -X POST "https://sonar.cpqd.com.br/api/projects/destroy?id=123456789"
{"err_code":401,"err_msg":"Unauthorized"}%
|
Can SonarQube project administrators delete a project via the API?
|
This "Detail" panel of a file is not customisable, and there's currently no plan to make it customisable.When providing your own metrics, the standard "Measure Drilldown" as long as a dashboard widget should be enough to expose your information.
|
By "file details" I mean this screen when you drill down on a file:Here there are only the basics displayed but, for instance, if you calculate duplications, another widget will appear with duplication information.In my case I have developed a crapload of code metrics for my language plugin; Idosee them if I click on the link "Show all measures" (you can see it at the bottom left of the image) but I am unable to see how I can create such a widget to add to this screen without clicking on the details...Is it possible? If yes, how do you do it?
|
Is it possible to customize SonarQube's file details screen?
|
even if I do understand that this might be misleading, not having any information about dependencies/librairies/design on C# projects is expected. FYI, in SQ 5.2, all those pages and relating metrics will be dropped, see the following Jira ticket:http://jira.sonarsource.com/browse/SONAR-6553.
|
We recently setup SonarQube analysis jobs for our main .Net applications, 6 of them totally 4.4 million lines of code and some 35K+ classes between them. We are getting lots of interesting information but the design analysis does not seem to be working at all. The tangle index is zero for all of projects and when we open up the design tool for any of them we get a list of all the folders/namespaces in the project but none of them have any dependancies on any of the other folders/namespaces.Any ideas on how to debug this? I looked through the logs but obviously with projects this size, unless I really know what I am looking for, grepping logs is needle-in-haystack work.This is using SQ 5.1 with the 4.0 version of the C# plugin and v 1.2 of the analysis bootstrapper for VS projects.
|
SonarQube reports no dependencies, 0 Tangle index, for C# solution with 12K+ classes?
|
I should have taken a deeper look intolint-results.xmlfile. The error is fully explained there. In my case:<?xml version="1.0" encoding="UTF-8"?>
<issues format="4" by="lint 24.1.2">
<issue
id="LintError"
severity="Error"
message="No `.class` files were found in project "debug", so none of the classfile based checks could be run. Does the project need to be built first?"
category="Lint"
priority="10"
summary="Lint Failure" explanation="This issue type represents a problem running lint itself. Examples include failure to find bytecode for source files (which means certain detectors could not be run), parsing errors in lint configuration files, etc.
These errors are not errors in your own code, but they are shown to make it clear that some checks were not completed.">
<location file="C:\Code\Android\TestApp\app\build\intermediates\manifests\androidTest\debug"/>
</issue>So the message is telling me the project has not been completely build, due to a dependencies problem.After solving that error, everything worked fine.
|
I have generatedLintfile results (generally namedlint-results.xml) and configured properly android project inAndroid Studioto run sonar (usingsonar-runner).When I executesonar-runnerI get the next errors:INFO 13:49:02.776 > 13:49:02.776 INFO - Sensor org.sonar.plugins.android.lint.AndroidLintSensor@5d5f10b2
INFO 13:49:02.832 > 13:49:02.832 INFO - Processing android lint report: C:\Code\Android\Project\app\lint-results.xml
INFO 13:49:03.477 > 13:49:03.475 WARN - Unable to find rule for LintError
[...]
INFO 13:49:03.505 > 13:49:03.505 WARN - Unable to find file C:\Code\Android\Project\app\build\intermediates\exploded-aar\com.google.android.gms\play-services-ads\7.3.0\AndroidManifest.xml to report issue
[...]
INFO 13:49:04.678 > 13:49:04.678 INFO - Sensor org.sonar.plugins.android.lint.AndroidLintSensor@5d5f10b2 (done) | time=1902msWhat can be causing these errors?
|
"LintError" found processing android lint report
|
Well, I've delved into the SonarQube's JavaScript Plugin code to debug it. Found the bug. Looks like this bug only happens on Windows. What the code does is iterates over all the test files, in my case "PersonTest.js" and "dashboard/MonkeyTest.js", and looks for the file "dashboard\MonkeyTest.js". But because "dashboard/MonkeyTest.js" does not equal to "dashboard\MonkeyTest.js" it ignores the results of this test. To be honest iterates over ALL the test files for every test result is inefficient to begin with. Below is the Java method. I'll try to get in contact with the author.protected InputFile getTestFileRelativePathToBaseDir(String fileName) {
for (InputFile inputFile : fileSystem.inputFiles(testFilePredicate)) {
LOG.warn("Slava: '" + inputFile.file().getAbsolutePath() + "'");
if (inputFile.file().getAbsolutePath().endsWith(fileName)) {
LOG.debug("Found potential test file corresponding to file name: {}", fileName);
LOG.debug("Will fetch SonarQube associated resource with (logical) relative path to project base directory: {}", inputFile.relativePath());
return inputFile;
}
}
return null;
}
|
I have a Surefire results directory with 2 files:TEST-Chrome_4202311135_Windows.dashboard.MonkeyTest.xmlandTEST-Chrome_4202311135_Windows.PersonTest.xml. Thus, my tests have the following directory structure:-tests
-PersonTest.js
-dashboard
-MonkeyTest.jsWhen I run Sonar Runner it picks upPersonTest.jsbut it says thatdashboard/MonkeyTest.jsdoesn't exist:18:24:58.747 WARN - Test result will not be saved for test class "dashboard.MonkeyTest", because SonarQube associated resource has not been found using file name: "dashboard/MonkeyTest.js"Has anybody encountered this? Looks to me like a bug because the file is there.
|
Is it a bug in SonarQube's JavaScript plugin that it doesn't pick up Surefire test results of tests that are in a subdirectory?
|
I just wrote an open source SonarQube plugin to take the output of the karma-junit-reporter plugin and allow its output to be populated into SonarQube. You can find it in the here:https://github.com/acwatson/sonar-karma-test-report-plugin
|
Our team writes JavaScript unit tests using Jasmine. We are setting up codebase analysis in SonarQube. The SonarQube JavaScript plugin documentation says that it will use unit test results only in the format that is generated by JS Test Driver. I'm using Karma already for generating the LCOV report but to my surprise I can't find a reporter that generate the collection of TEST-*.xml files that JS Test Driver generates. Please advise.
|
Does there exist a Karma Reporter that generates JS Test Driver format results so that SonarQube can pick them up?
|
It took me about a million years to find this, so I hope it's helpful to someone. This error is caused by updates to the sonar api that cause incompatibility with versions older than 4.5.The solution is to use the updated version of the sonar scala plugin which is available here:https://github.com/1and1/sonar-scalaThis built straight away for me and started analyzing scala without error.
|
I am using SonarQube 5.1 and its running on localhost. It was working out of box for java, but when i added the plugin for scala -http://docs.codehaus.org/display/SONAR/Scala+Plugin(i checked out the code from github, build the jar and then installed in sonarqube installation), now every time i invoke the gradle command sonarRunner - I am getting this error:19:52:55.232 [ERROR] [system.err] ERROR: Unable to execute Sonar
19:52:55.233 [ERROR] [system.err] ERROR: Caused by: Unable to register extension org.sonar.plugins.scala.cobertura.CoberturaSensor
19:52:55.233 [ERROR] [system.err] ERROR: Caused by: org/sonar/plugins/cobertura/api/AbstractCoberturaParser
19:52:55.233 [ERROR] [system.err] ERROR: Caused by: org.sonar.plugins.cobertura.api.AbstractCoberturaParserI tried searching for cause of the issue but could not find anything online. Please help me.
|
Unable to register extension org.sonar.plugins.scala.cobertura.CoberturaSensor
|
On current moment the only options are:Disable this rule at allChange default format on something like:
^[a-zA-Z0-9]+$ (to allow either upper and lowercase letters)It's possible that in future SQ will track JSDoc annotatations (but it's not the case for now):/**
* @constructor
*/
function MyClass() {
this.foo = 'bar';
}
|
I have a very simple javascript constructor function that looks like this:function DisplayedTableData() {
this.rowData = [];
}SonarQube is complaining about this and giving me the error, "Function names should comply with a naming convention", because it starts with a capital letter.But it's a constructor - it's supposed to start with a capital letter!Does anyone know a way to make SonarQube recognise that this is meant to be a constructor? Or a way to disable the rule in this particular case? Or an easy way to fix the rule?Thanks!
|
How to make SonarQube honour javascript constructor function naming conventions
|
With the latest issue page (on version 5.1 of SonarQube) you can search issues by author. Just click on Issues in the top bar and select the author facet. Havea look on nemoto see this feature (and all my issues ;) )
|
I am able to get the name of the developer who committed the culprit line when directly viewing the file, but is it possible to get all issues of a particular developer in a central location?The email address the developer uses to log in to the system is the same as that of the SCM.
|
SonarQube: Get all Issues of a particular user
|
Apparently the correct answer to this is something like: "SQL_Latin1_general_CP1_CS_AS" which the dba found after telling me there wasn't anything like what I was asking for.
|
I may be the only person who has actually read the "requirements" but it specifically states that for SQL Server 2012:(warning) Collation must be case-sensitive (CS) and accent-sensitive (AS)UTF-8 and Language to English. (this is for all databases) The UTF-8 is not an option for SQL Server 2012 but I know we can set that elsewhere.My DBA (who is setting up the database for us) says there are no "English" options for collation and accent-sensitive-ness.Refer to the pagehttp://docs.sonarqube.org/display/SONAR/Requirementsto see what I'm talking about.Should the instructions be updated or am I missing something?
|
Configuration of SonarQube SQL Server 2012 db documentation error?
|
The utility method Arrays.copyOf(T[] original, int newLength) will create a new array with the same objects from the internal array.The issue with return the internal array is usually about preventing unintended changes to the contents of the array, which would be shared any other clients. Sharing the contained objects is not usually of the same order of concern but if you are implementing some sort of map your requirements may be more stringent.
|
Consider thispublic class Data {
private final SomeField[] fields;
.....
public SomeField[] getFields() {
return map == null ? null : map.clone();
}Security - Method returns internal arrayExposing internal arrays directly allows the user to modify some code
that could be critical. It is safer to return a copy of the array.I get that we should not useclone()to copy objects, rather copy the objects usingcopy constructor.But that still copies the internal objects which are references.
What are recommended ways to avoidclone()above?Thanks
|
Returning 'data' may exposed internal array?
|
First:/tmp/testresults.xmlthis has nothing to do with coverage, but with test results import (number of tests, success tests).Do I need binaries for the coverage in SonarQube? I haven't compiled the code.The answer to your question lies in this interrogation : Yes.
In order to compute coverage when reading the .exec JaCoCo report file, JaCoCo analyzer (used in the java plugin) requires the .class file input stream, therefore bytecode is required to import JaCoCo reports. So please compile your project and provide the class files throughsonar.java.binariesproperty.
|
I struggle since days getting JaCoCo report integrated in SonarQube 5.0.1 for our project. Always I read 0.0% coverage in SonarQube.TeamCity 9 generated a testresults.xml and a jacoco.exec file which I use for the sonar runner. TeamCity displays the coverage, so the exec file seams to be okay. And Java code analysis works basically in SonarQube (FindBugs, PMD etc.)I have a multi module project which is still build with Ant. The unit tests for the "core" project are in an own project called "junit". The JUnit 4 library is used, but the tests are still JUnit 3.These are the relevant (?) properties I use in a file called "sonar-project.properties":core.sonar.tests = ../junit/src
core.sonar.junit.reportsPath = /tmp/testresults.xml
core.sonar.core.coveragePlugin = jacoco
core.sonar.jacoco.reportMissing.force.zero = false
core.sonar.jacoco.reportPath = /tmp/jacoco.execThe property prefix "core" is because they are configuring the module "core".Paths should be correct. But it says: "WARN - Reports path not found: /tmp/testresults.xml" The path is correct, I don't know why this warning appears.Do I need binaries for the coverage in SonarQube? I haven't compiled the code.Or what could be the reason that SonarQube displays 0% coverage after I run sonar-runner?
|
SonarQube 5 with JaCoCo 0.0% Coverage, why?
|
This solution is for Subversion and Maven.Install theParameterized Trigger PluginCreate a Maven job for the SonarQube analysis, eg._common-sonarwith these settings:Source Code Management:"Subversion",Repository URL:$PREVIOUS_SVN_URL,Check-out Strategy:"Always check out a fresh copy"Build:Goals and options:installPost-build Actions:"Sonar"For the job you want to run analysis on add aPost-build Action"Trigger parameterized build on other projects"with these settings:Projects to build:_common-sonarAddPredefined parameters:Parameters:PREVIOUS_SVN_URL=${SVN_URL}Now when the job-to-analyse completes it triggers the analysis job. The analysis job checks out the same SVN URL which was used by the first job.This solution works without scripting or copying workspaces but there are quite obvious limitations and non-ideal features:the build command is always onlymvn installthe SVN checkout may be from different revision than original buildcheckout and build are always done from scratchI didn't consider ant at all here.Improvement ideas are quite welcome!Late improvement edit:Instead of using a maven build ( in _common-sonar), you may also use SonarQube directly byinvoking a Standalone SonarQube analysisAdditionally to the SVN URL you can add a parameter for the build tag and project name to use in sonar. Simply addNAME=YOUR_PROJECT_NAMEBUILDTAG=$BUILD_TAGbeneath the PREVIOUS_SVN_URL parameter.In your _common-sonar you can use it with${NAME}and${BUILDTAG}.
|
I have a number of projects that need to be analysed bySONARfromjenkins. These projects includeantandmavenprojects. I have created a separate job for each SONAR analysis in jenkins.Is it possible to have a single jenkins job in which I can pass some parameters from each individual sonar job and then see the dashboard?If so, how do i go about it?
|
Single Jenkins job for SONAR analysis of multiple projects
|
After trying to work a bit with aResourceI was able to save the measures and group them by the requests I got from the Gatling files.It was a lot of try and error I had to do and the documentation by SonarQube is just awful when it comes to reverse engineering.I had to use a deprecated method to index my resources (SensorContext.index(Resource resource)) because I don't know any other way.For example: Though there is a new plugin API (which is declared@Betain the 4.5.1 version of SonarQube) it is not once mentioned in the official plugin documentation and you have to search through the source files to find it. However, I continued working with the old API.To retrieve the measures afterwards in the .html.erb-Template, I used the following code in my widget:m = measure('your_metric_name')
ProjectMeasure.find(:all,
:from => ['project_measures as p, snapshots as s'],
:conditions => ['p.metric_id=? AND s.id = p.snapshot_id
AND s.parent_snapshot_id = ?', m.metric.id, m.snapshot_id]This will return all the measures you made regarding this project (make sure that your resource'sgetParent()method returns the project you are analysing with SonarQube). I saved the category viameasure.setData("category")in Java and was able to categorize them in the widget through this trick.If someone is stuck here too, I will add additional code (especially on how to create a new resource to save your multiple measures). Just comment please.
|
I want to categorize specific metrics I have in SonarQube to fit my needs.In detail: I built a Gatling Plugin for SonarQube that reads the stats which Gatling writes and puts them into SonarQube Metrics.Now I want to categorize my measures according to the requests I did with Gatling.So, for example I have the global stats by Gatling (10,000 requests, 50ms per request, etc.) and I also have the data for the requests (for request 1 there were 1,000 requests, 40ms per request, etc.).How is it possible to assign the request to a measure in Sonar?A possible solution I could think about was to link the measures to specific contexts in Sonar. So, I will save the measures for the requests in a special context while the global stats are saved within the global context.But: how can I access my measures in the Ruby-Template afterwards and what would be a good context to pick?Update:I tried to save the same measure multiple times with the request name as the Measure.data-parameter but that resulted in an error.I also tried changing the resources-Context Sonar saves the measure in. But I did not succeed to query the measures afterwards in the widget, they seemed to have disappeared.
|
Categorize measures in SonarQube
|
Have you enabled any PMD and Checkstyle rules in the Quality Profile you are using to analyse?
|
I recently installed SonarQube 5. And I found that PMD and Checkstyle was not installed.I installed both of them via the update center. But I didn't find a way to activate them in the analyze of the projects.How can I activate PMD and Checkstyle in SonarQube?
|
How to activate PMD and Checkstyle
|
I would suggest adjusting your file structure to your package structure to make things easier to find in the future. That means setting your source folder toCore/src/main/java/and in there creating the folder structure/abc/xyz/annotations.This avoids breaking conventions and makes things far easier to read on top of pacifying Sonar
|
I have a project struture like :MyProject
|
|-Core/src/main/java/Annotations (a source directory)
|
|- abc.xyz.annotations (Package under source directory)
|
|-MyClass.java (1 among the classes)Some how sonar doesnot scan my code under such directory structure. But it does work fine if my directory structure isCore/src/main/javainstead.With the existing project structure I am getting an error saying"The source directory does not correspond to the package declaration abc.xyz.annotations"I have asonar-project.propertiesfile in my root directory of the project with the below entries in it:sonar.modules=Core
Core.sonar.sources=src/main/java/Annotations
sonar.projectName=MyProject
|
The source directory does not correspond to the package declaration
|
You can add// TODOcomments and enable the ruleTODO tags should be handledon your quality profile.Alternatively, you can create a manual issue on the given line from the SonarQube UI (if you have the "Browse" permission on the project).
|
Can I add a code comment that will show a Sonar warning after a Sonar scan?For example, I can put '//NOSONAR' on a line to get sonar to ignore the line.But, could I force a warning message on a line with something like this://SONAR_WARNING Show this message in SonarI just thought it would be useful as a code marker for me to mark certain lines of code with TODO items. Or, is this just a bad idea?
|
Can I add a code comment that will show a Sonar warning after a Sonar scan?
|
//NOSONAR only work on issues. But the root cause of your issue is "every dev had their own local sonar instance". This goes against the SonarQube philosophy and prevent you from settings exclusions. The question then would be: Why don't you have a single central SonarQube server?
|
When a line of code is decorated with a//NOSONARcomment, Sonar seems to correctly ignore specific code quality rules (eg non conforming naming standards).However, code duplication problems are still detected for lines so decorated.Is there a simple way to make Sonar ignore duplication?Note: I don't want to create a special exception on the sonar server, because every dev had their own local sonar instance, so it has to work "everywhere".
|
Sonar not respecting //NOSONAR for duplication
|
If I correctly understand you, you have one shared folder, located on the filesystem at the same level as your projects:Solution.slnProject1\...Project2\...Shared\...If you are using the Visual Studio Bootstrapper plugin, you are always analyzing a multi-module project: Each Visual Studio Project becomes a SonarQube module. A main project (with no sources) is created for the solution itself.There is a limitation in SonarQube: All sources of a module must be located within the module's folder, for example for the computation of relative paths (etc.) to work properly.The "Shared" folder in your case does not belong to any project, and hence cannot be imported in SonarQube.You have several options:Accept that the shared code is not being analyzed in SonarQubeNo longer rely on the Visual Studio Bootstrapper plugin, and analyze the whole solution as a single SonarQube project. But you will then hit other limitations (such ashttps://jira.codehaus.org/browse/SONARFXCOP-36)I would recommend you option 1 for the short term, while waiting for this ticket on the Visual Studio Bootstrapper to no longer create SonarQube modules to be implemented:https://jira.codehaus.org/browse/SONARVS-59
|
I have a Visual Studio / C# solution containing several projects. Some of the projects have links to source code in other directories (shared code that is used in several projects).When running Sonar it seems to work well (although I'm not sure that it actually works!), and when running ReSharper outside Sonar it also works well. However, when running ReSharper from Sonar, then I end up with a lot of
17:44:37.607 INFO - Skipping the ReSharper issue at line 6259 whose file "C:\GitRepos\myProject\Code\Shared.All\Core\StorageSqlCe.cs" is not in SonarQube.
(This is when I'm analysing the C:\GitRepos\myProject\Code\Server\ project)It's not really a multi-module project (since I don't want to analyse all of the Shared.All directory - only the files that are linked from my project (Server in this case).Does anyone know how to deal with this? If I were to ignore what's in each project and do analysis of the Shared.All folder I would fail with ReSharper since I have no VS-project file there...I can't change the project structure of the code. And the design to have shared code in special folders might not be the best, but that is a design that was made a long time ago that we have to live with. So, how can I work with Sonar on this?
|
Sonar+ReSharper with projects containing linked files
|
Check for sonar.inclusions and how it works. This can give you a better idea.
|
Is there any way to scan a single java file using sonar runner.By default all the java files in thescr*. I do not want to exclude all the other files by writing a exclusion. Rather I would like to include only a single file for analysis.
|
How to scan a single file using Sonar Runner
|
You can use the "sonar.inclusions" property, like describedin the documentation.For instance:sonar-runner -Dsonar.inclusions=src/main/java/com/foo/MyClass.java
|
Is there any way to scan a single java file using sonar runner.By default all the java files in thescr. I do not want to exclude all the other files by writing a exclusion. Rather I would like to include only a single file for analysis.
|
Scanning a single file using sonar runner
|
It seems that there has been a feature request at the sonar JIRA but the state was set to "closed" with "won't fix".https://jira.codehaus.org/browse/SONARCS-350On the other hand, if you add a "CustomDictionary.xml" file to the solution root folder, this works automatically.sample CustomDictionary.xml<Dictionary>
<Words>
<Recognized>
<Word>"productname"</Word>
<Word>"companyname"</Word>
</Recognized>
</Words>
</Dictionary>
|
Currently i am executing Fxcop rules as part of the sonar scan. We’ve got a couple of wordings that we need to add into the custom dictionary for FxCop so that don’t get raised as FxCop violations.I have committed CodeAnalysisDictionary.xml in the repository so that developer can changer whenever required and it is versioned.I know we can use /dictionary: argument using fxcopcmd.exe.Is there a way we can achieve the similar result using sonar properties.I am using the below mentioned sonar properties.sonar.fxcop.mode=
sonar.fxcop.installDirectory=C:\\Program Files (x86)\\Microsoft Fxcop 10.0
sonar.fxcop.assemblyDependencyDirectories=C:\\Lib***Any little help here is really appreciated.Thanks,
Santhosh
|
Is there Sonar properties to add custom dictionary in the Fxcop
|
A rule by itself will not appear, it needs to be registered by a plugin.
|
I am using SonarQube 4.2 with sonar-java-plugin-2.2.1.
I am trying to deploy a custom rule based on the BaseTreeVisitor (https://github.com/SonarSource/sonar-examples/blob/master/plugins/java-custom-rules/src/main/java/org/sonar/samples/java/ExampleCheck.java).I am using gradle(not maven) to create jar (containing ExampleCheck) and than I copy this jar to sonarqube-4.2/extensions/plugins.I expected to see ExampleCheck rule (with key nomethod)in the in/active rules after sonar will get up.But no such rule appears. On the pagehttp://docs.sonarqube.org/display/SONAR/Extending+Coding+Rulesis nothing about deployment to the Sonarqube.Is anything on above described deployment wrong? How to deploy ExampleCheck rule to SonarQube 4.2 ?
|
SonarQube Java plugin custom rule - deploy
|
SonarQube will not fetch the source code by itself, the Project Links section is only meant for documentation.The easiest way to have the source code from your repository analyzed periodically is to schedule analysis using a dedicated tool - e.g cron task, Windows scheduled task or even better, continuous integration server.For instance, you can setup a Jenkins job to fetch source code from your SVN repository, build it, run automated tests and finally launch SonarQube Runner.
|
I am working on a project for which I would want to perform quality analysis. I have heard good things aboutSonarQubeand wanted to try it. I have the following setup:SonarQubeis installed along with Sonar Runner for Java on a server. It is configured and ready to go. I have my code residing locally on my machine and remotely on aSVNserver distinct from theSonarQubehost server.I am using Eclipse and have installed Sonar Eclipse. I would want to proceed with scheduled quality analysis on the server and work locally with previews using Sonar Eclipse. At the moment, my biggest problem is how to get my source files analysed by the Sonar Runner.As far as I read in the documentation, I would need to somehow get my code into the respective folder in theSonarQubeProject folder, along with a configuration file. Is there no was to link the project to the remote source files?Looking at some of thedocumentation on linksit would seem that this is possible. Yet I do not understand the differences between, for example,SourcesandDeveloper connections.
|
How to link sources from SVN to be analysed with SonarQube
|
The Sonarqube eclipse plugin is able to present to you the results of your analysis you run with jenkins. The results your are looking for however, are stored in the sonarqube database. So you need to to configure the sonarqube eclipse plugin to connect to the sonarqube-server, not the jenkins-server.Here is how you do the configuration:http://docs.codehaus.org/display/SONAR/Configuring+SonarQube+in+Eclipse
|
I have a question regarding the setup and configuration of SonarQube plugin in Eclipse . We have Sonar plugin version 2.1 installed in Jenkins. It runs analysis every day and I want to configure the Eclipse plugin so that it displays the result from the Jenkins analysis. I don't know if this is possible because I can't find any information about this, the only hope comes from the first answer ofthis question.PS. I apologize if there already is an answer to my question, I couldn't find it.
|
Configure SonarQube Eclipse plugin to visualize the results of analysis from Sonar plugin on Jenkins
|
Just write a script to clean all the class files before build. That is the simplest and the surest way.
|
I am trying t o make sure that the .class file am selected is being generated fro the latest src file. Build is triggered by another mechanism. Hence I want to double check this before executing my task. Currently I am planning to compare the last modified time of src and class fle to make sure that class is being created after the src modification time.I want to know if this is the proper way of doing this? Or there are any other alternatives?I am trying to copy a class file from its location. My application is not going to compile src and generate class files. It just copies a required class file from target to dest. Before making the copy operation, but i want to ensure that class file am copying is the latest one.
|
Is Comparing last modified time stamp of src and class file is the best way to make sure that class file is the latest one?
|
You must first define some alerts on the Quality Profile you're using. For instance : error if critical issues > 0. Then you must install the Build Breaker plugin and each new upcoming SonarQube analysis will fail if there are some critical issues. If you don't manage to make it work could you attach to your question, the SonarQube analysis log file ?
|
Does anyone know any tutorials of how to setup the build breaker plugin on Sonar so that it fails the build after it reaches a certain threshold on critical issues. I tried using the official docs:http://docs.codehaus.org/display/SONAR/Build+Breaker+Pluginbut they don't provide much documentation.
As of now, the build breaker plugin is not running as expected. It gives an alert if there is a new critical issue, but it doesn't break the build.
|
Build Breaker Setup Sonar
|
In order to make the example work in IntelliJ you have to workaround a buggy issue in this IDE:In the pom.xml of the example you have this section :<dependency>
<groupId>org.codehaus.sonar-plugins.java</groupId>
<artifactId>sonar-java-plugin</artifactId>
<type>sonar-plugin</type>
<version>1.5</version>
<scope>provided</scope>
</dependency>(Assuming you don't have maven auto import feature enabled) In order to make it work in IntelliJ you have to comment out the line<type>sonar-plugin</type>and click on the popup to import maven settings and then uncomment the line (but do not reimport settings).
This will make the library available in IntelliJ classpath and thus compiling the project.To answer your other question :There is a breaking change between version 4.1 and 4.2. Thus the break you encounter.
As of when this will be updated, I might give it a shot this week, but no real guarantee on that, as we need to keep some example up for LTS version (3.7).
|
Cloned the examples found herehttps://github.com/SonarSource/sonar-examplesand imported into IntelliJI'm having some problems with the example codeThe imports fails in IntelliJ
import org.sonar.plugins.java.api.JavaFileScanner;
import org.sonar.plugins.java.api.JavaFileScannersFactory;I seems that imports with package org.sonar.plugins.* is not found.
Probably a dependency issue?
In which jar are those classes bundled?running mvn package seems to work, however IntelliJ does not find the classesWhen upgrading sonar-plugin-api from version 4.1 to 4.2, the import org.sonar.api.resources.Java also breaks
-> Running mvn package this time breaks the build with a compilation error(I need 4.2 as that's the version we are running)Has anybody managed to make the examples work?And does anybody when the examples will be updated to 4.2?
|
SonarQube custom java rules
|
on your sonar-properties files set the sonar.cxx.includeDirectories to the folder that contains the header for example:sonar.cxx.includeDirectories=c:\folderofheadersseewikialthough its not necessary to check because it says the same thing.
|
I'm trying to run sonar-runner on a project of mine.Relative to the root of the project directory, I have several subdirectories each which has its own subdirectories which contain the source code.I followed the SonarQube and Sonar-runner documents and got the server and (embedded) database running fine. As a matter of fact, the runner can show me in the SonarQube web interface dashboard some analysis. However, the one I care about the most, "Issues", is missing and I suspect it's because the runner can't findanyheader files while it's executing.All I see during sonar-runner execution iscannot find the sources for '#include <pthread.h>'
cannot find the sources for '#include <time.h>'and so on. It also can't include custom headers.I'm running this with the Coverity and cxx community plugin if that makes a noticeable difference.Note: I ran the example sets for both java and C and they run fine.The commands are in my path so at the root of my project I run:sonar-runner
|
Sonar-runner - cannot find the sources for '#include <pthread.h>'
|
I recommend following the paragraph "Ignore Code Coverage" in this documentation:http://docs.sonarqube.org/display/SONAR/Narrowing+the+Focus
|
How to turn off code coverage in SonarQube 4? I have JMockit usage in unit tests and JaCoCo code coverage plugin in Sonar. They conflict because they use different javaagents to edit bytecode of classes (as I know). I want to switch off code coverage in Sonar. I can exclude my project in settings of Jacoco, but it doesn't help.
|
How to turn off code coverage in SonarQube 4?
|
I add the same issue when i upgrade from sonar 3.5 to 4.2
The quality profile "sonar way" that i was using was "merged" with the new one with 0 rules in quality profile.
I changed it using the new "sonar way" with 47 rules (in my config) and re-run analysis. Then it worked again with relevant results.
I hope it could help
|
I'm using SonarQube 4.0 and when I set a project to be analyzed with All PHP CodeSniffer Rules quality profile, the result is 0 issue and 0,0 days of technical debt.The project I analyze is a PHP Project.The other metrics work well like cyclomatic complexity, comments, duplications.When I use the default quality profile named SonarWay, everything work well but I want to use the other quality profile since it contains a lot more rules.At first glance there is no issues related to that problem in SonarQube PHP Plugin JIRA.
|
Using SonarQube Quality profile All PHP CodeSniffer Rules results in 0 issue and 0,0 days of technical debt
|
You're not missing anything. Feel free to follow and vote forhttp://jira.codehaus.org/browse/SONAR-4367
|
I have a multi-module maven project on which SonarQube analyzes the reactor for me. I created a quality profile and specified an alert on code coverage.The problem is that I do not get an alert when any of my subprojects have a code coverage of less than X percent. On the alert page it is stated:"Only project measures are checked against thresholds. Modules, packages and classes are ignored."I suppose that with modules SonarQube means subprojects / components (of my reactor) and I was wondering why SonarQube does not support this.I think it would be nice to get an alert if any of my subprojects had a code coverage level of less than X percent. Am I missing something?Thanks and best,
Ronald
|
Applying SonarQube alerts on subprojects / components
|
This is currently a limitation in SonarQube. However, it can be done partially.For Checkstyle based rules, you can copysomerules (those that have aCopy Rulebutton;screenshot hereunder "Multiple activation of rules"). I've personally used this for the Comment Pattern Matcher and created a rule that matches TODO comments as INFO severity and another that matches FIXME comments as CRITICAL. As I understand your question, that is what you are looking for. I don't think this is possible forallparameterizable rules, though.Also, for PMD based rules, there isthis blog postwhich describes how to use the XPath rule template in order to create custom PMD rules. This could be a workaround for those PMD based rules that don't have aCopy Rulebutton.The feature we would need is aCopy Rulebutton for every parameterizable rule. AFAIK, this does not exist yet.
|
is there a possibility to duplicate existing checkstyle rules? I want Sonarqube to differ guideline rules.Example:The rule for method complexity should mark the method as [MINOR] when there is more than 10 lines of code per method and as [MAJOR] when there is more than 30 lines of code per method.Maybe there is a particular plugin for this special case?Thanks in advance
|
duplicate sonarqube checkstyle rules
|
Ok, thanks!!!Meanwhile, if anyone is interested, I´m trying to do that with sql scripting...CREATE VIEW lvl3 AS
select c.id, c.rule_id, c.characteristic_order, r.name, r.plugin_rule_key, r.plugin_name, r.language, ce.parent_id
from characteristics c
inner join rules r on c.rule_id=r.id
inner join characteristic_edges ce on c.id=ce.child_id
order by c.rule_id
CREATE VIEW lvl2 AS
select c.id, c.kee, c.name, c.depth, c.characteristic_order, ce.parent_id
from characteristics c
inner join characteristic_edges ce on c.id=ce.child_id
where depth=2 order by id
CREATE VIEW lvl1 AS
select id, kee, name, depth, characteristic_order
from characteristics
where depth=1 order by id
select l3.rule_id as "IdRule", l3.plugin_rule_key as "Name", l3.name as "Descrition", l3.plugin_name "Plugin", l3.language as "Language", l1.name as "Category"
from lvl1 l1
inner join lvl2 l2 on l3.parent_id=l2.id
inner join lvl3 l3 on l2.parent_id=l1.id
order by l3.rule_idThats works fine for me now...... waiting for web service :)Thanks!!!
|
How can I get a list (via webservice or sql query) of all the sonar rules with his category (Maintainability, Efficiency, Reliability...etc)Using xxxxx/api/rules?language=java&plugin=pmd,findbugs :<rule>
<title>Unnecessary Local Before Return</title>
<key>pmd:UnnecessaryLocalBeforeReturn</key>
<config_key>rulesets/design.xml/UnnecessaryLocalBeforeReturn</config_key>
<plugin>pmd</plugin>
<description>Avoid unnecessarily creating local variables</description>
<priority>MAJOR</priority>
</rule>Where is the category shown in the Technical Debt dashboard??Thanks!!!
|
Retrieve sonarqube rules by category
|
Code coverage is recomputed by SonarQube. SonarQube just retrieves from the report whether a line is covered or not by unit tests. Example:DA:10,0 => it means that line 10 is not coveredDA:20,1 => it means that line 20 is coveredDA:30,5 => it means that line 30 is coveredThen SonarQube recomputes the code coverage:Number of covered lines / (Number of covered lines + Number of uncovered lines)
|
I have a Jenkins job that is using the "Invoke standalone Sonar analysis" for a javascript project.I thought it was working fine with the following parameters:sonar.sources=src
sonar.language=js
sonar.dynamicAnalysis=reuseReports
sonar.javascript.jstestdriver.coveragefile=target/test-coverage/jscover.lcov
sonar.javascript.lcov.reportPath=target/test-coverage/jscover.lcovBut then I noticed that the numbers that are being reported in Sonar do not match the number in the lcov file.When I log into to Sonar I see the code coverage number as 30%.But when I examine the lcov file, I get completely different numbers:
$lcov --summary target/test-coverage/jscover.lcov
...
lines......: 48.1%
functions..: 41.7%
branches...: no data foundAnd in fact, when I view the jscover.html report file, I see the total coverage at 48%.
Sonar reports it at 30%.And drilling down into the individual files, Sonar's results do not match the results in the lcov file either.For instance:
Just by looking at a particular file, /src/js/models/Call.js, lcov says it’s at 97% code coverage.
But Sonar displays this:
49.0% by unit tests Line coverage:97.0% (97/100)Branch coverage:0.0% (0/98)It’s as if Sonar is using the Branch Coverage AND the Line Coverage Stats to get the final code coverage results at 49.0%.Do you know what I am doing wrong? Do you know why Sonar is not using the coverage results from the lcov file? Is it because the Branch Coverage has no data?Thanks for any insight on this.
|
Sonar not using lcov file
|
Yes, Sonar can detectNullPointerExceptions (NPEs) thrown by the JVM by using the FindBugs tool under the hood. However, it cannotdo so dynamically at runtime, because FindBugs is astaticanalysis tool.From theFindBugs detectors, choose those with theNP_prefix in their key, such asNP_ALWAYS_NULL. There are roughly 30 such detectors that deal with null pointer analysis.Note that FindBugs works bystaticanalysis of the code. In other words, it does not dynamically "catch" NPEs or somehow perform a simulated run of the code and "catch" NPEs. This would be hard to do because test cases would be required for every possible code path. Instead, FindBugs only analyses the class files using its detectors.So you are not going to findallcases where NPEs can occur, but due to the sheer number of detectors, you are going to catch most. Also, some FindBugs detectors in this field are quite sophisticated, even though there is always room for improvement.Note also that in order to help the detectors do their jobs, you may have to annotate method arguments and return values withnull pointer analysis annotations(alsoin JSR305 here). If you search SO for these annotations, you will find lots of helpful advice on their correct usage in various environments.
|
I would like to ask can sonar find null pointer exception caused by java virtual machine at run time?? if yes please tell me which sonar rule do it for us. I am very much puzzled with it as there are some rules exist in sonar findbugs profile which say sonar catch null pointer exception.
One of findbugs ruleAvoid Throwing Null Pointer Exceptionsay we should avoid throwing null pointer exception.please clarify me on that can sonar catch null pointer exception or not threw by JVM?? OR it can catch only customized null pointer exception(generated by developer) and what these sonar rules meant for(null pointer exception, null pointer dereference etc.) What are the rules to use Sonar?
|
Can sonar catch null pointer exceptions caused by JVM Dynamically
|
No, it's currently not possible.
|
Is it possible to enableSonarQubeto check duplicate code on jUnit tests?
|
Detect duplicate code on tests with sonar
|
You just have to run a new analysis in Eclipse to refresh the issues:http://docs.codehaus.org/display/SONAR/Working+with+SonarQube+in+Eclipse#WorkingwithSonarQubeinEclipse-RunninganAnalysis
|
in the previous versions of the plugin, there used to be a refresh button in the "Sonar Issues" view but since my last upgrade the refresh button seems to have disappeared and I cannot find any replacement.In the project properties, I can see that my last analysis dates back to September whereas on the server the full analysis is done everyday...Any idea about what is going on and how I can refresh the Sonar issues view?
|
How to refresh Sonar issues from Eclipse
|
The solution in the end was simple.Export from MySQL 5.5. (export file is 114 GB)Uninstall MySQL 5.5 (remove all data files)Install MySQL 5.6Import dataExport from MySQL 5.6 (export file is now 13 GB)Uninstall MySQL 5.6 (remove all data files)Install MySQL 5.6Import data
|
I've been using SonarQube/Sonar for a few years now and the measures_data.idb size has grown to a wopping 114GB, yes gig.I've got the default house keeping settings set.I'm using MySql 5.6 (with default per file setting)I'm using Sonar 4.0.I've tried exporting the db from mysql and then importing it again. but its the same size.
It does state..note : Table does not support optimize, doing recreate + analyze instead
status : OKI've deleted a couple of old projects from Sonar's "Bulk Deletion" option, but the file is the same size.Can anyone give me some advice on what to try next?Thanks
Jeff Porter
|
SonarQube : How to reduce size of measures_data.ibd?
|
You'll find the answers to all your questions athttp://docs.codehaus.org/display/SONAR/Differential+Views#DifferentialViews-DifferentialViewsSettings
|
In many reports there is the option to limit the report to a time span. I believe they call it a differential xxx (e.g. filter, dashboard, etc...). In the drop down there are three options: all time, 30 days, or 90 days. Is this customizable? Could it show the last 7 or 14 days? Could is show custom time spans. I would like to be to report on a sprint (we are practicing Agile Scrum). The behavior of developers is rhythmic and it would make the most sense to show reports for a sprint as this is the time span that determines the rhythm.
|
Sonar - Custom Time Changes or Time Span
|
You can follow this thread of discussion:http://sonar.15.x6.nabble.com/Java-compiler-warnings-Generics-td5015634.html
|
Is there a way to include the Java compiler's warnings in SonarQube's analysis and dashboards?I'm running SonarQube via Maven under Jenkins.
|
Can I display compiler warnings in Sonar?
|
In my case the value ofsonar.java.coveragePluginin sonar settings was set to cobertura, so it was just a wrong configuration.Always keep in mind, that one can define global and project specific settings in sonar.
|
We were running a sonar server with an old version (3.4.1) with an embedded H2 database.
While migrating to an oracle databse we were upgrading our sonar server to the most recent version 3.6.2.Upgrade finished successful (except it is not possible to keep the historical data). But after the upgrade was done sonar didn't show the code coverage any more.Using the old sonar instance the coverage analysis still works. We did not change any sonar code coverage settings (leaving it to default: jacoco), just starting the analysis from within Jenkins via the Sonar plugin.Did anyone had the same, a similar problem or any idea how to fix this?
Is there anything new, we have to configure?
|
No code coverage after Sonar upgrade to version 3.6.2
|
Look at the logs - is there an uncaught exception being thrown for failed Crowd authentication attempts? TheCrowdAuthenticatormay need to be fixed to catch them to and returnfalserather than propagating.SONAR-3138appears to have implemented general fallback for all external authentication providers, although there was afix requiredfor the LDAP provider to allow fallback to work. Assuming you're usingsonar-crowd-plugin'sCrowdAuthenticator.javait's possible that a similar bug remains in the Crowd authenticator.Edit: the LDAP authenticator also hasa fullSecurityRealm. This may be necessary to get the fallback behaviour when a user doesn't pass authentication.
|
Sonar supports fallback to the built-in authentication when using LDAP authentication. I expect the same to work for Crowd but somehow this does not seem to be the case. Is this a bug or do I miss some setting?
|
SonarQube: How to configure fallback authentication when using Crowd
|
You have to configure sonar.surefire.reportsPath and sonar.emma.reportPath for each module. This can't be done from command line, so you have to do it in pom.xml of each module.Please note that if you are using default Maven settings I'm quite sure you don't need to specify sonar.surefire.reportsPath and sonar.emma.reportPath at all because SonarQube will look at standard location by default.
|
we have the following structure in our project:maven project 1maven project 2module 1module 2module 3maven project 3Project 1 and 3 have each one unit test and code coverage result file. They are no problem. Project 2 has three unit test and code coverage result files, one for each module.Now I want to show the unit test and code coverage in SonarQube. But I can only configure one result file (sonar.surefire.reportsPath and sonar.emma.reportPath).How can I configure the three files, or do I have to merge the files?
|
SonarQube: Multiple unit test and code coverage result files
|
You can install Apache on the same machine and set reverse proxy.Yourhttp://your-sonar-host.comaddress needs to run on port 80. Apache will forward it to 9000 (sonar runs on port 9000)After installing Apache, open the configuration and type the following:<Location />
ProxyPass http://your-sonar-host.com:9000/
ProxyPassReverse http://your-sonar-host.com:9000/
RequestHeader set X_FORWARDED_PROTO 'https'
SetEnv force-proxy-request-1.0 1
SetEnv proxy-nokeepalive 1
</Location>There is nothing else you need to do.
|
I have just upgraded from Sonar 3.2.1 to Sonar 3.6. I was able to configure Sonar 3.2.1 to use https by placing a jetty.xml file in SONAR_HOME. The same approach does not seem to work for Sonar 3.6 and from looking at the source for org.sonar.application.JettyEmbedder I think the https port is hard-coded to 8443. FYI, The embedded jetty version is 7.6.11.The relevant Sonar FAQ reads thus :Can SonarQube run in HTTPS mode
No. But you can run SonarQube in a standard HTTPS infrastructure using reverse proxy (in this case the reverse proxy must be configured to set the value 'X_FORWARDED_PROTO: https' in each HTTP request header. Without this property, redirection initiated by the SonarQube server will fall back on HTTP).If this is true then Sonar has taken a step backwards security-wise. Is there an alternative way to configure Sonar/Jetty to run on https ?
|
sonar 3.6 https configuration
|
The upgrade from 3.5.1 to 3.6 can indeed last very long - but it will complete. You're facing this limitation:https://jira.codehaus.org/browse/SONAR-4470This is mainly linked to performance issues on JRuby side (DB migration scripts are usually written on Rails side). As you can read in the ticket, we decided to rewrite this migration script in full Java and to provide a SonarQube 3.6.1 fix version.
|
I'm just upgrading our Sonar installation, from v3.5.1 to 3.6, and the process has been running for over two hours. Last log file entry was "Convert 508818 violations to issues" as the process was starting.
Now, the sonar site /setup is still showing "Sonar database is currently upgrading".Is it correct that the upgrade of 500.000 violations to issues takes so much time?
Why does the log file is not being updated?Thanks in advance.
Andreas
|
Upgrate to Sonarqube 3.6 takes over 2 hours! Is it correct?
|
I was looking for the same thing, because I would like our Sonar to catch this too:List myList = new ArrayList();The rule that Dennis S mentions does not apply, since it is meant to catch the following situation (according tohttp://coding.tocea.com/java/gc_unchecked_type_in_generic_call/)StringBuilder myText = new StringBuilder();
...
List<String> myList = new ArrayList<String>();
boolean containsMyText = myList.contains(someText);The code compiles because thecollection.contains()method takes an Object parameter, even for typed collections. But it is an irrelevant check and will always return false, since themyTextobject has the wrong type and can never be added to the typedmyListcollection.From what I have seen, it seems you would have to build a custom rule.
|
I recently introduced sonar to a large legacy project, originally written in java 1.3.We have been gradually migrating code using raw collections etc to use generics. It would be nice to track our progress in sonar, but there does not seem to be an out of the box rule to catch raw collection use.Is there an existing solution, or will I need to create a custom rule in pmd/checkstyle?
|
Sonar rule to catch raw collection types
|
Based on my experience you can fix this by adding this to the plugins section of the pom.xml:<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.6.3.201306030806</version>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
</executions>
</plugin>
|
I have a very weird problem with the Jacoco plugin for Sonar.
I have a multi-maven project were I wrote an "Event" class and an "EventTest" class in Spock.
The Jacoco plugin for Sonar doesn't give me any code coverage for the test I made.
If I put a dummy Junit test in the same package, that is not testing anything, the Jacoco plugin show me a coverage of 100% which the coverage I was expecting from my Spock test.
Has anyone ever had the same problem ?Cheers
Luca
|
Jacoco plugin for Sonar doesn't support Spock test
|
I know in the Sonar dashboard you can exclude source files, but it does not say anything about excluding.classfiles.Following "SONAR - How to exclude packages that is defined under “sonar.test”", a directive like:/path/to/class/dir/**/*.classshould exclude all.classfiles.It should be fairly similr to thesonar.exclusionsAnalysis Parameter.
|
I am importing my full binaries folder which contains binaries of classes I don't want to analyze, as well as tests that I also want to analyze. Despite Sonar documentation stating that the sonar.properties property supports comma separated values, it is incorrect. If I try to include many folders, separating with a comma, only the first folder path will be included in the analysis.I know in the Sonar dashboard you can exclude source files, but it does not say anything about excluding .class files.
|
Sonar, how to exclude binaries
|
If you look at thedocumentation, you'll see that this plugin provides a widget. This means that you have to edit an existing dashboard (or create a new one) to add this widget if you want to see something in Sonar.Also, as mentioned in the documentation, do not forget to configure the plugin (in the settings), if a user and a password are required.
|
I downloaded build-stability-plugin and put it in my plugins folder and re-started the sonar server.I can't see anything in the dashboard of projects related to build-stability-plugin.Is there anything else i have to do in pom.xml file of projects. I don't have any idea to make this working. What i have to do?
|
How to Use build-stability-plugin in sonar
|
With the toolNDependit is immediate (Disclaimer: I am one of the developer of NDepend). You just have to write the code rule://<Name>Forbidden third-party assemblies</Name>
warnif count > 0
from a in ThirdParty.Assemblies.WithNameNotIn(
"Foo1", "Foo2", "Foo3")
select aet voila:
|
I have a client with a fairly large (> 150 solutions) code base. They have a list of approved third party assemblies their developers can use, and they would like to use Sonar to help identify projects that are using assemblies that are not on the approved list.A simple example:My solution references foo.dllFoo.dll is not on the list of approved 3rd party assembliesMy solution's use of foo.dll is reported as a rule violation when I run a Sonar analysisThis seems like a fairly simple requirement, but I am having some difficulty determining how it could best be implemented in Sonar.
|
Monitor 3rd party assembly usage with Sonar
|
We use Jenkins CI with success to do this.First installTFS client.InstallTFS pluginon Jenkins.Configure TFS client on Jenkins settings. Example:C:\Microsoft\TEE-CLC-10.0.0\tf.cmdWork nice with parallel analysis.
|
I want to integrate the sonar-runner with TFS 2010 build for analysis everytime the build is triggered.How to acheive this and Is it possible to run the analysis in parallel with build?
|
Sonar in TFS build
|
Consider upgrading Sonar - the current version is 3.2, and has JaCoCo as it's native code coverage module.Also, seehttps://github.com/SonarSource/sonar-examples/tree/master/projects/code-coverage/utfor lots of examples
|
How do I configure JaCoCo with Sonar 2.3 and Maven 3.0.4?My project is a multi-module Maven project. My top level pom has the following:<sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>After running mvn sonar:sonar I am getting 0% Code Coverage reported in Sonar. I should be seeing at least 50%. Note I do see the jacoco.exec in the target folder of each child project.
|
How do I configure JaCoCo with Sonar
|
Have you tried the Conditional Build Step Plugin ?https://wiki.jenkins-ci.org/display/JENKINS/Conditional+BuildStep+PluginYou can define rules and conditions for a build step.
Keep in mind also that Sonar Can be configured not only as a post build action but as build step as wellhttp://docs.codehaus.org/display/SONAR/Activate+Sonar+on+Jenkins+job
|
We are having some problems with configuring a multi-configuration build
with Sonar.I want to compile and test a project with multiple jdks' (6 and 7) to
make sure the project is functional under both. Additionally I want to
have Sonar execute, however want Sonar to execute on only one of the
builds to avoid executing it multiple times, which would duplicate data
in the Sonar db and waste time.I have set this up as a multi-configuration project, with the two jvms
as an axis, and Sonar as a post build action. This builds and tests
fine, however it seems to execute Sonar on both builds.One problem is what is the definition of a "post build action" on a
multi-configuration project. Is it something that executes after each
configuration, or something that is run once after all configurations
have finished. We have a Git publish action that seems to do what I
expect which is run once after all other configurations have been built,
however sonar appears to be the opposite. Is this a quirk of the Sonar
plugin and what it is doing is not really a "post build action"?Is there any way of configuring a build that would achieve what I want?
|
Sonar executing multiple times in a Multi-Configuration Jenkins build
|
Here at SonarSource, we are analysing our Sonar Eclipse Plugins using a combination of Ant and Maven. Maybe this can help you: here are the sources =>https://github.com/SonarSource/sonar-eclipse
|
Our Eclipse RCP project contains several plugins and has an existing Ant build using PDE build. I want to add Sonar to our build pipeline. I am aware that Sonar supports analyzing Ant builds in general with the Sonar Ant Task. I am looking for someone who has done this already for a multi-plugin Eclipse RCP application. The Sonar report should look like the report of a multi-module Maven project. Are there any templates/build scripts to copy from available?
|
How to analyze multi-plugin Eclipse RCP project with existing Ant build using Sonar?
|
We haven't heard of such a plugin, but if you ever find (or code) one, please let us know on the Sonar user mailing list, thanks!
|
Is there any Sonar plugin to parse velocity templates to check the code quality?I am using Liferay portal and I have lot of Liferay themes which uses velocity templates as template engine. I want to get the metrics for those Liferay themes.I have tried to get the metrics using Sonar, but the problem is they dont parse .vm files. I was successful to get the metrics for Liferay Portlets, but I am stuck with Liferay Themes.
|
Sonar plugin to parse Velocity templates to check code quality
|
It is not possible yet to add Ruby controllers and views at the same time through a Sonar plugin. Currently, when extending Sonar Web interface, you can only:Add a Ruby widget (that will be displayed on a dashboard): this isonlya viewAdd a Ruby web service API: this isonlya controllerAdd a GWT extension: here you can define a controlleranda viewHowever, please note that we will drop GWT support in the future, and replace it with the possibility to define extension points that allow to write both controllers and views in Ruby.So to answer your need, I would advise you to write a widget, like the ones you can see on Sonar source code here:https://github.com/SonarSource/sonar/tree/master/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgetsHTH
|
I have been fiddling with SONAR for some time now, and I would like to extend it to some point. I don't think I will be able to achieve this with a custom plugin but if I would introduce an additional controller and some views - it would get the job done.Now as I understand, MVC model in sonar is written in RUBY, and I have yet to do research on ruby coding, but before I get to that - is my goal reasonable/achievable ?Or can additional views and controllers can be added via plugin extensions ?Basically I just need certain information gathered from sonar DataBase about the project, and displayed in a custom view for additional statistics.Thanks.P.S. I have hard time finding information for sonar development, maybe someone could recommend some forums discussing sonar extension topics ?
|
Sonar (software quality) - extending sonar (controllers and views)
|
You need to have an actual sonar-server installation. And the Analysis for your project must have run once.Before those steps your project can't be found on the server, because your server doesn't know it exists.See:Sonar plugin Eclipse
|
I was trying to analyze a simple java project using sonar.
Following are the things I have done so far:Installed the Sonar2.0 plugin for Eclipse helios 3.6.Installed the Maven plugin for eclipse.After setting up the plugins, I created a simple java project .Then I created the POM.xml file to enable the Maven Dependency In that I have given the GroupId as<ProjectName>and ArtifactId also as<Projectname>Then I tried to associate the project with Sonar (Using right click on Project >> Configure >> Associate with Sonar)Here I am stuck up with a problem. When I selecthttp://localhost:9000as my server and I try to search this project, "project '' with key 'projectname:projectname' not found on server" is displayed as an errorPlease help me to solve this issue.
|
Issue in associating simple java project with sonar-eclipse
|
Out of the box, Sonar can't really do this: it will tell you if the total of lines has changed, but e.g., if you were to remove 1000 lines, change 1000 lines and add 1000 lines, Sonar would see that the total number of lines is the same, so no obvious change (on that metric anyway).You can get some information with theSCM Activity Plugin, and more with Sonar 2.5 (which seems to add better support for differential measures). But I'm not sure if it will be completely what you are looking for; I can't tell what the full set of metrics is. Nonetheless, that's where I would focus effort for improvements if I were you.For a more detailed report on changes of this nature you should be able to get the information directly from your version control system.
|
I would like to know if Sonar has the option to provide the report for lines of code changed/inserted/updated between the given timeframe ?
|
lines of code between time frame in sonar
|
You can match on the leading4., and then take the text after that, but before the next dot character, and parse it as a number.
Then you can check if that number is greater than or equal to 2 and less than or equal to 11./project/parent/version[starts-with(text(), '4.') and number(substring-before(substring-after(text(), '.'), '.')) >= 2 and number(substring-before(substring-after(text(), '.'), '.')) <= 11]
|
I'm writing a custom xml rule for SonarQube with XPath 1.0.The parent version cannot be lower than 4.12.*<?xml version="1.0" encoding="UTF-8"?>
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>xpto.micronaut</groupId>
<artifactId>microservice-bom</artifactId>
<version>4.8.0.RC</version>
</parent>
<groupId>br.com.xpto</groupId>
<artifactId>teste-pipe</artifactId>
<version>1.0.0-SNAPSHOT</version>
<build>
<finalName>${pom.artifactId}-${pom.version}</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.9.0.2155</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>XPath 1.0:/project/parent/version[starts-with(text(), '4.11.')] |
/project/parent/version[starts-with(text(), '4.10.')] |
/project/parent/version[starts-with(text(), '4.9.')] |
/project/parent/version[starts-with(text(), '4.8.')] |
/project/parent/version[starts-with(text(), '4.7.')] |
/project/parent/version[starts-with(text(), '4.6.')] |
/project/parent/version[starts-with(text(), '4.5.')] |
/project/parent/version[starts-with(text(), '4.4.')] |
/project/parent/version[starts-with(text(), '4.3.')] |
/project/parent/version[starts-with(text(), '4.2.')]This XPath works, but would there be a way to simplify it?
|
Range in XPATH 1.0
|
Figured it outHow to enable VSCode Logs for SonarLint?Go toVSCode SettingsUnderExtensions, expandSonarLintEnable Sonarlint › Output: Show Verbose LogsRestart VSCodeThen, go toTerminaland you will see a tab forOutputSelectSonarLintfrom the dropdown (mine defaults toTasks)How do I make it trust the certificate?As it turns out, the self signed certificate indeed needed to have the URL into theAlternative Names. To me, that doesn't make any sense as the browser's behaviour is to first look at theCommon Nameand then go toAlternative Names. But apparently not the case in the VSCode plugin. I created another self-signed SSL certificate with the url into theCommon NameandAlternative Namesand viola - works like a charm now.Hope this helps someone.
|
We have a SonarQube server which is hosted on a private network which can only be accessible via VPN. URL's something like:https://sonar.internalOur server is using a Self Signed SSL certificate and it works well on browsers (you may get a warning but can move past it).However, the issue is that on SonarLint on VSCode, when I try to useConnected Mode, I get the following error:Failed: Certificate for <sonar.internal> doesn't match any of the subject alternative names: [*.internal, other.internal]However, the certificate's common name has this name already; so it should not even go to alternative names.I have two questions:How do I find the logs for the SonarLint within VSCode?How do I make it trust the certificate?PS: I have been on various other posts and there is never anything crystal clear.Thanks in advance
|
SonarLint on VSCode doesn't work with self signed SonarQube server
|
In your case I would useCLI-version of SonarScanneron a separate stage (with different Java version) of your CI pipeline
|
I'm trying to fail my Gradle build in case of critical or blocker warning reported by Sonar.I have a buildscript section with sonar gradle plugin :buildscript {
dependencies {
classpath 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:3.3'
}
}I apply the sonarqube plugin among the other plugins:apply plugin: 'java'
apply plugin: 'org.sonarqube'I have a sonarqube section with properties :sonarqube {
properties {
property 'sonar.host.url', 'http://some.host:8743'
property 'sonar.projectKey', 'some-project'
property 'sonar.login', '${env.SONAR_TOKEN}'
property 'sonar.qualitygate.wait', 'true'
}
}I run sonarqube after unit tests :tasks.withType(Test) {
finalizedBy 'sonarqube'
}And I have such issue :org/sonar/batch/bootstrapper/EnvironmentInformation has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0My project must build on JDK8. Upgrading it to JDK11 is not an option (it’s a vendor constraint, we don’t get to choose the JDK to use).
What can I do to make my build work ?I would hate to split the build in two (1 JDK8 build for compilation & tests + 1 JDK11 build just for Sonar) because that would mean first build can succeed and the other fail.I'm using SonarQube Community Edition Version 9.8 (build 63668).
|
Issue running Gradle build with SonarQube plugin
|
As specified inthis issue, the correct method of specifying exclusions in jacoco-sbt is with thejacocoExcludesvariable. For example:jacocoExcludes := Seq(
"com.test.base.model.TestModel.*"
)Note that this variable supports glob patterns to ignore a package or specific files under the package.
|
I am trying to exclude specific file extension from the raport of jacoco. According to the documentation:https://www.scala-sbt.org/sbt-jacoco/settings.htmlI have to specify
jacocoExcludes. So I did it in that way:jacocoExcludes in Test := Seq(
"**/*.sh"
)but that does not work... I can still any .sh files in raport of jacoco and then in sonar.How can I receive that?
|
Excluding a specific file extension from jacoco using sbt
|
I also asked this question in Codacy's forum (see here). Here is the answer I got:Basically, the SonarLint.xml file should contain all and only the rules that you want to use in your repository.
One of our engineers developed a script that’s going to the public repository codacy-sonar-csharp, fetches all the patterns used by default in Codacy’s Sonar tool, and creates a SonarLint.xml file with them.And here the mentioned script:#!/bin/env bash
container_id=$(docker create codacy-csharp:latest)
codacy_rules_file=/tmp/codacy-rules.json
# get all the rules defined for the tool from inside the docker container
docker cp $container_id:/docs/patterns.json $codacy_rules_file
docker rm $container_id
# obtain all ids of the rules we have enabled by default
rules_ids=$(cat $codacy_rules_file | jq -r '.patterns[] | select (.enabled == true) | .patternId')
cat << EOF > SonarLint.xml
<?xml version="1.0" encoding="UTF-8"?>
<AnalysisInput>
<Rules>
EOF
for rule_id in $rules_ids
do
echo -e "\t<Rule>\n\t\t<Key>$rule_id</Key>\n\t</Rule>\n" >> SonarLint.xml
done
cat << EOF >> SonarLint.xml
</Rules>
</AnalysisInput>
EOF
|
I’d like to disable certain rules for Sonar C# for my Codacy project. According to the SonarQube docs, I have to create an.editorconfigfile, so I did:[*.cs]
dotnet_diagnostic.S121.severity = none
dotnet_diagnostic.S3216.severity = noneHowever, Codacy does not seem to pick up the.editorconfigfile - at least the warnings that should be disabled are still there.What do I have to do to disable certain rules for Sonar C#?Thanks!
|
Disable rule for Sonar C#
|
In your getProduct method, both the parameters are marked as nonNull and in your code you initialized both the parameters to null. There are chances for NullPointerException. Because of that you are getting this sonar issue.Probable solution would be. You can initialize both the variables to empty string instead of null. It might resolve your issue.
|
I get SonarQube error from below code: param 1 and 2 in getProducts() call is marked as "javax.annotation.Nonnull" but null could be passed.Summary summaryForOrg = null;
PoolSummary poolSummary = null;
summaryForOrg = getSummary(); //GET Api call
poolSummary = getPoolSummary(); //GET Api call
// I get an error from SonarCube for parameter 1 and 2 below
products = SummaryUtils.getProducts(summaryForOrg, poolSummary);Below is the signature of getProducts method:public ProductsSummary getProducts(
@Nonnull Summary summary,
@Nonnull PoolSummary poolSummary,
) {
....
}
|
How do I solve SonarCube issue: call is marked "javax.annotation.Nonnull" but null could be passed
|
For safety purposes, always check thatonly expected or allowed commandsare coming fromsys.argv.If anyother command is passed, do not execute those commands.Even if you add the above validation, sonarqube might throw error.In thesonar rule doc, it is mentioned that this rule will be deprecated in future.
|
I want to use the command line arguments for one of my application, But Sonarqube is showing the code issue and recommending to sanitize it. Can anyone suggest how to resolve this ?
Sonarqube is showing issue in this line -execute_from_command_line(sys.argv)I already tried puttingsys.argvin some variable and then using it function calls. But it didn't helped.I am using following versions:Python : 3.9.10Sonar-Scanner : 4.6.2.2472
|
Sonarqube rule| Using command line arguments is security-sensitive for Python Application
|
There are few possibilities to fix the illegal attribute exceptionChange yourencodingmethod intoUTF-8UTF-8 with BOMand others like (UTF-16 LE, UTF-16 LE with BOM, UTF-16 BE, UTF-16 BE with BOM, Western (Windows 1252)) as per your usageTry to re-create the file again by eithercloningthe repo to different location or by copy-paste the file contents inside newly created file.Try to use the RecentSonarqubeversion 9.1Refer hereLink 1&Link 2
|
I have a CI pipeline in Azure DevOps for .net core app. Below is the task list in the job.1] Prepare Analysis Configuration (5.0.0) 2] .NET Core (2.187.0) to restore, build, publish and test 3] Run Code Analysis (5.0.0)Build failing at the “Run Code Analysis” step. Error details below.##[error]java.lang.IllegalArgumentException: Start pointer [line=40, lineOffset=49] should be before end pointer [line=40, lineOffset=49]
|
Project’s Sonarqube scan issue in Azure DevOps
|
The issue is you're using**without telling it where to start and then give a subset of directories.Update tosonar.coverage.jacoco.xmlReportPaths=./**/jacoco.xml
|
As per the documentation it says this property "sonar.coverage.jacoco.xmlReportPaths" supports wildcardshttps://docs.sonarqube.org/latest/analysis/coverage/But if I try to use wildcard like below, it is not working and showing code coverage as '0'.sonar.coverage.jacoco.xmlReportPaths=**/jacoco.xml
If I give absolute path to the jacoco.xml file then only it is working and showing code coverage.
Isn't it supposed to work with wildcards as the documentation says?
|
wildcard support for jacocoxmlreportspath property is not working as expected
|
Since you are required to keep the exception there is no benefit in usingcomputeIfAbsent. The reference documentation states the following:If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.This means that whatever mapping function you define it will only be called when the map does not have the key already. Since you simply want to throw an exception when the key is already available usingcomputeIfAbsentis nonsense.Having said that just keep your code and ignore sonar warning. Keep in mind that sonar analysis is a static one, looking for patterns in your code but that does not always apply to whatever you are trying to do in your code.If an exception would not be mandatory, then you could do something simpler:if (promoRequest.getCharset() != null) {
Map<Character, Integer> map = new HashMap<>();
for (char charsetCharacter : promoRequest.getCharset().toCharArray()) {
map.putIfAbsent(charsetCharacter, 1);
}
}
|
I have written an application that does not allow duplicated characters. My code is just working fine, however sonar says "instead of containsKey use computeIfAbsent". How can I get over the sonar warning?My code is below:if (promoRequest.getCharset() != null) {
Map<Character, Integer> map = new HashMap<>();
for (char charsetCharacter : promoRequest.getCharset().toCharArray()) {
if (map.containsKey(charsetCharacter)) {
throw new BadRequestException(Constants.INCLUDE_MUST_NOT_BE_DUPLICATED);
}
map.put(charsetCharacter, 1);
}
}I have solved problemfor (char charsetCharacter : promoRequest.getCharset().toCharArray()) {
if (!map.containsKey(charsetCharacter)) {
map.put(charsetCharacter, 1);
} else {
throw new BadRequestException(Constants.CHARSET_CHARACTER_INCLUDE_MUST_NOT_BE_DUPLICATED);
}
|
Sonarlint Error says: instead of containsKey use computeIfAbsent
|
After running the command prompt as administrator, I could run the command.
|
FollowingSonarScanner for .NET documentation, I have already installed SonarScanner / SonarQube locally and I can start the service at http://localhost:9000/I have also run this command:dotnet tool install --global dotnet-sonarscannerBut when I run dotnet sonarscanner begin /k:"Project_Scan_1", I got this errorCould not execute because the specified command or file was not found.
Possible reasons for this include:You misspelled a built-in dotnet command.You intended to execute a .NET program, but dotnet-sonarscanner does not exist.You intended to run a global tool, but a dotnet-prefixed executable with this name could not be found on the PATH.
|
Unable to run dotnet sonarscanner begin /k:"project-key" /d:sonar.login="<token>"
|
A bit late but in Eclipse you may:Right click in your project -> SonarLint -> Bind to SonarQube or SonarCloud...After you just need to pass connection information. Automatically the rules from actived quality profiles will be applied.
|
We are usingSonarQube Community Edition Version 7.9.4 (build 35981)on a remote server where we have created few quality profiles for java code. But I want to import these profile and rules to mySonarLintin eclipse so that I will be able to fix issues while writing code eventually saving time and iterations.
Can this be done ?
|
Import quality profile or rules from SonarQube to SonarLint in eclipse
|
The solution is to define the proxy in Variable groups and link that to pipeline.
This way Prepare Analysis Task works perfectly to achieve connection to sonarqube instance through a proxy when we use "Integrate With Maven or Gradle option".For MSBuid and Standalone Scanner options we can use Inline Powershell to define the Sonar_Scanner_opts to use the proxy connection to sonarqube instance
|
Im stuck with this error for a long time now in Prepare Analysis Task in Azure DevOps .Im using a proxy task defined in Inline powershell before this task where i defined -Dhttps.proxyHost and -Dhttps.proxyPort along with Dhttp.proxyHost and -Dhttp.proxyPort which works fine with Msbuild, But unfortunately i recieve this below error when i select Integrate with Maven.Im confused as the proxy points to same sonar instance for MS build and Maven but Msbuild succeeds while Maven Fails##[error][SQ] API GET '/api/server/version' failed, error was: {"code":"ENOTFOUND","errno":"ENOTFOUND","syscall":"getaddrinfo","hostname"
|
Prepare Analysis Task Failing with ##[error][SQ] API GET '/api/server/version' failed only for Maven Integration in Azure Devops
|
I'm not sure if this is what you are doing, but I'll say it anyway. If you are creating submodule1 as 'code' and submodule2 as 'tests', that's a horrible way to organize it. Tests (specifically, unit tests) should be stored with the code that it is testing. Thus, each submodule has src/main/java and src/test/java.Now, that said, it is plausible that you have a 'common-lib' module, and then additional modules that depend on that lib (e.g. application tier). It is highly likely that you run a test at the application-tier and it invokes code in the lib module. But you get no code-coverage credit for that. Jacoco coverage of the lib will be solely based on the tests in the lib. The 'app' tests only give you coverage of the app. This has to do with the instrumentation that happens when jacoco runs - it's only going to instrument the things local to the module it is running in.Yes, there is a jacoco-aggregate report, but this will merge the module reports together - single report of each module. It does NOT give you unified coverage of an app-tier test calling lib methods, etc.Lastly, sonar. I believe as long as you have jacoco files hanging around, the sonar-scanner will make use of them. I think it operates on the raw jacoco.exec file, but may be able to interpret a jacoco-result.xml or jacoco-aggregate.xml. If it is giving you grief, include your pom.xml
|
I have a setup for multi Module module project something like thisModule1|
submodule1
|
submodule2I have written a Junit test in submodule 1 and it's covering the code of submodule 2 also but when I try to see coverage in sonar it's showing 0% for submodule 2 is there any way to show coverage of submodule2 ? Also I can generate aggregated xml report by running mvn clean install jacoco:report-aggregate but how can I feed this aggregated report into sonar ? How to setup pom of module as well as submodules ?
|
Aggregated Sonar report for mutiModule maven Project
|
For anyone finding this later, I found the solution.According tohttps://docs.sonarqube.org/7.9/analysis/scan/sonarscanner/only sonar-scanner version 4.0 is compatible.The docker image with version 4.1 (https://hub.docker.com/layers/sonarsource/sonar-scanner-cli) works fine though.
|
I am running a sonarQube analysis inside my gitlab runner, with the following config:Sonarqube version: Version 7.9.1 (build 27448)Gitlab-ci.yml:Sonarqube:
image:
name: sonarsource/sonar-scanner-cli:latest
entrypoint: [""]
stage: code analysis
variables:
SONAR_TOKEN: $SONAR_API_KEY
SONAR_HOST_URL: $SONAR_URL
script:
- sonar-scanner -Dsonar.qualitygate.wait=false -Dsonar.projectKey=$CI_PROJECT_NAME -Dsonar.python.coverage.reportPaths=coverage.xml -Dsonar.sources=app/ -Dsonar.tests=tests/I am using a Sonarqube instance from my company and cannot change any plug-ins or anything. I am getting the following error from my runner logs:INFO: Waiting for report processing to complete...
INFO: Waiting for report processing to complete...
ERROR: [BUILD BREAKER] API query limit (30) reached. Try increasing sonar.buildbreaker.queryMaxAttempts, sonar.buildbreaker.queryInterval, or both.The report is avaibable at the url that it's trying to reach...Is there a way to disable this plug-in from the commandline or anything else I can do?
|
BUILD BREAKER API query limit (30) reached
|
Naturally, best approach would be to buy Developer edition and forget about this, but there is things we could not overcome.To solve this, I created separate project in SonarQube, where I am doing only PR analysis and, if quality gates fails there - there is huge chance, that data in PR is faulty.Also, I created Powershell script and posted it asgist(it is pretty huge, so I am sharing it via link). In the root, this script will collect all issues in SonarQube project before analysis, then, if quality gates fails - it will collect issues after analysis and use diff to actually find issues and post them to Jira as new bugs, assigned to owner of build (we are using Bamboo and Jira integration).Description of script could be readhere, at my blogas well
|
I am using SonarQube community edition with Bitbucket server (awful combination - everything costs fortune in this combination) and wish to get new Blocker issues, brought in by current analysis. There could be several analysis executed in a row, so all I have is analysis id and quality gate. If quality gate fails, I wish to give my developers not only fact, that this analysis brought in some new Blocker issue, but indicate what is this issue.
So far I tried to useapi/issueto search for them, but there is no way to indicate that I want only new issues (or I do not see it); creation dates are taken from CVS information, updateDate does not match with time when analysis was running.
|
Get new issues in SonarQube brought in by current analysis via API
|
Sonarqube comes with two awesome functionality to group projects under a application (in your case say team).The two functionality are:Applications: An Application is an aggregation of projects into a synthetic project.Portfolios: Portfolio offers an aggregate view of the releasability of all projects in the Portfolio.Note: Both of these two available in Sonarqube Enterprise Edition only.
|
Asked support forum but they are unresponsive:https://community.sonarsource.com/t/how-can-i-get-a-top-level-coverage-report-for-all-my-projects/30286I was looking in the UI and googling but didnt turn anything upI have 2 teams in bitbucket and many projects in eachI just want to generate a csv that includes each sonar project name and the current code coverage of that projectHow do I do this? Can I export this csv/pdf/whatever report that includes projects in both of my organizations?
|
How can I get a top level coverage report for ALL my projects?
|
Lis not valid because you made a change that makes the serialized form of the new version of the class incompatible with the serialized form of the old version. You were supposed to update the value ofserialVersionUIDbut sonarqube detected that you didn't.(Sonar probably does not compare the old and the new version numbers, instead it knows what algorithm IDEs use to generate the version number, and it checks if the id matches its the calculation)Changeprivate static final long serialVersionUID = 18234907734L;Toprivate static final long serialVersionUID = 1L;And don't forget to update it when you change the class structure in some way, like by adding a new field or removing a field.See alsoWhat is a serialVersionUID and why should I use it?
|
Correctness - Class defines a computed serialVersionUID that doesn't equate to the calculated valueThis serializable class defines a serialVersionUID that appears to be a computed value, however the value does not match the computed value, and thus losses it's value as version indicator. Either create a custom value like 1, 2, 3, 4.. etc, or recompute the serialVersionUID using your IDE.Probably referring to the field:private static final long serialVersionUID = 18234907734L;Why 18234907734L isn't valid?
|
Sonarqube error: Class defines a computed serialVersionUID that doesn't equate to the calculated value
|
be aware that sonarqube in branch or pr analysis only displays the difference. Hence that it will not show you coverage information, when you do not have code changes in there.Code and details of code coverage not showing in SonarCloud for .Net solutionexplains this very well.
|
I have integrated Jest with SonarQube, SonarQube execution is getting failure throwing the below error,Error during parsing of generic test execution report '**/reports/test-reporter.xml'. Look at the SonarQube documentation to know the expected XML format.and in SonarQube dashboard getting " Coverage on 0 New Lines to cover"below is my sonar and package.json configurationsonar.projectKey=projectname
sonar.projectVersion=1.0
sonar.sourceEncoding=UTF-8
sonar.branch.name=branchname
sonar.sources=**/src
sonar.tests=**/src/__test__
sonar.test.inclusions=**/src/__test__/*.spec.js
sonar.coverage.exclusions=**/src/__test__/__snapshots__/**
sonar.exclusions=**/src/assets/*
sonar.javascript.lcov.reportPaths=**/output/coverage/jest/lcov.info
sonar.testExecutionReportPaths=**/reports/test-reporter.xml
"jest": {
"verbose" :true,
"notify": true,
"testRegex": "((\\.|/*.)(spec))\\.js?$",
"moduleNameMapper": {
"^.+\\.(css|less|scss|sass)$": "identity-obj-proxy"
},
"moduleDirectories": ["node_modules", "src"],
"transformIgnorePatterns": [
"node_modules/(?!@agm)"
],
"testResultsProcessor": "jest-sonar-reporter",
"automock": false,
"collectCoverage":true,
"coverageReporters": [
"text",
"lcov"
],
"reporters": [
"default"
]
},
"jestSonar": {
"sonar56x": true,
"reportPath": "reports",
"reportFile": "test-reporter.xml",
"indent": 4
},Please suggest me on this. TIA.
|
SonarQube with Jest and react - Coverage on 0 New Lines to cover
|
If anyone is interested, i've developed a rule that does what i was asking for in the question. For now, it was tested only onsonarqube-8.3.1.link to the repo.
|
I am usingSonarQubeand i can't find any rule forJavathat would report reassignment of local variables (optionally also method parameters or class fields, but not in setters of course), or, in other words, force every local variable to beeffectively final.Non compilant examplepublic Car createRedCar() {
Car car = new Car();
car.setColor(Color.RED);
car = makeCool(car); // <- error, car variable was reassigned
// do other irrelevant stuff with car, eg log, dispatch event or whatever
return car;
}Compilant examplepublic Car createRedCar() {
Car car = new Car();
car.setColor(Color.RED);
Car coolCar = makeCool(car); // <- it's ok, because all local variables are effectively final
// do other irrelevant stuff with car, eg log, dispatch event or whatever
return coolCar;
}Another compilant examplepublic Car createRedCar() {
final Car car = new Car();
car.setColor(Color.RED);
final Car coolCar = makeCool(car); // <- it's also ok, but i don't want to force every variable to be final
// do other irrelevant stuff with car, eg log, dispatch event or whatever
return coolCar;
}I don't want to force every variable to have final keyword, just for them to be effectively final OR final.If no default rule for this is present i'm okay with using custom rules and / or plugins, or finally even write one, but someone probably already did this and this is why i'm posting here.I am using sonarqube-7.4, and i am willing to update if it comes with the rule i want.
|
SonarQube - Java - Force local variables to be effectively final
|
First, you have to know that Proparse doesn't give access to every detail of the preprocessor. That said, the methodunit.getMacroGraph()will give you access to the visible part of the preprocessor, so that's a good starting point.
If you're looking for usage of given preprocessor variable, you can search for NamedMacroRef instances pointing to the right MacroDef object (withNamedMacroRef#getMacroDef()#getName()), and the right value.In a old-style for-each loop:for (MacroRef ref : unit.getMacroSourceArray()) {
if ((ref instanceof NamedMacroRef)) {
if ("opts".equalsIgnoreCase(((NamedMacroRef) ref).getMacroDef().getName())
&& "A".equalsIgnoreCase(((NamedMacroRef) ref).getMacroDef().getValue())) {
System.out.println("OPTS variable usage with value 'A' at file " + ref.getFileIndex() + ":" + ref.getLine());
}
}
}On this file:&global-define opts a
&IF "{&opts}" = "A" &THEN
MESSAGE "DEPRECATED CODE".
&ENDIF
&undefine opts
&global-define opts b
&IF "{&opts}" > "A" &THEN
MESSAGE "OK CODE".
&ENDIFThis gives:OPTS variable usage with value 'A' at file 0:2So you don't have access to the expression engine, but I think that the current API is enough for what you want to do.You can then report the issue with SonarQube withOpenEdgeProparseCheck#reportIssue()
|
I am trying to create a custom plugin, based on theRiverside OpenEdge pluginand its version ofProparseto create a rule that valids a &IF preprocessor.This rule needs to verify if the application is using a deprecated value of a&GLOBAL-DEFINElike this:/* "A" is the deprecated value of "opts" so I want to create a new ISSUE here */
&IF "{&opts}" = "A" &THEN
MESSAGE "DEPRECATED CODE".
&ENDIF
&IF "{&opts}" > "A" &THEN
MESSAGE "OK CODE".
&ENDIFFor this rule I extended I tried to do something like this:if (unit.getMacroGraph().macroEventList.stream().noneMatch(macro -> macro instanceof NamedMacroRef
&& ((NamedMacroRef) macro).getMacroDef().getName().equalsIgnoreCase("opts"))) {
return;
}
TokenSource stream = unit.lex();
ProToken tok = (ProToken) stream.nextToken();
while (tok.getNodeType() != ABLNodeType.EOF_ANTLR4) {
if (tok.getNodeType() == ABLNodeType.AMPIF) {
// Verify node.
System.out.println(tok);
}
tok = (ProToken) stream.nextToken();
}But I don't know if its the best way to verify (I did based on the code from other sources) and it's not working because the next node comes as an empty "QSSTRING". I am very new in theProparseworld, any help is appreciated.
|
SonarQube OpenEdge custom rule to verify &IF preprocessor with Proparse
|
You can use REST APIs to do whatever configuration you need to do across your repositories. Refer to the REST API documentation.Shouldn't matter, although I haven't tested it. The SonarQube tasks aren't aware of whether the build source is YAML or visual designer/classic/JSON builds. The underlying tasks and job running architecture is the same. As long as the build is hooked up to a branch policy, it should still work.
|
The company I work on recently purchased SonarQube Enterprise to improve code quality throughout all repositories.I found out that there is a feature that enables SonarQube to comment automatically on PRs targeting a specific branch, and I successfully managed to try that out.Thing is:That configuration is not scalable: I would need to manually configure every repo to follow that ruleThat configuration needs a build pipeline to be defined "old school" on Azure DevOps to work, and we are moving into Pipeline as Code, starting of course with CI (where this takes place)Anyone managed to get the PR commenting working in that scenario? Or, at least, solving the #1 problem?Cheers
|
SonarQube + Azure DevOps + Pipeline as Code - Is it possible?
|
The simpliest way to fix it, was to create a test to check if the object is not nullUsing Kotlin and JUnitval obj = Messages
assertNotNull(obj)
|
In my project I created an object to hold some Constants to be used along the project modules, for example, Success/Error messages, but when I run the Sonar scan, it reports the file with 0% coverage.I tried to test the constants values to check if Sonar would see that as covered, but it didn't, actually it does show theobject Messages {}as not covered, not the lines inside:How can I cover it with tests so Sonar won't report it as 0% covered?
|
Sonar Kotlin Object 0% coverage
|
So, at the end I figured out it's up to Jenkins pipeline, which was causing problems. At the end, I had to modify steps in my Jenkinsfile in order for SonarQube to detect my branches.steps {
script {
slackSend message:"Starting Project Name Full Test Build Version ${VERSION} - ${env.JOB_NAME} ${env.BUILD_NUMBER} (<${env.BUILD_URL}|Open>)", baseUrl: "https://projectname.slack.com/services/hooks/jenkins-ci/", token: "token"
}
echo 'Starting Project Name Full Test Build and Sonar Analysis'
withSonarQubeEnv('Sonar') {
sh 'mvn clean verify -P full-test sonar:sonar -Dsonar.branch.name=$BRANCH_NAME -e --settings ${SETTINGS}'
}
script {
sleep(20)
def qualitygate = waitForQualityGate()
if (qualitygate.status != "OK") {
error "Project Name Full Test Build FAILED due to quality gate failure: ${qualitygate.status}"
}
}
script {
if ($BRANCH_NAME == "master") {
echo 'Starting SNAPSHOT artifact deploy'
sh 'mvn clean deploy -DskipTests -P dist --settings ${SETTINGS}'
}
}
|
I went through the following documentation:https://docs.sonarqube.org/latest/branches/overview/, but I am not able to make SonarQube detect other branches than master branch (I am using a developer edition). I've passed the following parameter as a variable to pom.xml properties:<sonar.branch.name>${git.branch}</sonar.branch.name>.
|
How to make SonarQube detect non-master branches?
|
I dont believe that there is a way. I ended up usingsonarqube.mydomain.com.
|
I have used the helm charts for sonarqubehttps://github.com/helm/charts/tree/master/stable/sonarqubebut I am using istio virtual service instead of ingress.I want to set the base url tomydomain.com/sonarqubeIs that possible with sonarqube?
|
How to set base url for sonarqube?
|
This seems like a memory resource starvation issue. According to:Oracle's Troubleshooting Guide on Memory Leaks, this message is the result of the garbage collector running low on heap memory which causes this exception to be thrown. The link indicates that you can turn this exception off with the '-XX:-UseGCOverheadLimit' switch (and the process will continue to execute with a potential performance penalty).Also, the type of garbage collection may be an issue. Try changing the garbage collector policy with '-XX:+UseConcMarkSweepGC' or '-XX:+UseParallelGC' and running it again.
|
Findbugs Plugin have around 449 rules. Applying all those rules into my existing sonarqube quality profile and started sonar scanning which is taking lots of memory to scan the whole project and also it is throwing error after some time.I am usingSonarqube version: 7.5 and Spotbugs jar version: 3.9.4Set SONAR_SCANNER_OPTS=-Xmx10Gfor Temporary Command Prompt session but facing the issue with Java Heap Space (GC overhead limit exceed)ERROR: Error during SonarQube Scanner execution
ERROR: Can not execute Findbugs
ERROR: Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded
ERROR: Caused by: GC overhead limit exceeded
ERROR:
ERROR: Re-run SonarQube Scanner using the -X switch to enable full debug logging.I expect sonar scanner to work successfully with some selected Spotbugs(Findbugs) rule like vulnerabilities and Malicious rule but its didn't work for limited rule also.
|
Getting error while running sonar scanner with Spotbugs rules for monolithic project?
|
WARN: The Code Coverage report doesn't contain any coverage data for the included files.For troubleshooting hints, please refer tohttps://docs.sonarqube.org/x/CoBh, the .coverage file will be convert to coveragexml during sonarqube end analysis taskRun Unit Tests and Save Results in file "NUnitResults.xml"
packages\NUnit.ConsoleRunner.3.7.0\tools \ nunit3-console.exe --result=NUnitResults.xml "NUnitTestProject1\bin\Debug\NUnitTestProject1.dll"
or, for older NUnit 2
"%ProgramFiles(x86)%\NUnit 2.6.4\bin \nunit-console.exe /result=NUnitResults.xml "NUnitTestProject1\bin\Debug\NUnitTestProject1.dll"Meanwhile,there is a workaround explained in theVSTS extension documentation in "Analysing a .NET solution": in the Additional Properties text area, add the following property:sonar.cs.vscoveragexml.reportsPaths=**/*.coveragexmlYou can also refer to these cases(case1,case2) for details.Here is ablogabout configuring Code Coverage for Dotnet Core based applications using SonarQube and Azure DevOps .
|
I am using azure devops for running a test and trying to integrate sonarqube with it.The issue i am facing is that in the summary part of azure pipeline i am able to view code coverage as 22% but in the sonarqube console i am only able to view code coverage as '-'.There is a warning message that i am seeing when i run 'Run Code Analysis' task in pipeline.
The warning message is WARN: The Code Coverage report doesn't contain any coverage data for the included files.
[Please find the image to view the code coverage displayed in azure pipeline][1]This is the yaml for dot test task- task: DotNetCoreCLI@2
displayName: 'dotnet test'
inputs:
command: test
projects: '**/*Test*.csproj'
arguments: '--configuration $(BuildConfiguration) --collect "Code coverage" '
workingDirectory: '$(System.DefaultWorkingDirectory)'
This is the yaml for copy files task that i am doing right after the dot test task
steps:
- task: CopyFiles@2
displayName: 'Copy Files to: $(Common.TestResultsDirectory)'
inputs:
SourceFolder: '$(Agent.WorkFolder)\_temp'
TargetFolder: '$(Common.TestResultsDirectory)'
Please find the yaml file for Prepare analysis on sonarqube task
displayName: 'Prepare analysis on SonarQube'
inputs:
SonarQube: 'CDA-Sonarqube'
projectKey: Test
projectName: Test
extraProperties: sonar.cs.nunit.reportsPaths
Any help is appreciated.
[1]: https://i.stack.imgur.com/HbZfW.png
|
Code Coverage and Lines of Code are displayed as '-' in sonarqube console
|
Xccov don't generate any coverage data. Xccov can read coverage reports from tool xcodebuild:To get coverage data you should select gather coverage data at your test scheme:At your CI script you can add flag -resultBundlePath to select folder where coverage data will save.Then you can use xccov to get following information:Overall target coverage byxccov view --only-targets report.xccovreportCoverage by filexccov view --files-for-target target_name report.xccovreportCoverage for each functionxccov view --func-
tions-for-file name_or_path report.xccovreportRaw coverage data line by linexccov view --file file_name report.xccovarchiveYou can use--jsonflag to analyze results by script.For more information about xccov you can readman xccovor watch the WWDC sessionWhat's New in TestingSo, xccov give you statistics for functions out the box. If you want more. For example, statistic for statements and branches you can create script by yourself using SourceKit and xccov data. SourceKit can give an information about AST of source code and where statement are located. By the location you can match information about coverage through xccov report.
|
xccov tool generates the unit test coverage report for covered lines of code only. So if example.swift file has 20 lines, and 10 is covered by unit tests the coverage will be 50%.Karma (used in Angular 2 development)creates reportnot just for lines of code covered, but also statements, branches and functions.Is it possible to config xccov, or is there a similar tool to achieve this in iOS development? Thanks!
|
iOS Unit Test Coverage - Sonar Report - xccov
|
Even i am facing same scanario. What we are currently doing is we setup build-wrapper utility as indicated athttps://docs.sonarqube.org/latest/analysis/languages/cfamily/.
So, initially it worked fine for a month or so. Later, we start getting following error:====================================================================================
02:36:25.658 INFO: ------------------------------------------------------------------------
02:36:25.658 ERROR: Error during SonarQube Scanner execution
java.lang.IllegalStateException: The "build-wrapper-dump.json" file was found but 0 C/C++/Objective-C files were analyzed. Please make sure that:
* you are using the latest version of the build-wrapper and the SonarCFamily analyzer
* you are correctly invoking the scanner with correct configuration * your compiler is supported
* you are wrapping your build correctly
* you are wrapping a full/clean build
* you are providing the path to the correct build-wrapper output directory====================================================================================So, we have decide to install a backelite plug-in / jar (that handles sonar coverage reports for a mix of Swift and Objective-C) to our sonar server (Enterprise edition) , but, it led to the following error:error message screenshotSo, basically you can set uo build wrapper utility and try performing the sonar scan. Make sure sonar-scanner is installed and you are passing relevant switches to the sonar-scanner command.
|
According to the docs, both the swift and Obj-C sonar scanners want code coverage data and in different ways (build-wrapper vs xccov). But this got me thinking, code coverage is for anentiretarget/project in xcode, not just files for a particularlanguage. So for a mixed Obj-Candswift project, does SonarQube want the same entire-project-xcode-generated coverage data twice (once per scanner)? If not, how does it relate code coverage for a particular language in a sonar project, or does it not care at all?Only asking this because again, and much to my surprise, the docs for the 2 scanners list different code coverage instructions, leading the user to wonder if each scanner doesn't expect the data to be mixed together like it is with xcode and a mixed obj-c swift project (i.e. its thesamedata)
|
sonarqube mixed obj-c swift project, how scan is done for code coverage
|
I had the same problem, and finally solved it by deleting old .sonar folders and pointing to the correct one.I end with different '.sonar' folder (where the scan is stored). The issue was that I was generating the scan in a different folder from where it was parsing it for the report.Configuration in file 'sonar-project.properties':sonar.cfamily.build-wrapper-output=../.sonarCommand to execute the scan (since I'm working on macos):build-wrapper-macosx-x86 --out-dir ../.sonar xcodebuild [PARAMS]Make sure both relative paths (../.sonar) are pointing to the same absolute path.It worked for me, hope it does for you.
|
I am using SonarQube for objc and have some problems with the rule "objc:S819 – Functions should be declared explicitly". It seems Sonar does not find the path to header files, so the prototypes defined in header file is not visible. How to fix this error?dispatch_async(dispatch_get_main_queue(), ^{});Critical issue - Make the prototype of this function visible at this point.SonarQube Version 6.7.3 (build 38370)Quality Profile - Sonar WayPlease let me know for more informationAnyone know about the solution please help.Thanks
|
SonarQube Objective-C rule "Functions should be declared explicitly" Not working
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.