Giter Site home page Giter Site logo

sonarsource / sonar-dotnet Goto Github PK

View Code? Open in Web Editor NEW
717.0 54.0 221.0 134.88 MB

Code analyzer for C# and VB.NET projects

Home Page: https://redirect.sonarsource.com/plugins/csharp.html

License: GNU Lesser General Public License v3.0

Java 2.09% C# 82.18% Shell 0.01% Batchfile 0.01% PowerShell 0.13% HTML 4.73% PureBasic 0.01% Smalltalk 0.01% Makefile 0.01% Python 0.01% CSS 0.10% JavaScript 0.22% Liquid 0.04% F# 0.25% Visual Basic .NET 10.16% ASP.NET 0.01% XSLT 0.04%
c-sharp sonarqube static-analysis static-analyzer static-code-analysis code-quality language-team roslyn visual-basic

sonar-dotnet's Introduction

Code Quality and Security for C# and VB.NET

Build Status

Product Quality Gate Coverage
Analyzer Quality Gate Coverage
Plugin Quality Gate Coverage

Static analysis of C# and VB.NET languages in SonarQube, SonarCloud and SonarLint code quality and security products. These Roslyn analyzers allow you to produce Clean Code that is safe, reliable, and maintainable by helping you find and correct bugs, vulnerabilities, and code smells in your codebase.

Features

Useful public resources

Nuget.org packages

Integration with SonarQube and SonarCloud

Do you have a question or feedback?

Get started

How to contribute

There are many ways you can contribute to the sonar-dotnet project. When contributing, please respect our Code of Conduct.

Join the discussions

One of the easiest ways to contribute is to share your feedback with us (see give feedback) and also answer questions from our community forum. You can also monitor the activity on this repository (opened issues, opened PRs) to get more acquainted with what we do.

Pull Request (PR)

If you want to fix an issue, please read the Get started pages first and make sure that you follow our coding style.

Before submitting the PR, make sure all tests are passing (all checks must be green).

  • We suggest you do not pick issues with the Area: CFG label (they are difficult, can have many side effects and are less likely to be accepted).
  • We suggest you do not implement new rules unless they are already specified for C# and/or VB.NET on our rules repository.

Note: Our CI does not get automatically triggered on the PRs from external contributors. A member of our team will review the code and trigger the CI on demand by adding a comment on the PR (see Azure Pipelines Comment triggers docs):

  • /azp run Sonar.Net - It will run the full pipeline, including plugin tests and promotion

Join us

If you would like to work on this project full-time, we are hiring!

Custom Rules

To request new rules, Contact us on our Community Forum.

If you have an idea for a rule but you are not sure that everyone needs it, you can implement your own Roslyn analyzer.

Configuring Rules

SonarQube / SonarCloud and SonarLint in Connected Mode

Open the rule in SonarQube / SonarCloud, scroll down, and (in case the rule has parameters), you can configure the parameters for each Quality Profile the rule is part of.

Use SonarLint Connected Mode to connect to SonarQube and SonarCloud.

SonarLint

