Monday, November 23, 2020

Create Sonar Plugin - Rules definition class

 Rules definition class helps to load the rules to SonarQube. These rules will be shown under "Rules" tab.

  1. FooRulesDefinition implements RulesDefinition
  2. Create repository
  3. load the rules from the xml file -  eg: foo-sonar-rules.xml

------------------------------------------------------------------------------------------------------------

package com.plugin.sonar.language.foo;

import com.plugin.sonar.util.FooConstants;
import org.sonar.api.server.rule.RulesDefinition;
import org.sonar.api.server.rule.RulesDefinitionXmlLoader;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class FooRulesDefinition implements RulesDefinition {


private static String rulesDefinitionFilePath() {
return FooConstants.PATH_TO_RULES_XML;
}

private void defineRulesForLanguage(Context context, String repositoryKey,
                 String repositoryName, String languageKey) {
NewRepository repository = context.createRepository
                (repositoryKey, languageKey).setName(repositoryName);

InputStream rulesXml = this.getClass().getResourceAsStream(rulesDefinitionFilePath());
if (rulesXml != null) {
RulesDefinitionXmlLoader rulesLoader = new RulesDefinitionXmlLoader();
rulesLoader.load(repository, rulesXml, StandardCharsets.UTF_8.name());
}

repository.done();
}

@Override
public void define(Context context) {
defineRulesForLanguage(context,
            FooConstants.REPO_KEY, FooConstants.REPO_NAME, FooConstants.LANGUAGE_KEY);
}
}

-----------------------------------------------------------------------------------

Below is the sample "foo-sonar-rules.xml"

---------------------------------------------------------------------------------

<foo-rules>
<rule>
<key>1</key>
<name>rule name</name>
<internalKey>1</internalKey>
<description>Description of rule 1
</description>
<severity>BLOCKER</severity>
<cardinality>SINGLE</cardinality>
<status>READY</status>
<type>BUG</type>
<tag>foo</tag>
<remediationFunction>CONSTANT_ISSUE</remediationFunction>
<remediationFunctionBaseEffort>2min</remediationFunctionBaseEffort>
</rule>
</foo-rules>

No comments:

Post a Comment