Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SONARPY-2371 Move the custom rule examples to sonar-python repository #2179

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions docs/LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
MIT No Attribution

Copyright 2023, SonarSource SA

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
20 changes: 20 additions & 0 deletions docs/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>org.sonarsource.python</groupId>
<artifactId>python</artifactId>
<version>4.24-SNAPSHOT</version>
</parent>

<artifactId>docs</artifactId>
<packaging>pom</packaging>

<name>SonarQube Python :: Documentation</name>

<modules>
<module>python-custom-rule-examples</module>
</modules>

</project>
86 changes: 86 additions & 0 deletions docs/python-custom-rule-examples/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>org.sonarsource.python</groupId>
<artifactId>docs</artifactId>
<version>4.24-SNAPSHOT</version>
</parent>

<artifactId>python-custom-rule-examples</artifactId>
<packaging>sonar-plugin</packaging>

<name>SonarQube Python :: Documentation :: Custom Rules Example</name>
<description>Python custom rule examples for SonarQube</description>

<properties>
<sonar.python.version>3.15.0.9787</sonar.python.version>
</properties>
<dependencies>
<dependency>
<groupId>org.sonarsource.sonarqube</groupId>
<artifactId>sonar-plugin-api</artifactId>
<version>7.9</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.sonarsource.python</groupId>
<artifactId>sonar-python-plugin</artifactId>
<type>sonar-plugin</type>
<version>${sonar.python.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.sonarsource.python</groupId>
<artifactId>python-checks-testkit</artifactId>
<version>${sonar.python.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.sonarsource.sonar-packaging-maven-plugin</groupId>
<artifactId>sonar-packaging-maven-plugin</artifactId>
<version>1.21.0.505</version>
<extensions>true</extensions>
<configuration>
<pluginClass>org.sonar.samples.python.CustomPythonRulesPlugin</pluginClass>
<requirePlugins>python:${sonar.python.version}</requirePlugins>
<sonarLintSupported>true</sonarLintSupported>
<skipDependenciesPackaging>true</skipDependenciesPackaging>
</configuration>
</plugin>

<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>com.mycila</groupId>
<artifactId>license-maven-plugin</artifactId>
<configuration>
<licenseSets>
<licenseSet>
<header>${project.basedir}/src/main/resources/license-header.txt</header>
</licenseSet>
</licenseSets>
</configuration>
</plugin>
</plugins>
</build>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright (C) 2011-2024 SonarSource SA - mailto:info AT sonarsource DOT com
* This code is released under [MIT No Attribution](https://opensource.org/licenses/MIT-0) license.
*/
package org.sonar.samples.python;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.sonar.api.server.rule.RulesDefinition;
import org.sonar.api.server.rule.RulesDefinitionAnnotationLoader;
import org.sonar.plugins.python.api.PythonCustomRuleRepository;
import org.sonar.samples.python.checks.CustomPythonSubscriptionCheck;
import org.sonar.samples.python.checks.CustomPythonVisitorCheck;

public class CustomPythonRuleRepository implements RulesDefinition, PythonCustomRuleRepository {

@Override
public void define(Context context) {
NewRepository repository = context.createRepository(repositoryKey(), "py").setName("My custom repo");
new RulesDefinitionAnnotationLoader().load(repository, checkClasses().toArray(new Class[] {}));
Map<String, String> remediationCosts = new HashMap<>();
remediationCosts.put(CustomPythonVisitorCheck.RULE_KEY, "5min");
remediationCosts.put(CustomPythonSubscriptionCheck.RULE_KEY, "10min");
repository.rules().forEach(rule -> rule.setDebtRemediationFunction(
rule.debtRemediationFunctions().constantPerIssue(remediationCosts.get(rule.key()))));

// Optionally override html description from annotation with content from html files
repository.rules().forEach(rule -> rule.setHtmlDescription(loadResource("/org/sonar/l10n/python/rules/python/" + rule.key() + ".html")));
repository.done();
}

@Override
public String repositoryKey() {
return "python-custom-rules";
}

@Override
public List<Class> checkClasses() {
return Arrays.asList(CustomPythonVisitorCheck.class, CustomPythonSubscriptionCheck.class);
}

private String loadResource(String path) {
URL resource = getClass().getResource(path);
if (resource == null) {
throw new IllegalStateException("Resource not found: " + path);
}
ByteArrayOutputStream result = new ByteArrayOutputStream();
try (InputStream in = resource.openStream()) {
byte[] buffer = new byte[1024];
for (int len = in.read(buffer); len != -1; len = in.read(buffer)) {
result.write(buffer, 0, len);
}
return new String(result.toByteArray(), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new IllegalStateException("Failed to read resource: " + path, e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* Copyright (C) 2011-2024 SonarSource SA - mailto:info AT sonarsource DOT com
* This code is released under [MIT No Attribution](https://opensource.org/licenses/MIT-0) license.
*/
package org.sonar.samples.python;

import org.sonar.api.Plugin;

public class CustomPythonRulesPlugin implements Plugin {

@Override
public void define(Context context) {
context.addExtension(CustomPythonRuleRepository.class);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Copyright (C) 2011-2024 SonarSource SA - mailto:info AT sonarsource DOT com
* This code is released under [MIT No Attribution](https://opensource.org/licenses/MIT-0) license.
*/
package org.sonar.samples.python.checks;

import org.sonar.check.Priority;
import org.sonar.check.Rule;
import org.sonar.plugins.python.api.PythonSubscriptionCheck;
import org.sonar.plugins.python.api.tree.ForStatement;
import org.sonar.plugins.python.api.tree.Tree;

@Rule(
key = CustomPythonSubscriptionCheck.RULE_KEY,
priority = Priority.MINOR,
name = "Python subscription visitor check",
description = "desc")
public class CustomPythonSubscriptionCheck extends PythonSubscriptionCheck {

public static final String RULE_KEY = "subscription";

@Override
public void initialize(Context context) {
context.registerSyntaxNodeConsumer(Tree.Kind.FOR_STMT, ctx -> ctx.addIssue(((ForStatement) ctx.syntaxNode()).forKeyword(), "For statement."));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* Copyright (C) 2011-2024 SonarSource SA - mailto:info AT sonarsource DOT com
* This code is released under [MIT No Attribution](https://opensource.org/licenses/MIT-0) license.
*/
package org.sonar.samples.python.checks;

import org.sonar.check.Priority;
import org.sonar.check.Rule;
import org.sonar.plugins.python.api.PythonVisitorCheck;
import org.sonar.plugins.python.api.tree.FunctionDef;

@Rule(
key = CustomPythonVisitorCheck.RULE_KEY,
priority = Priority.MINOR,
name = "Python visitor check",
description = "desc")
public class CustomPythonVisitorCheck extends PythonVisitorCheck {

public static final String RULE_KEY = "visitor";

@Override
public void visitFunctionDef(FunctionDef pyFunctionDefTree) {
addIssue(pyFunctionDefTree.name(), "Function def.");
super.visitFunctionDef(pyFunctionDefTree);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
* Copyright (C) 2011-2024 SonarSource SA - mailto:info AT sonarsource DOT com
* This code is released under [MIT No Attribution](https://opensource.org/licenses/MIT-0) license.
*/
@ParametersAreNonnullByDefault
package org.sonar.samples.python.checks;

import javax.annotation.ParametersAreNonnullByDefault;

Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
* Copyright (C) 2011-2024 SonarSource SA - mailto:info AT sonarsource DOT com
* This code is released under [MIT No Attribution](https://opensource.org/licenses/MIT-0) license.
*/
@ParametersAreNonnullByDefault
package org.sonar.samples.python;

import javax.annotation.ParametersAreNonnullByDefault;

Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Copyright (C) ${license.years} ${license.owner} - ${license.mailto}
This code is released under [MIT No Attribution](https://opensource.org/licenses/MIT-0) license.
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<p>raises an issue on a <code>For statement.</code></p>
<h2>Noncompliant Code Example</h2>
<pre>
TO DO
</pre>
<h2>Compliant Solution</h2>
<pre>
TO DO
</pre>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<p>raises an issue on a <code>For statement.</code> with a visitor on which you can control the visit.</p>
<h2>Noncompliant Code Example</h2>
<pre>
TO DO
</pre>
<h2>Compliant Solution</h2>
<pre>
TO DO
</pre>
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Copyright (C) 2011-2024 SonarSource SA - mailto:info AT sonarsource DOT com
* This code is released under [MIT No Attribution](https://opensource.org/licenses/MIT-0) license.
*/
package org.sonar.samples.python;

import org.junit.Test;
import org.sonar.api.server.rule.RulesDefinition;

import static org.assertj.core.api.Assertions.assertThat;

public class CustomPythonRuleRepositoryTest {

@Test
public void test_rule_repository() {
CustomPythonRuleRepository customPythonRuleRepository = new CustomPythonRuleRepository();
RulesDefinition.Context context = new RulesDefinition.Context();
customPythonRuleRepository.define(context);
assertThat(customPythonRuleRepository.repositoryKey()).isEqualTo("python-custom-rules");
assertThat(context.repositories()).hasSize(1).extracting("key").containsExactly(customPythonRuleRepository.repositoryKey());
assertThat(context.repositories().get(0).rules()).hasSize(2);
assertThat(customPythonRuleRepository.checkClasses()).hasSize(2);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Copyright (C) 2011-2024 SonarSource SA - mailto:info AT sonarsource DOT com
* This code is released under [MIT No Attribution](https://opensource.org/licenses/MIT-0) license.
*/
package org.sonar.samples.python;

import org.junit.Test;
import org.sonar.api.Plugin;
import org.sonar.api.SonarEdition;
import org.sonar.api.SonarQubeSide;
import org.sonar.api.SonarRuntime;
import org.sonar.api.internal.PluginContextImpl;
import org.sonar.api.internal.SonarRuntimeImpl;
import org.sonar.api.utils.Version;

import static org.assertj.core.api.Assertions.assertThat;

public class CustomPythonRulesPluginTest {
@Test
public void test() {
SonarRuntime sonarRuntime = SonarRuntimeImpl.forSonarQube(Version.create(7, 9), SonarQubeSide.SCANNER, SonarEdition.DEVELOPER);
Plugin.Context context = new PluginContextImpl.Builder().setSonarRuntime(sonarRuntime).build();
new CustomPythonRulesPlugin().define(context);
assertThat(context.getExtensions()).hasSize(1);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* Copyright (C) 2011-2024 SonarSource SA - mailto:info AT sonarsource DOT com
* This code is released under [MIT No Attribution](https://opensource.org/licenses/MIT-0) license.
*/
package org.sonar.samples.python.checks;

import org.junit.Test;
import org.sonar.python.checks.utils.PythonCheckVerifier;
import org.sonar.samples.python.checks.CustomPythonSubscriptionCheck;

public class CustomPythonSubscriptionCheckTest {
@Test
public void test() {
PythonCheckVerifier.verify("src/test/resources/checks/customPythonSubscriptionCheck.py", new CustomPythonSubscriptionCheck());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
* Copyright (C) 2011-2024 SonarSource SA - mailto:info AT sonarsource DOT com
* This code is released under [MIT No Attribution](https://opensource.org/licenses/MIT-0) license.
*/
package org.sonar.samples.python.checks;


import org.junit.Test;
import org.sonar.python.checks.utils.PythonCheckVerifier;
import org.sonar.samples.python.checks.CustomPythonVisitorCheck;

public class CustomPythonVisitorCheckTest {
@Test
public void test() {
PythonCheckVerifier.verify("src/test/resources/checks/customPythonVisitorCheck.py", new CustomPythonVisitorCheck());
}
}
Loading