如何为SonarQube创建自己的C#自定义规则?

问题描述:

我一直在做一些研究.我发现的是一个很好的示例列表,但使用了其他语言这里.

I've been doing some research on it. What I found is a list of quite nice samples but for other languages here.

我还查看了声纳-点网.但这看起来与其他实现并不相似.

I also looked at sonar-dotnet. But it doesn't look similar to the other implementations.

最后,老实说,也许是我最后的机会,我快速浏览了 FxCop自定义规则,但我不确定哪种方法是正确的.

Finally, and to be honest probably my last chance, I took a quick look at FxCop Custom Rules and I'm not sure what would be the right way.

我想做的只是一个基本的c#规则,可以像由声纳预先定义.

What I'm trying to do is just a basic c# rule that can be reviewed like this predefined by sonar.

我的意思是,使用不兼容的代码兼容的解决方案.

您指向的 sonar-custom-rules-examples 都是用Java编写的,并且将用Java编写的解析器用于各种目标语言.使用

The sonar-custom-rules-examples you pointed at are all written in Java and use parsers written in Java for the various target languages. The sonar-dotnet analyzers for C# and VB.NET are written in C# using the Roslyn framework provided by Microsoft.

如果您想为C#编写自己的自定义规则,那么编写Roslyn分析器绝对是最简单的方法(Roslyn取代了FxCop,现在已经过时了).但是,有数十种免费的第三方Roslyn分析器可用,因此有人可能已经至少编写了您想要的某些规则.看看 NuGet ,以了解可用的内容.

If you want to write your own custom rules for C# then writing a Roslyn analyzer is definitely the easiest way to do it (Roslyn replaced FxCop, which is now obsolete). However, there are dozens of free third-party Roslyn analyzers available, so it's possible that someone has already written at least some of the rules you want. Have a look on NuGet to see what's available.

接下来,您希望Roslyn分析仪引起的问题出现在SonarQube中.如果您使用的是SonarQube(v7.4 +),MSBuild的SonarScanner(v4.4 +)和SonarC#插件(v7.6 +)的较新版本,则由第三方Roslyn分析仪提出的问题将自动出现.被导入为 通用问题 .有关更多信息,请参见文档.

Next, you want issues raised by a Roslyn analyzer to appear in SonarQube. If you are using new-ish versions of SonarQube (v7.4+), the SonarScanner for MSBuild (v4.4+) and the SonarC# plugin (v7.6+), then issues raised by third-party Roslyn analyzers will automatically be imported as generic issues. See the docs for more info.

一般问题有两个重大局限性,就像无法选择要在SonarQube UI中运行的规则一样.如果您想要更全功能的体验(或者如果您使用的是SonarQube的旧版本),则可以使用

Generic issues have a couple of significant limitations, just as not being able to select which rules to run in the SonarQube UI. If you want a more full-featured experience (or if you are using an older version of SonarQube), you can use the SonarQube Roslyn SDK to generate a custom SonarQube plugin that wraps the Roslyn analyzer. Using the SDK is straightforward: it's an exe that you run against the Roslyn analyzer, and it generates a SonarQube plugin jar for you.