参考:
1、https://segmentfault.com/a/1190000008659108
2、https://docs.sonarqube.org/display/DEV/Adding+Coding+Rules
3、https://docs.sonarqube.org/display/DEV/Adding+Coding+Rules+using+Java
4、https://docs.sonarqube.org/display/PLUG/Writing+Custom+Java+Rules+101
有两种方式可以扩展代码规则:但是Java只支持方式1
1、Writing coding rules using Java via a SonarQube plugin
2、Adding XPath rules directly through the SonarQube web interface
Writing coding rules in Java is a six-step process:
- Create a SonarQube plugin.
- Put a dependency on the API of the language plugin for which you are writing coding rules.
- Create as many custom rules as required
- Generate the SonarQube plugin (jar file)
- Place this jar file in the SONARQUBE_HOME/extensions/plugins directory
- Restart SonarQube server
下面详述这个过程:
1、把项目拉到本地
git clone git@github.com:shengulong/sonar-custom-rules-examples.git
2、里面有cobol/java/javascript/php/rpg的自定义规则,我们只关注java的
3、使用intellij idea打开项目java-custom-rules(github上,我已经调试通过)。这是一个maven项目的模板。
4、修改下pom文件:sonar的版本以及对应的java插件版本,这样sonar6.0以上版本都可以用这个插件
1 <properties> 2 <!--<sonar.version>6.3</sonar.version>--> 3 <sonar.version>6.0</sonar.version> 4 <!-- this 6.3 is only required to be compliant with SonarLint and it is required 5 even if you just want to be compliant with SonarQube 5.6 --> 6 <!--<java.plugin.version>4.7.1.9272</java.plugin.version>--> 7 <java.plugin.version>4.5.0.8398</java.plugin.version> 8 <sslr.version>1.21</sslr.version> 9 <gson.version>2.6.2</gson.version> 10 </properties>
5、修改下文件,因为最初下载的报编译错误