The easiest way is to configure a Quality Profile in SonarCloud.

  • Create a dummy repository and analyze it in SonarCloud (it's free for open-source).
  • Configure the Quality Profile in SonarCloud for the project you created.
  • Then connect SonarLint to that project, and it will download the configuration (ruleset and SonarLint.xml files) locally and update your project based on the Quality Profile.

Standalone NuGet

The rules from standalone NuGet packages can be enabled or disabled in the same way as the other analyzers based on Roslyn, by using the .globalconfig or .editorconfig files. See: https://learn.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2022#set-rule-severity-in-an-editorconfig-file

If the rules are parameterized, the parameter values can be changed using SonarLint.xml additional files.

The first step is to create a new file, named SonarLint.xml, that has the following structure:

<?xml version="1.0" encoding="utf-8"?>
<AnalysisInput xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Settings>
    <Setting>
      <Key>sonar.cs.analyzeGeneratedCode</Key>
      <Value>false</Value>
    </Setting>
  </Settings>
  <Rules>
    <Rule>
      <Key>S107</Key>
      <Parameters>
        <Parameter>
          <Key>max</Key>
          <Value>2</Value>
        </Parameter>
      </Parameters>
    </Rule>
  </Rules>
</AnalysisInput>

Then, update the projects to include this additional file:

<ItemGroup>
  <AdditionalFiles Include="SonarLint.xml" />
</ItemGroup>

Internal resources

Build configuration

License

Copyright 2014-2024 SonarSource.

Licensed under the GNU Lesser General Public License, Version 3.0

sonar-dotnet's People

Contributors

alexvictoor avatar andrei-epure-sonarsource avatar antonioaversa avatar bellingard avatar christophe-zurn-sonarsource avatar costin-zaharia-sonarsource avatar cristian-ambrosini-sonarsource avatar csaba-sagi-sonarsource avatar dbmeneses avatar dbolkensteyn avatar dependabot[bot] avatar dinesh-bolkensteyn-sonarsource avatar dmitry-golovinov-sonarsource avatar duncanp-sonar avatar ehartmann avatar godin avatar gregory-paidis-sonarsource avatar henryju avatar lindamartin avatar loic-joly-sonarsource avatar martin-strecker-sonarsource avatar mary-georgiou-sonarsource avatar michalb-sonar avatar pavel-mikula-sonarsource avatar sebastien-marichal avatar tamasvajk avatar tim-pohlmann avatar tomverin avatar valhristov avatar zsolt-kolbay-sonarsource avatar

Stargazers

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

Watchers

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

sonar-dotnet's Issues

Do not execute Coverage Sensor on non C# projects

When analyzing for instance a JS project, and when the C# plugin is installed, we can see in logs:

[INFO] Sensor Coverage Report Import
[INFO] Sensor Coverage Report Import (done) | time=0ms
[INFO] Sensor Coverage Report Import
[INFO] Sensor Coverage Report Import (done) | time=0ms
[INFO] Sensor Unit Test Results Import
[INFO] Sensor Unit Test Results Import (done) | time=1ms
  • First issue is that it is not obvious that this is coming from the C# plugin.
  • Second issue is that it looks Coverage report sensor is executed twice (while in fact it is once for UTs and once for ITs)
  • Last issue is that the Sensor should probably not appear in logs when project do not contains any C# file (or VB.NET when it is used in the VB.NET plugin)

Initial ticket: SONARCS-641

Fix 1450: False positive in VS2017 but not VS2015

The following code raises a warning (S1450) within VS2017 but not VS2015. We need to investigate what's creating this behavior and then fix it.

public class PrivateFieldUsedAsLocalVariable
{
  private readonly string _a; // FP - S1450

  public PrivateFieldUsedAsLocalVariable(string a)
  {
    _a = a;
  }

  public string GetValue()
  {
    return _a;
  }
}

Feed metric 'executable_lines_data' when SQ >= 6.2

As a replacement of the "force coverage to zero" feature, the plugin should provide for every executable file a measure that will tell platform what are executable lines (ie lines to cover by tests).

Note that the metric was introduced before 6.2 but due to an issue, measure should only be provided when runtime is 6.2+.

Contributes to MMF-739

Update S1144: Rule should handle unused internal types

The current implementation only raises an issue on private unused types but should also raise an issue on internal ones The proposed approach is to effectively raise on unused internal types but to skip types where the assembly defines at least one InternalsVisibleToAttribute attribute.

RSPEC also needs to be updated.

Contributes to MMF-820: SonarC#: fill the gap with FXCop (Step 4)

Implements RSPEC-1144: Unused "private" methods should be removed

Ability to associate several rules to one single DiagnosticAnalyzer

We start having some rules which closely relate to each other relate either because they are raising very similar issues (see #165) or because they depends upon the same engine (see #176 Symbolic execution engine should be executed once and only once).

In both cases, the capability to have one DiagnoticAnalyzer covering several rules would be a perfect solution.

Symbolic execution engine should be executed once and only once

For the timebeing, each rule based on dataflow analysis executes by itself the symbolic execution engine, so 5 rules -> 5 executions and tomorrow 15 rules -> 15 executions. This will quickly lead to a big performance hotspot.

The solution might depends upon our ability to associate several rules to one DiagnosticAnalyzer (depends upon #177).

Rule S2681: Expand implementation for additional patterns

This rule implementation should also catch the following patterns:

if(condition) firstActionInBlock(); secondAction();  // Noncompliant; secondAction executed unconditionally

if(condition) firstActionInBlock();  // Noncompliant
  secondAction();  // Executed unconditionally

Rule S3928: Check ArgumentException instantiations for argument names

void Method(int a, int b)
{
    throw new ArgumentException("My error message", "c"); // Noncompliant 
    throw new ArgumentException("My error message", "c", innerException); // Noncompliant 
    throw new ArgumentException("a", "My error message"); // Noncompliant
    throw new ArgumentException("My error message", "a"); // Compliant
    throw new ArgumentException("My error message", "a", innerException); // Compliant
}

See https://msdn.microsoft.com/en-us/library/2ek3h5bz(v=vs.110).aspx

See https://code-cracker.github.io/diagnostics/CC0002.html

Implements RSPEC-3928

Protobuf files should use OS casing constraint for paths

Since default windows file system is not case sensitive, path to projects may not have the same character case in VS project configuration and in the file system.

In such case, the ".pb" files that are generated during the execution of MSBuild uses path to source files that are not matching exactly the file system.

It impact the SonarQube analysis because the link between the information contained in these ".pb" files and the sources files is broken.

To reproduce:

  • create a solution and a project
  • the case of some folders / file names in the file system
  • run the analysis of your solution

Add support for pattern matching in conditions in CFG

Code like this should be correctly analyzed

public void Patterns(object o)
{
    if (o is null)
    {
        return;
    }

    if (o is int i)
    {
        Console.WriteLine(i);
    }
}

Apart from if statements, the other language elements that should support pattern matching are:
ternary operators, for loops, while loops, do loops

Switch statements are handled in the referenced ticket #1775

False positive on Nullable<bool> checks S2583

The following code generates a false positive:

bool? x = null;
if (x == true)
{
}
else if (x == false) // FP
{
}

The problem is that we set a true or false constraint on SV_x when a constraint is set on x == true, however there's a third option that the x == true is false due to x being null, and == being the lifted operator.

Support many coverage reports

In SonarQube 6.2, the concept of coverage type (unit/IT/overall) was dropped. Instead a plugin can save multiple coverage reports (with no specific type) per file. As a result, the plugin should be updated.

When the runtime is SonarQube 6.2+ :

  • accept comma separated lists of coverage reports, with no differentiation by type

Contributes to MMF-345

Fix S1144: Unused private members should not report false positives with Unity classes

We should investigate the options:

  • whitelist affected classes, such as https://docs.unity3d.com/ScriptReference/MonoBehaviour.html, docs.unity3d.com/ScriptReference/AssetPostprocessor.html
  • introduce a whitelist parameter which can be set by the user in SQ. Note that the list might be very long, (I'm not sure if there's a limit in SQ for parameter length), and that this rule should work out of the box with SonarLint with no parameters (at least for non Unity projects).

See SONARCS-677 for the full thread of discussion

Fix S1121: Assignments should not be made from within sub-expressions' should ignore chained assignments

For instance, an issue is raised here and should not be:
cPos = curLineStart = 0;

Why? Because this is a not-uncommon practice, and the intent is clear and should not confuse maintainers. Additionally, there's not a lot to be gained by updating it to:

i = 0;
j = 0;
{code}
and it would perhaps be a regression in terms of readability to update it to
{code}
i = 0;
j = i;

Relates to RSPEC-1121 Assignments should not be made from within sub-expressions

RSPEC-2360 fix "compliant solution"

The rule is "Optional parameters should not be used", yet the compliant solution contains an optional parameter:

void Notify(string company, string office = "QJZ")

I assume it was erroneously copied from the noncompliant example.

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

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

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.